├── .gitignore
├── .idea
├── misc.xml
├── modules.xml
├── python-algorithm-templates.iml
└── vcs.xml
├── DP
├── A_Frog_1.py
├── B_Frog_2.py
├── C_Vacation.py
├── D_Knapsack1.py
├── E_Knapsack2.py
└── readme.md
├── LICENSE
├── LeetCodeList.md
├── LeetCodeSolutions
├── LeetCode_0001.py
├── LeetCode_0002.py
├── LeetCode_0003.py
├── LeetCode_0004.py
├── LeetCode_0005.py
├── LeetCode_0006.py
├── LeetCode_0007.py
├── LeetCode_0008.py
├── LeetCode_0009.cpp
├── LeetCode_0009.py
├── LeetCode_0010.cpp
├── LeetCode_0010.py
├── LeetCode_0011.py
├── LeetCode_0012.py
├── LeetCode_0013.py
├── LeetCode_0014.cpp
├── LeetCode_0014.py
├── LeetCode_0015.cpp
├── LeetCode_0015.py
├── LeetCode_0016.cpp
├── LeetCode_0016.py
├── LeetCode_0017.py
├── LeetCode_0018.py
├── LeetCode_0019.py
├── LeetCode_0020.py
├── LeetCode_0021.py
├── LeetCode_0022.py
├── LeetCode_0023.py
├── LeetCode_0024.py
├── LeetCode_0025.py
├── LeetCode_0026.py
├── LeetCode_0027.py
├── LeetCode_0028.py
├── LeetCode_0029.py
├── LeetCode_0030.py
├── LeetCode_0031.py
├── LeetCode_0032.cpp
├── LeetCode_0032.py
├── LeetCode_0033.py
├── LeetCode_0034.cpp
├── LeetCode_0034.py
├── LeetCode_0035.cpp
├── LeetCode_0035.py
├── LeetCode_0036.py
├── LeetCode_0037.py
├── LeetCode_0038.py
├── LeetCode_0039.py
├── LeetCode_0040.py
├── LeetCode_0041.cpp
├── LeetCode_0042.py
├── LeetCode_0043.cpp
├── LeetCode_0043.py
├── LeetCode_0044.cpp
├── LeetCode_0045.py
├── LeetCode_0046.cpp
├── LeetCode_0046.py
├── LeetCode_0047.py
├── LeetCode_0048.cpp
├── LeetCode_0048.py
├── LeetCode_0049.py
├── LeetCode_0050.py
├── LeetCode_0051.cpp
├── LeetCode_0051.py
├── LeetCode_0052.py
├── LeetCode_0053.py
├── LeetCode_0054.cpp
├── LeetCode_0054.py
├── LeetCode_0055.py
├── LeetCode_0057.cpp
├── LeetCode_0058.py
├── LeetCode_0059.py
├── LeetCode_0060.cpp
├── LeetCode_0061.py
├── LeetCode_0062.cpp
├── LeetCode_0062.py
├── LeetCode_0063.cpp
├── LeetCode_0063.py
├── LeetCode_0064.cpp
├── LeetCode_0064.py
├── LeetCode_0065.cpp
├── LeetCode_0065.py
├── LeetCode_0066.py
├── LeetCode_0067.cpp
├── LeetCode_0067.py
├── LeetCode_0069.py
├── LeetCode_0070.cpp
├── LeetCode_0070.py
├── LeetCode_0071.py
├── LeetCode_0072.py
├── LeetCode_0073.py
├── LeetCode_0074.py
├── LeetCode_0075.py
├── LeetCode_0076.py
├── LeetCode_0077.py
├── LeetCode_0078.py
├── LeetCode_0079.py
├── LeetCode_0080.py
├── LeetCode_0081.py
├── LeetCode_0082.py
├── LeetCode_0083.py
├── LeetCode_0084.py
├── LeetCode_0085.cpp
├── LeetCode_0085.py
├── LeetCode_0086.py
├── LeetCode_0088.py
├── LeetCode_0089.py
├── LeetCode_0090.py
├── LeetCode_0091.py
├── LeetCode_0092.cpp
├── LeetCode_0093.py
├── LeetCode_0094.py
├── LeetCode_0095.cpp
├── LeetCode_0095.py
├── LeetCode_0096.cpp
├── LeetCode_0096.py
├── LeetCode_0097.cpp
├── LeetCode_0098.py
├── LeetCode_0100.py
├── LeetCode_0101.py
├── LeetCode_0102.py
├── LeetCode_0103.py
├── LeetCode_0104.py
├── LeetCode_0105.py
├── LeetCode_0106.py
├── LeetCode_0107.py
├── LeetCode_0108.cpp
├── LeetCode_0108.py
├── LeetCode_0109.py
├── LeetCode_0110.py
├── LeetCode_0111.py
├── LeetCode_0112.cpp
├── LeetCode_0112.py
├── LeetCode_0114.py
├── LeetCode_0116.py
├── LeetCode_0117.py
├── LeetCode_0118.py
├── LeetCode_0119.py
├── LeetCode_0120.cpp
├── LeetCode_0120.py
├── LeetCode_0121.py
├── LeetCode_0122.cpp
├── LeetCode_0122.py
├── LeetCode_0123.py
├── LeetCode_0124.cpp
├── LeetCode_0124.py
├── LeetCode_0125.cpp
├── LeetCode_0125.py
├── LeetCode_0126.cpp
├── LeetCode_0127.py
├── LeetCode_0128.cpp
├── LeetCode_0129.py
├── LeetCode_0130.py
├── LeetCode_0131.py
├── LeetCode_0133.py
├── LeetCode_0134.cpp
├── LeetCode_0134.py
├── LeetCode_0135.cpp
├── LeetCode_0136.py
├── LeetCode_0138.py
├── LeetCode_0139.cpp
├── LeetCode_0139.py
├── LeetCode_0140.py
├── LeetCode_0141.py
├── LeetCode_0143.py
├── LeetCode_0144.py
├── LeetCode_0145.py
├── LeetCode_0146.py
├── LeetCode_0147.py
├── LeetCode_0148.cpp
├── LeetCode_0148.py
├── LeetCode_0149.py
├── LeetCode_0150.py
├── LeetCode_0151.py
├── LeetCode_0152.py
├── LeetCode_0153.cpp
├── LeetCode_0154.cpp
├── LeetCode_0154.py
├── LeetCode_0155.py
├── LeetCode_0156.py
├── LeetCode_0157.cpp
├── LeetCode_0158.cpp
├── LeetCode_0159.py
├── LeetCode_0160.py
├── LeetCode_0161.cpp
├── LeetCode_0162.cpp
├── LeetCode_0163.py
├── LeetCode_0164.cpp
├── LeetCode_0165.py
├── LeetCode_0166.py
├── LeetCode_0167.py
├── LeetCode_0168.py
├── LeetCode_0169.py
├── LeetCode_0170.py
├── LeetCode_0171.cpp
├── LeetCode_0172.cpp
├── LeetCode_0173.py
├── LeetCode_0174.py
├── LeetCode_0175.sql
├── LeetCode_0176.sql
├── LeetCode_0178.sql
├── LeetCode_0179.py
├── LeetCode_0181.sql
├── LeetCode_0182.sql
├── LeetCode_0183.sql
├── LeetCode_0184.sql
├── LeetCode_0186.py
├── LeetCode_0187.cpp
├── LeetCode_0188.py
├── LeetCode_0189.py
├── LeetCode_0190.py
├── LeetCode_0191.py
├── LeetCode_0193.sh
├── LeetCode_0195.sh
├── LeetCode_0197.sql
├── LeetCode_0198.py
├── LeetCode_0199.cpp
├── LeetCode_0199.py
├── LeetCode_0200.py
├── LeetCode_0201.py
├── LeetCode_0202.py
├── LeetCode_0203.py
├── LeetCode_0204.cpp
├── LeetCode_0204.py
├── LeetCode_0205.py
├── LeetCode_0207.py
├── LeetCode_0208.py
├── LeetCode_0209.cpp
├── LeetCode_0209.py
├── LeetCode_0210.py
├── LeetCode_0211.cpp
├── LeetCode_0213.py
├── LeetCode_0214.cpp
├── LeetCode_0215.cpp
├── LeetCode_0215.py
├── LeetCode_0217.py
├── LeetCode_0219.py
├── LeetCode_0220.py
├── LeetCode_0221.py
├── LeetCode_0222.cpp
├── LeetCode_0222.py
├── LeetCode_0223.py
├── LeetCode_0224.cpp
├── LeetCode_0225.py
├── LeetCode_0226.py
├── LeetCode_0228.py
├── LeetCode_0229.py
├── LeetCode_0230.py
├── LeetCode_0231.cpp
├── LeetCode_0232.py
├── LeetCode_0233.py
├── LeetCode_0234.py
├── LeetCode_0235.py
├── LeetCode_0236.py
├── LeetCode_0237.py
├── LeetCode_0239.py
├── LeetCode_0240.py
├── LeetCode_0241.cpp
├── LeetCode_0242.py
├── LeetCode_0243.cpp
├── LeetCode_0246.cpp
├── LeetCode_0249.py
├── LeetCode_0250.cpp
├── LeetCode_0252.py
├── LeetCode_0253.py
├── LeetCode_0256.cpp
├── LeetCode_0257.py
├── LeetCode_0258.cpp
├── LeetCode_0259.cpp
├── LeetCode_0261.py
├── LeetCode_0263.py
├── LeetCode_0266.cpp
├── LeetCode_0267.cpp
├── LeetCode_0268.py
├── LeetCode_0269.py
├── LeetCode_0270.py
├── LeetCode_0273.py
├── LeetCode_0276.cpp
├── LeetCode_0278.py
├── LeetCode_0279.py
├── LeetCode_0281.py
├── LeetCode_0283.cpp
├── LeetCode_0283.py
├── LeetCode_0285.cpp
├── LeetCode_0285.py
├── LeetCode_0286.py
├── LeetCode_0287.py
├── LeetCode_0288.py
├── LeetCode_0289.cpp
├── LeetCode_0289.py
├── LeetCode_0290.py
├── LeetCode_0292.py
├── LeetCode_0293.cpp
├── LeetCode_0295.py
├── LeetCode_0297.cpp
├── LeetCode_0297.py
├── LeetCode_0298.cpp
├── LeetCode_0299.cpp
├── LeetCode_0300.py
├── LeetCode_0301.py
├── LeetCode_0303.cpp
├── LeetCode_0306.py
├── LeetCode_0307.py
├── LeetCode_0309.cpp
├── LeetCode_0309.py
├── LeetCode_0310.py
├── LeetCode_0312.cpp
├── LeetCode_0315.cpp
├── LeetCode_0315.py
├── LeetCode_0318.cpp
├── LeetCode_0319.py
├── LeetCode_0322.py
├── LeetCode_0326.cpp
├── LeetCode_0326.py
├── LeetCode_0327.cpp
├── LeetCode_0327.py
├── LeetCode_0328.cpp
├── LeetCode_0328.py
├── LeetCode_0329.cpp
├── LeetCode_0332.py
├── LeetCode_0333.cpp
├── LeetCode_0336.py
├── LeetCode_0339.cpp
├── LeetCode_0340.cpp
├── LeetCode_0342.cpp
├── LeetCode_0343.py
├── LeetCode_0344.py
├── LeetCode_0346.py
├── LeetCode_0347.py
├── LeetCode_0349.py
├── LeetCode_0350.cpp
├── LeetCode_0350.py
├── LeetCode_0352.py
├── LeetCode_0354.py
├── LeetCode_0355.py
├── LeetCode_0357.cpp
├── LeetCode_0359.py
├── LeetCode_0365.py
├── LeetCode_0367.cpp
├── LeetCode_0371.py
├── LeetCode_0374.py
├── LeetCode_0375.py
├── LeetCode_0380.py
├── LeetCode_0381.py
├── LeetCode_0382.py
├── LeetCode_0383.py
├── LeetCode_0384.py
├── LeetCode_0387.py
├── LeetCode_0389.cpp
├── LeetCode_0392.cpp
├── LeetCode_0394.py
├── LeetCode_0395.py
├── LeetCode_0398.py
├── LeetCode_0399.cpp
├── LeetCode_0399.py
├── LeetCode_0401.cpp
├── LeetCode_0402.cpp
├── LeetCode_0404.cpp
├── LeetCode_0405.cpp
├── LeetCode_0406.py
├── LeetCode_0408.cpp
├── LeetCode_0409.py
├── LeetCode_0410.cpp
├── LeetCode_0412.py
├── LeetCode_0414.cpp
├── LeetCode_0415.py
├── LeetCode_0416.py
├── LeetCode_0417.py
├── LeetCode_0421.cpp
├── LeetCode_0422.cpp
├── LeetCode_0426.py
├── LeetCode_0428.py
├── LeetCode_0429.py
├── LeetCode_0430.py
├── LeetCode_0434.cpp
├── LeetCode_0436.cpp
├── LeetCode_0441.py
├── LeetCode_0442.py
├── LeetCode_0443.cpp
├── LeetCode_0445.py
├── LeetCode_0447.py
├── LeetCode_0450.py
├── LeetCode_0451.py
├── LeetCode_0452.cpp
├── LeetCode_0454.py
├── LeetCode_0455.cpp
├── LeetCode_0456.py
├── LeetCode_0459.py
├── LeetCode_0460.py
├── LeetCode_0461.py
├── LeetCode_0463.py
├── LeetCode_0470.py
├── LeetCode_0473.py
├── LeetCode_0482.cpp
├── LeetCode_0485.py
├── LeetCode_0486.py
├── LeetCode_0487.cpp
├── LeetCode_0491.py
├── LeetCode_0493.cpp
├── LeetCode_0494.py
├── LeetCode_0495.py
├── LeetCode_0496.py
├── LeetCode_0498.py
├── LeetCode_0500.py
├── LeetCode_0502.py
├── LeetCode_0503.py
├── LeetCode_0504.py
├── LeetCode_0509.py
├── LeetCode_0511.sql
├── LeetCode_0512.sql
├── LeetCode_0514.cpp
├── LeetCode_0516.cpp
├── LeetCode_0518.cpp
├── LeetCode_0529.py
├── LeetCode_0538.py
├── LeetCode_0539.cpp
├── LeetCode_0542.py
├── LeetCode_0543.py
├── LeetCode_0549.py
├── LeetCode_0556.py
├── LeetCode_0557.py
├── LeetCode_0559.py
├── LeetCode_0560.py
├── LeetCode_0561.py
├── LeetCode_0563.py
├── LeetCode_0567.py
├── LeetCode_0572.py
├── LeetCode_0576.cpp
├── LeetCode_0577.sql
├── LeetCode_0584.sql
├── LeetCode_0586.sql
├── LeetCode_0589.py
├── LeetCode_0590.py
├── LeetCode_0595.sql
├── LeetCode_0596.sql
├── LeetCode_0599.py
├── LeetCode_0603.sql
├── LeetCode_0604.cpp
├── LeetCode_0605.py
├── LeetCode_0606.py
├── LeetCode_0616.cpp
├── LeetCode_0617.cpp
├── LeetCode_0621.cpp
├── LeetCode_0622.py
├── LeetCode_0628.cpp
├── LeetCode_0632.py
├── LeetCode_0637.py
├── LeetCode_0647.py
├── LeetCode_0648.cpp
├── LeetCode_0649.py
├── LeetCode_0650.py
├── LeetCode_0651.py
├── LeetCode_0652.py
├── LeetCode_0657.py
├── LeetCode_0658.cpp
├── LeetCode_0661.cpp
├── LeetCode_0662.cpp
├── LeetCode_0666.cpp
├── LeetCode_0673.py
├── LeetCode_0674.cpp
├── LeetCode_0680.py
├── LeetCode_0681.cpp
├── LeetCode_0683.cpp
├── LeetCode_0687.cpp
├── LeetCode_0688.cpp
├── LeetCode_0692.py
├── LeetCode_0695.py
├── LeetCode_0696.py
├── LeetCode_0700.py
├── LeetCode_0701.py
├── LeetCode_0702.py
├── LeetCode_0703.py
├── LeetCode_0704.py
├── LeetCode_0705.py
├── LeetCode_0706.py
├── LeetCode_0707.py
├── LeetCode_0708.py
├── LeetCode_0709.py
├── LeetCode_0714.py
├── LeetCode_0716.cpp
├── LeetCode_0717.py
├── LeetCode_0718.cpp
├── LeetCode_0720.py
├── LeetCode_0724.py
├── LeetCode_0725.py
├── LeetCode_0733.py
├── LeetCode_0738.cpp
├── LeetCode_0739.cpp
├── LeetCode_0739.py
├── LeetCode_0743.py
├── LeetCode_0744.py
├── LeetCode_0746.cpp
├── LeetCode_0747.py
├── LeetCode_0752.py
├── LeetCode_0753.py
├── LeetCode_0763.py
├── LeetCode_0767.cpp
├── LeetCode_0769.cpp
├── LeetCode_0771.py
├── LeetCode_0777.py
├── LeetCode_0778.cpp
├── LeetCode_0785.cpp
├── LeetCode_0787.cpp
├── LeetCode_0788.py
├── LeetCode_0792.cpp
├── LeetCode_0803.cpp
├── LeetCode_0819.py
├── LeetCode_0830.py
├── LeetCode_0831.py
├── LeetCode_0834.py
├── LeetCode_0836.py
├── LeetCode_0837.py
├── LeetCode_0841.py
├── LeetCode_0844.py
├── LeetCode_0845.py
├── LeetCode_0852.cpp
├── LeetCode_0856.py
├── LeetCode_0859.cpp
├── LeetCode_0860.py
├── LeetCode_0861.cpp
├── LeetCode_0868.py
├── LeetCode_0870.py
├── LeetCode_0872.py
├── LeetCode_0876.py
├── LeetCode_0883.cpp
├── LeetCode_0887.py
├── LeetCode_0892.py
├── LeetCode_0901.py
├── LeetCode_0904.cpp
├── LeetCode_0907.py
├── LeetCode_0912.py
├── LeetCode_0914.py
├── LeetCode_0916.cpp
├── LeetCode_0919.cpp
├── LeetCode_0922.cpp
├── LeetCode_0925.py
├── LeetCode_0937.py
├── LeetCode_0941.py
├── LeetCode_0945.py
├── LeetCode_0946.py
├── LeetCode_0947.cpp
├── LeetCode_0953.py
├── LeetCode_0954.cpp
├── LeetCode_0955.py
├── LeetCode_0959.cpp
├── LeetCode_0962.py
├── LeetCode_0963.py
├── LeetCode_0973.cpp
├── LeetCode_0974.py
├── LeetCode_0976.cpp
├── LeetCode_0977.py
├── LeetCode_0983.py
├── LeetCode_0986.py
├── LeetCode_0989.cpp
├── LeetCode_0990.cpp
├── LeetCode_0990.py
├── LeetCode_0991.py
├── LeetCode_0994.py
├── LeetCode_0997.cpp
├── LeetCode_0999.py
├── LeetCode_1002.py
├── LeetCode_1006.cpp
├── LeetCode_1013.py
├── LeetCode_1014.cpp
├── LeetCode_1018.py
├── LeetCode_1019.py
├── LeetCode_1024.py
├── LeetCode_1028.cpp
├── LeetCode_1030.cpp
├── LeetCode_1033.py
├── LeetCode_1035.cpp
├── LeetCode_1038.cpp
├── LeetCode_1041.cpp
├── LeetCode_1056.cpp
├── LeetCode_1057.cpp
├── LeetCode_1059.cpp
├── LeetCode_1062.py
├── LeetCode_1071.py
├── LeetCode_1074.cpp
├── LeetCode_1079.py
├── LeetCode_1080.cpp
├── LeetCode_1081.cpp
├── LeetCode_1082.sql
├── LeetCode_1089.cpp
├── LeetCode_1094.py
├── LeetCode_1095.py
├── LeetCode_1099.py
├── LeetCode_1101.cpp
├── LeetCode_1103.py
├── LeetCode_1109.cpp
├── LeetCode_1111.py
├── LeetCode_1114.py
├── LeetCode_1115.py
├── LeetCode_1116.py
├── LeetCode_1117.py
├── LeetCode_1122.cpp
├── LeetCode_1124.py
├── LeetCode_1134.cpp
├── LeetCode_1135.cpp
├── LeetCode_1135.py
├── LeetCode_1138.py
├── LeetCode_1139.cpp
├── LeetCode_1153.cpp
├── LeetCode_1154.cpp
├── LeetCode_1160.py
├── LeetCode_1162.py
├── LeetCode_1169.py
├── LeetCode_1188.py
├── LeetCode_1190.py
├── LeetCode_1192.py
├── LeetCode_1195.py
├── LeetCode_1198.cpp
├── LeetCode_1202.cpp
├── LeetCode_1207.py
├── LeetCode_1209.cpp
├── LeetCode_1229.py
├── LeetCode_1232.cpp
├── LeetCode_1232.py
├── LeetCode_1236.py
├── LeetCode_1242.py
├── LeetCode_1244.py
├── LeetCode_1245.cpp
├── LeetCode_1246.py
├── LeetCode_1248.cpp
├── LeetCode_1249.py
├── LeetCode_1257.py
├── LeetCode_1260.py
├── LeetCode_1269.cpp
├── LeetCode_1275.cpp
├── LeetCode_1279.py
├── LeetCode_1288.cpp
├── LeetCode_1299.py
├── LeetCode_1300.py
├── LeetCode_1305.py
├── LeetCode_1323.cpp
├── LeetCode_1325.py
├── LeetCode_1333.py
├── LeetCode_1353.py
├── LeetCode_1365.py
├── LeetCode_1372.py
├── LeetCode_1373.py
├── LeetCode_1376.cpp
├── LeetCode_1391.py
├── LeetCode_1410.cpp
├── LeetCode_1419.cpp
├── LeetCode_1428.py
├── LeetCode_1429.py
├── LeetCode_1431.py
├── LeetCode_1441.py
├── LeetCode_1442.py
├── LeetCode_1443.py
├── LeetCode_1444.py
├── LeetCode_1446.py
├── LeetCode_1447.py
├── LeetCode_1448.py
├── LeetCode_1449.py
├── LeetCode_1450.py
├── LeetCode_1451.py
├── LeetCode_1452.py
├── LeetCode_1453.py
├── LeetCode_1455.py
├── LeetCode_1456.py
├── LeetCode_1457.py
├── LeetCode_1458.py
├── LeetCode_1467.cpp
├── LeetCode_1467.py
├── LeetCode_1469.cpp
├── LeetCode_1486.py
├── LeetCode_1487.py
├── LeetCode_1490.cpp
├── LeetCode_1498.py
├── LeetCode_1499.cpp
├── LeetCode_1500.cpp
├── LeetCode_1506.cpp
├── LeetCode_1513.cpp
├── LeetCode_1579.cpp
├── LeetCode_1594.py
├── LeetCode_1606.py
├── LeetCode_1608.py
├── LeetCode_1609.py
├── LeetCode_1610.py
├── LeetCode_1611.py
├── LeetCode_1642.py
├── LeetCode_1643.py
├── LeetCode_1650.cpp
├── LeetCode_1673.py
├── LeetCode_1674.cpp
├── LeetCode_1697.cpp
├── LeetCode_1724.cpp
├── LeetCode_510.py
├── README.md
└── create_readme.py
├── Notes
├── @classmethod 多态总结.md
├── @classmethod 多态总结.pdf
├── Buffon’s Needle 问题.md
├── Buffon’s Needle 问题.pdf
├── CentOS 非root服务器配置.md
├── CentOS 非root服务器配置.pdf
├── DeepGlint AI编程练习赛 对抗性攻击.md
├── DeepGlint AI编程练习赛 对抗性攻击.pdf
├── LeetCode 0406 根据身高重建队列.md
├── LeetCode 0406 根据身高重建队列.pdf
├── LeetCode 1074 元素为目标值的子矩阵数量.md
├── LeetCode 1130 叶值的最小代价生成树.md
├── Python property 介绍.md
├── Python property 介绍.pdf
├── [CV] Anchor-Free Target Assignment 高斯核半径.md
├── [CV] Anchor-Free Target Assignment 高斯核半径.pdf
├── [CV] Rotated IoU 如何计算带旋转矩形之间的重叠面积.md
├── [CV] Rotated IoU 如何计算带旋转矩形之间的重叠面积.pdf
├── 古董键盘题解.md
├── 古董键盘题解.pdf
├── 快速幂和矩阵快速幂.md
├── 快速幂和矩阵快速幂.pdf
├── 快速计算灰度图 bounding box 内部的方差.md
├── 快速计算灰度图 bounding box 内部的方差.pdf
├── 感知机建模及对偶形式.md
├── 感知机建模及对偶形式.pdf
├── 找实习的记录.md
├── 支持向量机.md
├── 最小二乘法解的矩阵形式.md
├── 最小二乘法解的矩阵形式.pdf
├── 树状数组归并排序应用计算数组的小和.md
├── 树状数组归并排序应用计算数组的小和.pdf
├── 欧拉通路回路和一笔画问题.md
├── 欧拉通路回路和一笔画问题.pdf
├── 深度学习中需要的矩阵计算.md
├── 深度学习中需要的矩阵计算.pdf
├── 组合数学常用公式.md
├── 组合数学常用公式.pdf
├── 统计学习方法概论.md
├── 统计学习方法概论.pdf
├── 记录一次失败的字节跳动面试.md
├── 记录一次失败的字节跳动面试.pdf
├── 零神模拟面试总结.md
└── 零神模拟面试总结.pdf
├── README.md
├── data_structures
├── __init__.py
├── binarytree.py
├── fenwicktree.py
├── hashmap.py
├── hashset.py
├── heap.py
├── linkedlist.py
├── trietree.py
└── union_find.py
├── design
├── CircularQueue.py
├── LFU_Cache.py
├── LRU_Cache.py
└── SerializeAndDeserializeBinaryTree.py
├── geometry
├── angular_sweep.py
├── chech_two_line_intersection.py
├── check_circle_rectangular_overlap.py
├── maximum_points_in_a_line.py
├── rectangler_in_rectangr.py
└── rotate_iou.py
├── graph
├── dijkstra.py
└── kruskal.py
├── maths
├── Buffon_needle.py
├── Euclidean_algorithm.py
├── Josephus_problem.py
├── LeetCode 面试题05.04 下一个数(位运算).md
├── Reservoir_sampling.py
├── bezouts.py
├── catalan_number.py
├── compute_square_root.py
├── fast_pow_and_matrix_multi.py
├── find_prime_in_N.py
└── 快速幂和矩阵快速幂.md
├── search and sort
├── Boyer_Moore_vote.py
├── binary_search.py
├── effect_of_partition.py
├── partitions.py
├── quickselect_algorithm.py
└── sorting_algorithms.py
├── string
├── KMP.py
├── LCS.py
├── LSwithoutRC.py
└── regular_expression_matching.py
├── 其他面试题
├── A中彩票的概率.py
├── DNA改造.py
├── README.md
├── 删除回文子数组.py
├── 士兵分组.py
├── 异或.py
├── 携程水族馆的小海豚.py
├── 最小客服数量.py
├── 查询等差数组.py
├── 矩阵最小绝对值之和.py
├── 表达式组合.py
├── 装备掉落.py
├── 订单分配.py
└── 骰子的类别和个数.py
├── 剑指Offer
├── No_03.py
├── No_04.py
├── No_05.py
├── No_06.py
├── No_07.py
├── No_09.py
├── No_10_1.py
├── No_10_2.py
├── No_11.py
├── No_12.py
├── No_13.py
├── No_14_1.py
├── No_14_2.py
├── No_15.py
├── No_16.py
├── No_17.py
├── No_18.py
├── No_19.py
├── No_20.py
├── No_21.py
├── No_22.py
├── No_24.py
├── No_25.py
├── No_26.py
├── No_27.py
├── No_28.py
├── No_29.py
├── No_30.py
├── No_31.py
├── No_32_1.py
├── No_32_2.py
├── No_32_3.py
├── No_33.py
├── No_34.py
├── No_35.py
├── No_36.py
├── No_37.py
├── No_38.py
├── No_39.py
├── No_40.py
├── No_41.py
├── No_42.py
├── No_43.py
├── No_44.py
├── No_45.py
├── No_46.py
├── No_47.py
├── No_48.py
├── No_49.py
├── No_50.py
├── No_51.py
├── No_52.py
├── No_53_1.py
├── No_53_2.py
├── No_54.py
├── No_55_1.py
├── No_55_2.py
├── No_56_1.py
├── No_56_2.py
├── No_57_1.py
├── No_57_2.py
├── No_58_1.py
├── No_58_2.py
├── No_59_1.py
├── No_59_2.py
├── No_60.py
├── No_61.py
├── No_62.py
├── No_63.py
├── No_64.py
├── No_65.py
├── No_66.py
├── No_67.py
├── No_68_1.py
└── No_68_2.py
├── 机器学习
└── precepton.py
└── 程序员面试金典
├── No_01_01.cpp
├── No_01_02.cpp
├── No_01_03.cpp
├── No_01_04.cpp
├── No_01_05.cpp
├── No_01_06.cpp
├── No_01_06.py
├── No_01_07.py
├── No_01_08.cpp
├── No_01_09.cpp
├── No_02.08.cpp
├── No_02_01.cpp
├── No_02_02.cpp
├── No_02_03.cpp
├── No_02_04.cpp
├── No_02_05.cpp
├── No_02_06.cpp
├── No_02_07.cpp
├── No_03_01.cpp
├── No_03_02.cpp
├── No_03_03.cpp
├── No_03_04.cpp
├── No_03_05.cpp
├── No_03_06.cpp
├── No_04_01.cpp
├── No_04_02.cpp
├── No_04_03.cpp
├── No_04_04.cpp
├── No_04_05.cpp
├── No_04_06.cpp
├── No_04_08.cpp
├── No_04_10.py
├── No_04_12.py
├── No_05_01.py
├── No_05_02.py
├── No_05_03.py
├── No_08_01.py
├── No_08_03.py
├── No_08_04.py
├── No_08_08.cpp
├── No_08_09.cpp
├── No_08_11.cpp
├── No_10_01.py
├── No_10_05.py
├── No_10_11.cpp
├── No_16_01.cpp
├── No_16_03.py
├── No_16_05.cpp
├── No_16_06.cpp
├── No_16_07.py
├── No_16_08.cpp
├── No_16_10.cpp
├── No_16_11.cpp
├── No_16_18.cpp
├── No_17_08.cpp
├── No_17_13.cpp
├── No_17_18.py
├── No_17_22.cpp
├── No_17_24.py
├── No_17_26.cpp
└── Noe_17_14.cpp
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/DP/A_Frog_1.py:
--------------------------------------------------------------------------------
1 | def min_cost(n, heights):
2 | inf = 1e9
3 | if n == 1:
4 | return 0
5 | dp = [inf] * n
6 | dp[0] = 0
7 | dp[1] = abs(heights[1] - heights[0])
8 | for i in range(2, n):
9 | dp[i] = min(dp[i - 1] + abs(heights[i] - heights[i - 1]),
10 | dp[i - 2] + abs(heights[i] - heights[i - 2]))
11 | return dp[-1]
12 |
13 |
14 | if __name__ == '__main__':
15 | n = int(input())
16 | heights = [int(_) for _ in input().split()]
17 | print(min_cost(n, heights))
18 |
--------------------------------------------------------------------------------
/DP/B_Frog_2.py:
--------------------------------------------------------------------------------
1 | n, k = [int(_) for _ in input().split()]
2 | h = [int(_) for _ in input().split()]
3 | inf = 1e9
4 | dp = [inf] * n
5 | dp[0] = 0
6 | for i in range(1, n):
7 | cnt = 1
8 | while cnt <= k and i - cnt > -1:
9 | dp[i] = min(dp[i], dp[i - cnt] + abs(h[i] - h[i - cnt]))
10 | cnt += 1
11 | print(dp[-1])
12 |
--------------------------------------------------------------------------------
/DP/C_Vacation.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | h = []
3 | for _ in range(n):
4 | h.append(list(map(int, input().split())))
5 |
6 | res = h[0]
7 | for i in range(1, n):
8 | tmp = res[:]
9 | for j in range(3):
10 | res[j] = h[i][j] + max(tmp[(j + 1) % 3], tmp[j - 1])
11 | print(max(res))
12 |
--------------------------------------------------------------------------------
/DP/D_Knapsack1.py:
--------------------------------------------------------------------------------
1 | n, w = map(int, input().split())
2 | elems = []
3 | for _ in range(n):
4 | elems.append(list(map(int, input().split())))
5 | res = [0] * (w + 1)
6 | for item in elems:
7 | for j in range(w, item[0] - 1, -1):
8 | res[j] = max(res[j], res[j - item[0]] + item[1])
9 |
10 | print(res[-1])
11 |
--------------------------------------------------------------------------------
/DP/E_Knapsack2.py:
--------------------------------------------------------------------------------
1 | n, w = map(int, input().split())
2 | elems = []
3 | for _ in range(n):
4 | elems.append(list(map(int, input().split())))
5 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0001.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def twoSum(self, nums: List[int], target: int) -> List[int]:
6 | res = {}
7 | for idx, num in enumerate(nums):
8 | if target - num not in res:
9 | res.update({num: idx})
10 | else:
11 | return [res[target - num], idx]
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0003.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def lengthOfLongestSubstring(self, s: str) -> int:
3 | if not s:
4 | return 0
5 | cnt = 0
6 | sldwin = []
7 | for idx, v in enumerate(s):
8 | if v not in sldwin:
9 | sldwin.append(v)
10 | else:
11 | i = sldwin.index(v)
12 | cnt = len(sldwin) if len(sldwin) > cnt else cnt
13 | sldwin.append(v)
14 | sldwin = sldwin[i + 1:]
15 | cnt = len(sldwin) if len(sldwin) > cnt else cnt
16 | return cnt
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0007.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reverse(self, x: int) -> int:
3 | pos = x >= 0
4 | x = abs(x)
5 | s = list(str(x))
6 | i, j = 0, len(s) - 1
7 | while i < j:
8 | s[i], s[j] = s[j], s[i]
9 | i += 1
10 | j -= 1
11 | # print(s)
12 | res = int(''.join(s))
13 | if not pos:
14 | res = -res
15 | return res if -0x80000000 <= res <= 0x7FFFFFFF else 0
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0009.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool isPalindrome(int x) {
4 | if (x < 0) return false;
5 | if (x < 10) return true;
6 | if (x % 10 == 0) return false;
7 | int r = 0;
8 | while (x > r){
9 | int n = x % 10;
10 | x /= 10;
11 | r *= 10;
12 | r += n;
13 | }
14 |
15 | return r == x || r / 10 == x;
16 | }
17 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0009.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isPalindrome(self, x: int) -> bool:
3 | n = x
4 | if n < 0:
5 | return False
6 | if n == 0: return True
7 | if n % 10 == 0:
8 | return False
9 | tmp = 10
10 | org = n
11 | res = 0
12 | while n:
13 | res = res * 10 + n % tmp
14 | n //= tmp
15 | print(org, res)
16 | return org == res
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0010.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isMatch(self, s: str, p: str) -> bool:
3 | if not p:
4 | return not s
5 | pre = s and p[0] in ['.', s[0]]
6 | if len(p) > 1 and p[1] == '*':
7 | return self.isMatch(s, p[2:]) or pre and self.isMatch(s[1:], p)
8 | else:
9 | return pre and self.isMatch(s[1:], p[1:])
10 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0012.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def intToRoman(self, num: int) -> str:
3 | # greedy algorithm
4 | val = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
5 | nums = ['I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM', 'M']
6 | val, nums = val[::-1], nums[::-1]
7 | res = ''
8 | while num > 0:
9 | for idx, _ in enumerate(val):
10 | if _ <= num:
11 | res += nums[idx]
12 | num -= _
13 | break
14 | return res
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0013.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def romanToInt(self, s: str) -> int:
3 | d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
4 | res = 0
5 | pre = d[s[0]]
6 | i = 1
7 | while i < len(s):
8 | cur = d[s[i]]
9 | if pre < cur:
10 | res -= pre
11 | else:
12 | res += pre
13 | pre = cur
14 | i += 1
15 | res += pre
16 | return res
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0014.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def longestCommonPrefix(self, strs: List[str]) -> str:
6 | if strs == []:
7 | return ''
8 | n = min([len(_) for _ in strs])
9 | if n < 1:
10 | return ''
11 | res = ''
12 | i = 0
13 | while i < n:
14 | s = [_[i] for _ in strs]
15 | tmp = s[0]
16 | s = set(s)
17 | if len(s) == 1:
18 | res += tmp
19 | else:
20 | break
21 | i += 1
22 | return res
23 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0019.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | class ListNode:
3 | def __init__(self, x):
4 | self.val = x
5 | self.next = None
6 |
7 |
8 | class Solution:
9 | def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
10 | left = head
11 | right = head
12 | while n > -1:
13 | if not right:
14 | return head.next
15 | right = right.next
16 | n -= 1
17 |
18 | while right:
19 | left, right = left.next, right.next
20 | left.next = left.next.next
21 | return head
22 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0020.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isValid(self, s: str) -> bool:
3 | pat = {
4 | '(': 1, ')': -1,
5 | '{': 2, '}': -2,
6 | '[': 3, ']': -3
7 | }
8 | stack = []
9 | for _ in s:
10 | tmp = pat[_]
11 | if tmp > 0:
12 | stack.append(tmp)
13 | else:
14 | if not stack:
15 | return False
16 | elif stack[-1] + tmp != 0:
17 | return False
18 | stack.pop()
19 | return not stack
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0024.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | class ListNode:
3 | def __init__(self, x):
4 | self.val = x
5 | self.next = None
6 |
7 |
8 | class Solution:
9 | def swapPairs(self, head: ListNode) -> ListNode:
10 | def helper(node):
11 | if not node:
12 | return None
13 | if not node.next:
14 | return node
15 | tmp = node.next
16 | node.next = helper(node.next.next)
17 | tmp.next = node
18 | return tmp
19 |
20 | return helper(head)
21 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0026.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def removeDuplicates(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: int
6 | """
7 | if len(nums) == 0:
8 | return 0
9 | ans = 1
10 | for i in range(1, len(nums)):
11 | if nums[i] != nums[i - 1]:
12 | nums[ans] = nums[i]
13 | ans += 1
14 | return ans
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0027.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def removeElement(self, nums, val):
3 | """
4 | :type nums: List[int]
5 | :type val: int
6 | :rtype: int
7 | """
8 | ans = 0
9 | if len(nums) == 0:
10 | return 0
11 | for i in range(len(nums)):
12 | if nums[i] == val:
13 | continue
14 | nums[ans] = nums[i]
15 | ans += 1
16 | return ans
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0029.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def divide(self, dividend: int, divisor: int) -> int:
3 | sign = 1 if dividend ^ divisor >= 0 else -1
4 | dividend, divisor = abs(dividend), abs(divisor)
5 | res = 0
6 | while dividend >= divisor:
7 | tmp, i = divisor, 1
8 | while dividend >= tmp:
9 | dividend -= tmp
10 | res += i
11 | tmp <<= 1
12 | i <<= 1
13 | res *= sign
14 | return res if -1 << 31 <= res <= (1 << 31) - 1 else (1 << 31) - 1
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0034.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector searchRange(vector& nums, int target) {
4 | int l = 0, r = nums.size();
5 | while (l < r){
6 | int mid = l + (r - l) / 2;
7 | if (nums[mid] < target) l = mid + 1;
8 | else r = mid;
9 | }
10 | if (l == nums.size()) return {-1, -1};
11 | if (nums[l] != target) return {-1, -1};
12 | int a = 0, b = nums.size();
13 | while (a < b){
14 | int m = a + (b - a) / 2;
15 | if (nums[m] <= target) a = m + 1;
16 | else b = m;
17 | }
18 | return {l, a - 1};
19 | }
20 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0035.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int searchInsert(vector& nums, int target) {
4 | int l = 0, r = nums.size();
5 | if (r == 0) return 0;
6 | while (l < r){
7 | int mid = l + (r - l) / 2;
8 | if (nums[mid] >= target) r = mid;
9 | else l = mid + 1;
10 | }
11 | return l;
12 | }
13 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0035.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def searchInsert(self, nums, target):
3 | """
4 | :type nums: List[int]
5 | :type target: int
6 | :rtype: int
7 | """
8 | for ans in range(len(nums)):
9 | if nums[ans] == target:
10 | return ans
11 | if nums[ans] > target:
12 | return ans
13 | return len(nums)
14 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0039.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
6 | res = []
7 | candidates.sort()
8 | n = len(candidates)
9 |
10 | def backtrack(i, tmp, cur_sum):
11 | if cur_sum == target:
12 | res.append(tmp)
13 | return
14 | if cur_sum > target or i == n:
15 | return
16 |
17 | backtrack(i, tmp + [candidates[i]], cur_sum + candidates[i])
18 | backtrack(i + 1, tmp, cur_sum)
19 |
20 | backtrack(0, [], 0)
21 | return res
22 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0045.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | '''
6 | 贪心算法
7 | '''
8 |
9 | def jump(self, nums: List[int]) -> int:
10 | last_idx = len(nums) - 1
11 | if last_idx < 1:
12 | return 0
13 | ans = 0
14 | cur = 0
15 | while cur + nums[cur] < last_idx:
16 | step_len = nums[cur]
17 | tmp = 0
18 | ans += 1
19 | for _ in range(1, step_len + 1):
20 | if cur + _ + nums[cur + _] > tmp:
21 | tmp = cur + _ + nums[cur + _]
22 | idx = cur + _
23 | cur = idx
24 | return ans + 1
25 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0048.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | void rotate(vector>& matrix) {
4 | if (matrix.empty()) return;
5 | int row = matrix.size(), col = matrix[0].size();
6 | for(int r = 0; r < row / 2; ++r){
7 | for(int c = 0; c < col; ++c) swap(matrix[r][c], matrix[row - r - 1][c]);
8 | }
9 | for (int r = 0; r < row; ++r)
10 | for(int c = r + 1; c < col; ++c){
11 | swap(matrix[r][c], matrix[c][r]);
12 | }
13 | return;
14 | }
15 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0048.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def rotate(self, matrix: List[List[int]]) -> None:
3 | """
4 | Do not return anything, modify matrix in-place instead.
5 | """
6 | l = len(matrix)
7 | for i in range(l):
8 | for j in range(i, l):
9 | if i != j:
10 | # tmp = matrix[i][j]
11 | matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
12 | # matrix[j][i] = tmp
13 | for i in range(l):
14 | for j in range(l // 2):
15 | matrix[i][j], matrix[i][l - 1 - j] = matrix[i][l - 1 - j], matrix[i][j]
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0049.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
3 | from collections import defaultdict
4 | res = defaultdict(list)
5 | for _ in strs:
6 | res[tuple(sorted(_))].append(_)
7 | return res.values()
8 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0050.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def myPow(self, x: float, n: int) -> float:
3 | if not n:
4 | return 1
5 | ispos = n > 0
6 | n = abs(n)
7 | res, tmp = 1, x
8 | while n:
9 | if n & 1:
10 | res *= tmp
11 | tmp *= tmp
12 | n >>= 1
13 | if not ispos:
14 | res = 1 / res
15 | return res
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0053.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxSubArray(self, nums: List[int]) -> int:
3 | if not nums: return 0
4 | dp = [0 for _ in nums]
5 | dp[0] = nums[0]
6 | for idx, _ in enumerate(nums):
7 | if not idx:
8 | continue
9 | dp[idx] = _ + dp[idx - 1] if dp[idx - 1] > 0 else _
10 | return max(dp)
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0055.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def canJump(self, nums: List[int]) -> bool:
3 | maxlen = nums[0]
4 | l = len(nums)
5 | for idx in range(l):
6 | if idx <= maxlen:
7 | cur_len = idx + nums[idx]
8 | if cur_len > maxlen:
9 | maxlen = cur_len
10 | else:
11 | return False
12 | return True
13 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0058.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def lengthOfLastWord(self, s: str) -> int:
3 | s = s.split()
4 | if not s:
5 | return 0
6 | return len(s[-1])
7 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0062.cpp:
--------------------------------------------------------------------------------
1 | int dp[110][110];
2 | class Solution {
3 | public:
4 | int uniquePaths(int m, int n) {
5 | memset(dp, 0, sizeof(dp));
6 | dp[0][0] = 1;
7 | for (int r = 0; r < m; ++r){
8 | for(int c = 0; c < n; ++c){
9 | int u = r > 0? dp[r - 1][c]: 0;
10 | int l = c > 0? dp[r][c - 1]: 0;
11 | dp[r][c] += u + l;
12 | }
13 | }
14 | return dp[m - 1][n - 1];
15 | }
16 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0064.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int minPathSum(vector>& grid) {
4 | int m = grid.size();
5 | if (m == 0) return 0;
6 | int n = grid[0].size();
7 | vector dp(n, 0);
8 | for(int i = 0; i < n; ++i){
9 | dp[i] = i == 0? grid[0][i] : dp[i - 1] + grid[0][i];
10 | }
11 | for (int i = 1; i < m; ++i){
12 | for (int j = 0; j < n; ++j){
13 | dp[j] = j == 0? dp[j] + grid[i][j] : min(dp[j], dp[j - 1]) + grid[i][j];
14 | }
15 | }
16 | return dp[n - 1];
17 | }
18 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0069.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def mySqrt(self, x):
3 | if x < 2:
4 | return x
5 | cur = x
6 | while True:
7 | pre = cur
8 | cur = (cur + x / cur) / 2
9 | if abs(pre - cur) < 1e-6:
10 | return int(cur)
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0070.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int climbStairs(int n) {
4 | if (n < 3) return n;
5 | int pp = 1, p = 2;
6 | --n;
7 | while (--n){
8 | int cur = pp + p;
9 | pp = p;
10 | p = cur;
11 | }
12 | return p;
13 | }
14 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0070.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def climbStairs(self, n: int) -> int:
3 | pre, cur = 1, 0
4 | if not n: return n
5 | for _ in range(n + 1):
6 | tmp = pre + cur
7 | pre = cur
8 | cur = tmp
9 | return cur
10 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0071.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def simplifyPath(self, path: str) -> str:
3 | elems = path.split('/')
4 | res = []
5 | for tmp in elems:
6 | if tmp == '..':
7 | if res:
8 | res.pop()
9 | elif tmp and tmp != '.':
10 | res.append(tmp)
11 | return '/' + '/'.join(res)
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0074.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
3 | if not matrix:
4 | return False
5 | m, n = len(matrix), len(matrix[0])
6 | i, j = 0, n - 1
7 | while -1 < i < m and -1 < j < n:
8 | tmp = matrix[i][j]
9 | if tmp == target:
10 | return True
11 | elif tmp < target:
12 | i += 1
13 | else:
14 | j -= 1
15 | return False
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0075.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def sortColors(self, nums: List[int]) -> None:
3 | """
4 | Do not return anything, modify nums in-place instead.
5 | """
6 | if not nums or len(nums) < 2:
7 | return nums
8 | cur, p0, p2 = 0, 0, len(nums) - 1
9 | while cur <= p2:
10 | if nums[cur] == 0:
11 | nums[p0], nums[cur] = nums[cur], nums[p0]
12 | p0 += 1
13 | cur += 1
14 | elif nums[cur] == 2:
15 | nums[cur], nums[p2] = nums[p2], nums[cur]
16 | p2 -= 1
17 | else:
18 | cur += 1
19 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0077.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def combine(self, n: int, k: int) -> List[List[int]]:
3 | if n < k or k == 0 or n < 1:
4 | return []
5 | if n == k:
6 | return [list(range(1, n + 1))]
7 | elems = list(range(1, n + 1))
8 | res = []
9 |
10 | def helper(idx, cur_num, tmp):
11 | if cur_num == k:
12 | for _ in range(idx, n):
13 | res.append(tmp + [elems[_]])
14 | return
15 | for _ in range(idx, n):
16 | helper(_ + 1, cur_num + 1, tmp + [elems[_]])
17 |
18 | helper(0, 1, [])
19 | return res
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0078.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def subsets(self, nums: List[int]) -> List[List[int]]:
3 | res = []
4 | n = len(nums)
5 |
6 | def helper(idx, tmp):
7 | res.append(tmp)
8 | for idx in range(idx, n):
9 | helper(idx + 1, tmp + [nums[idx]])
10 |
11 | helper(0, [])
12 | return res
13 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0080.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def removeDuplicates(self, nums: List[int]) -> int:
3 | if len(nums) < 3:
4 | return len(nums)
5 | slow, fast = 1, 2
6 | n = len(nums)
7 | while fast < n:
8 | if nums[fast] != nums[slow - 1]:
9 | slow += 1
10 | nums[slow] = nums[fast]
11 | fast += 1
12 | return slow + 1
13 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0083.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def deleteDuplicates(self, head: ListNode) -> ListNode:
9 | dummy = ListNode(None)
10 | dummy.next = head
11 | p = dummy
12 | while p.next:
13 | cur = p.next
14 | nxt = cur.next
15 | while nxt and cur.val == nxt.val:
16 | cur = cur.next
17 | nxt = cur.next
18 | p.next = cur
19 | p = cur
20 | return dummy.next
21 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0089.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def grayCode(self, n: int) -> List[int]:
6 | res = [0] * 2 ** n
7 | exp = 0
8 | l = r = 1
9 | for i in range(1, 2 ** n):
10 | res[i] += res[r - i] + 2 ** exp
11 | if i == r:
12 | exp += 1
13 | l = r + 1
14 | r = l + 2 ** exp - 1
15 | return res
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0096.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | unordered_map memo;
4 | int numTrees(int n) {
5 | return dp(n);
6 | }
7 |
8 | int dp(int n){
9 | if (n == 1 || n == 0) memo[n] = 1;
10 | if(memo.count(n)) return memo[n];
11 | int ret = 0;
12 | for(int i = 1; i < n + 1; ++i){
13 | int l = i - 1;
14 | int r = n - i;
15 | ret += dp(l) * dp(r);
16 | }
17 | memo[n] = ret;
18 | return memo[n];
19 | }
20 |
21 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0096.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def numTrees(self, n: int) -> int:
3 | import functools
4 | @functools.lru_cache(None)
5 | def helper(n):
6 | if n <= 1:
7 | return 1
8 | return sum([helper(i) * helper(n - 1 - i) for i in range(n)])
9 |
10 | return helper(n)
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0106.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
3 | def _build(l1, r1, l2, r2):
4 | if l1 > r1:
5 | return None
6 | if l1 == r1 or l2 == r2:
7 | return TreeNode(postorder[l2])
8 | root = TreeNode(postorder[r2])
9 | idx = inorder.index(root.val)
10 | root.left = _build(l1, idx - 1, l2, l2 + idx - 1 - l1)
11 | root.right = _build(idx + 1, r1, l2 + idx - l1, r2 - 1)
12 | return root
13 |
14 | n = len(inorder)
15 | return _build(0, n - 1, 0, n - 1)
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0118.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def generate(self, numRows):
3 | """
4 | :type numRows: int
5 | :rtype: List[List[int]]
6 | """
7 | ans = [[] for _ in range(numRows)]
8 | for i in range(numRows):
9 | if i == 0:
10 | ans[i] = [1]
11 | else:
12 | ans[i] = [1] * (i + 1)
13 |
14 | if numRows > 2:
15 | for i in range(2, numRows):
16 | j = 1
17 | while (j < i):
18 | ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j]
19 | j += 1
20 | return ans
21 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0119.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def getRow(self, rowIndex):
3 | """
4 | :type rowIndex: int
5 | :rtype: List[int]
6 | """
7 | ans = [[] for _ in range(rowIndex + 1)]
8 | for i in range(rowIndex + 1):
9 | if i == 0:
10 | ans[i] = [1]
11 | else:
12 | ans[i] = [1] * (i + 1)
13 |
14 | if rowIndex > 1:
15 | for i in range(2, rowIndex + 1):
16 | j = 1
17 | while (j < i):
18 | ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j]
19 | j += 1
20 | return ans[rowIndex]
21 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0120.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int minimumTotal(vector>& triangle) {
4 | int n = triangle.size();
5 | for(int i = 1; i < n; ++i){
6 | for(int j = 0; j < i + 1; ++j){
7 | triangle[i][j] += j != i && j != 0? min(triangle[i - 1][j], triangle[i - 1][j - 1]) : 0;
8 | triangle[i][j] += j == i? triangle[i - 1][j - 1]: 0;
9 | triangle[i][j] += j == 0? triangle[i - 1][0]: 0;
10 | }
11 | }
12 | int ret = triangle[n - 1][0];
13 | for(auto &n: triangle[n - 1]) ret = min(ret, n);
14 | return ret;
15 | }
16 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0120.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minimumTotal(self, triangle: List[List[int]]) -> int:
3 | n = len(triangle)
4 | dp = [0] * n
5 | for i in range(n - 1, -1, -1):
6 | if i == n - 1:
7 | dp = triangle[i][:]
8 | continue
9 | for j in range(0, i + 1):
10 | dp[j] = min(dp[j], dp[j + 1]) + triangle[i][j]
11 | return dp[0]
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0122.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int maxProfit(vector& prices) {
4 | int ans = 0;
5 | for (int i = 1; i < prices.size(); ++i){
6 | ans += prices[i] > prices[i - 1]? prices[i] - prices[i - 1]: 0;
7 | }
8 | return ans;
9 | }
10 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0122.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxProfit(self, prices: List[int]) -> int:
3 | profit = 0
4 | for _ in range(1, len(prices)):
5 | tmp = prices[_] - prices[_ - 1]
6 | if tmp > 0:
7 | profit += tmp
8 | return profit
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0123.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxProfit(self, prices: List[int]) -> int:
3 | if not prices:
4 | return 0
5 | # [0 firstbuy, 1fsell, 2secondbuy, 3ssell]
6 | dp = [-prices[0], 0, float('-inf'), 0]
7 | for i in range(1, len(prices)):
8 | pre = dp[:]
9 | dp[0] = max(-prices[i], pre[0])
10 | dp[1] = max(prices[i] + pre[0], pre[1])
11 | dp[2] = max(pre[2], pre[1] - prices[i])
12 | dp[3] = max(pre[2] + prices[i], pre[3])
13 | return max(dp[1], dp[3])
14 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0124.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution:
9 | def maxPathSum(self, root: TreeNode):
10 | ret = float('-inf')
11 |
12 | def helper(node):
13 | nonlocal ret
14 | if (not node): return 0
15 | left = max(helper(node.left), 0)
16 | right = max(helper(node.right), 0)
17 | ret = max(ret, left + right + node.val)
18 | return max(right, left) + node.val;
19 |
20 | helper(root)
21 | return ret
22 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0125.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool isPalindrome(string s) {
4 | string ss;
5 | for(auto c: s){
6 | if ((c >= 'a' && c <= 'z')||(c >= 'A' && c <= 'Z')||(c >='0' && c<='9')) ss += c;
7 | }
8 | int i = 0, j = ss.size() - 1;
9 | while (i < j){
10 | auto a = ss[i], b = ss[j];
11 | if (a >= 'A' && a <= 'Z') a = 'a' + a - 'A';
12 | if (b >= 'A' && b <= 'Z') b = 'a' + b - 'A';
13 | if (a != b) return false;
14 | ++i;
15 | --j;
16 | }
17 | return true;
18 | }
19 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0125.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isPalindrome(self, s: str) -> bool:
3 | s = s.upper()
4 | tmp = ''
5 | for _ in s:
6 | if '0' <= _ <= '9' or 'A' <= _ <= 'Z':
7 | tmp += _
8 | # n = len(tmp)
9 | i, j = 0, len(tmp) - 1
10 | while i < j:
11 | if tmp[i] != tmp[j]:
12 | return False
13 | i += 1
14 | j -= 1
15 | return True
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0128.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int longestConsecutive(vector& nums) {
4 | unordered_set st;
5 | for (auto &num: nums) st.insert(num);
6 |
7 | int res = 0;
8 | int cur = 0;
9 | for (auto num: st){
10 | if (st.count(num - 1) == 0){
11 | cur = 1;
12 | while (st.count(num + 1)){
13 | ++cur;
14 | ++num;
15 | }
16 | }
17 | res = max(res, cur);
18 | }
19 | return res;
20 | }
21 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0134.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
3 | total = 0
4 | minvalue = float('inf')
5 | ret = -1
6 | for idx in range(len(gas)):
7 | total += gas[idx] - cost[idx]
8 | if total < minvalue:
9 | ret = idx
10 | minvalue = total
11 | return (ret + 1) % len(gas) if total >= 0 else -1
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0136.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def singleNumber(self, nums: List[int]) -> int:
3 | from functools import reduce
4 | return reduce(lambda x, y: x ^ y, nums)
5 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0139.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def wordBreak(self, s: str, wordDict: List[str]) -> bool:
6 | wordDict = set(wordDict)
7 | import functools
8 | @functools.lru_cache(None)
9 | def helper(s):
10 | if s in wordDict:
11 | return True
12 | for word in wordDict:
13 | n = len(word)
14 | if s[:n] == word:
15 | if helper(s[n:]):
16 | return True
17 | return False
18 |
19 | return helper(s)
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0144.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution:
9 | def preorderTraversal(self, root: TreeNode) -> List[int]:
10 | res = []
11 |
12 | def helper(node):
13 | if not node:
14 | return
15 | res.append(node.val)
16 | helper(node.left)
17 | helper(node.right)
18 |
19 | helper(root)
20 | return res
21 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0148.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | class ListNode:
3 | def __init__(self, x):
4 | self.val = x
5 | self.next = None
6 |
7 |
8 | class Solution:
9 | def sortList(self, head: ListNode) -> ListNode:
10 | if not head:
11 | return head
12 | res = []
13 | while head:
14 | res.append(head.val)
15 | head = head.next
16 | res.sort()
17 | root = ListNode(res[0])
18 | tmp = root
19 | for i in res[1:]:
20 | tmp.next = ListNode(i)
21 | tmp = tmp.next
22 | return root
23 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0151.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reverseWords(self, s: str) -> str:
3 | return ' '.join(s.split()[::-1])
4 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0152.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxProduct(self, nums: List[int]) -> int:
3 | dpmax = [0] * len(nums)
4 | dpmin = [0] * len(nums)
5 | for idx, _ in enumerate(nums):
6 | if idx == 0:
7 | dpmax[idx] = dpmin[idx] = _
8 | else:
9 | if _ >= 0:
10 | dpmax[idx] = max(dpmax[idx - 1] * _, _)
11 | dpmin[idx] = min(dpmin[idx - 1] * _, _)
12 | else:
13 | dpmax[idx] = max(dpmin[idx - 1] * _, _)
14 | dpmin[idx] = min(dpmax[idx - 1] * _, _)
15 | return max(dpmax)
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0153.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int findMin(vector& nums) {
4 | int l = 0, r = nums.size() - 1;
5 | while (l < r){
6 | int mid = l + (r - l >> 1);
7 | if (nums[mid] < nums[r]){
8 | r = mid;
9 | }
10 | else l = mid + 1;
11 | }
12 | return nums[l];
13 |
14 | }
15 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0154.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int findMin(vector& nums) {
4 | int l = 0, r = nums.size() - 1;
5 | while (l < r){
6 | int mid = l + (r - l) / 2;
7 | if (nums[mid] > nums[r]){
8 | l = mid + 1;
9 | }
10 | else if (nums[mid] < nums[r]){
11 | r = mid;
12 | }
13 | else{
14 | --r;
15 | }
16 | }
17 | return nums[l];
18 |
19 | }
20 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0154.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findMin(self, nums: List[int]) -> int:
3 | lo, hi = 0, len(nums) - 1
4 | while lo < hi:
5 | mid = (lo + hi) // 2
6 | if nums[mid] < nums[hi]:
7 | hi = mid
8 | elif nums[mid] > nums[hi]:
9 | lo = mid + 1
10 | else:
11 | hi -= 1
12 | return nums[lo]
13 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0156.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def upsideDownBinaryTree(self, root: TreeNode) -> TreeNode:
3 | parent = parent_right = None
4 | while root:
5 | root_left = root.left
6 | root_right = root.right
7 | root.left = parent_right
8 | root.right = parent
9 | parent = root
10 | parent_right = root_right
11 | root = root_left
12 | return parent
13 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0162.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int findPeakElement(vector& nums) {
4 | decltype(nums.size()) l = 0, r = nums.size();
5 | while (l < r){
6 | auto mid = l + (r - l) / 2;
7 | if (mid == nums.size() - 1 || nums[mid] > nums[mid + 1]){
8 | r = mid;
9 | }
10 | else{
11 | l = mid + 1;
12 | }
13 | }
14 | return l;
15 | }
16 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0165.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def compareVersion(self, version1: str, version2: str) -> int:
3 | v1 = version1.split('.')
4 | v2 = version2.split('.')
5 | for i in range(max(len(v1), len(v2))):
6 | try:
7 | s1 = int(v1[i])
8 | except:
9 | s1 = 0
10 | try:
11 | s2 = int(v2[i])
12 | except:
13 | s2 = 0
14 | if s1 < s2:
15 | return -1
16 | elif s1 > s2:
17 | return 1
18 | return 0
19 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0167.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def twoSum(self, numbers: List[int], target: int) -> List[int]:
3 | d = {}
4 | for idx, _ in enumerate(numbers):
5 | if target - _ not in d:
6 | d[_] = idx + 1
7 | else:
8 | return [d[target - _], idx + 1]
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0168.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def convertToTitle(self, n: int) -> str:
3 | nums = list(range(1, 27))
4 | alphas = [chr(_) for _ in range(ord('A'), ord('Z') + 1)]
5 | d = dict(zip(nums, alphas))
6 | d[0] = 'Z'
7 | res = ''
8 | while n > 0:
9 | div = n // 26
10 | mod = n - div * 26
11 | if mod == 0:
12 | div = (n - 26) // 26
13 | res = d[mod] + res
14 | n = div
15 | return res
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0171.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int titleToNumber(string s) {
4 | int ret = 0;
5 | for (auto c: s){
6 | ret *= 26;
7 | ret += (int)(c - 'A' + 1);
8 | }
9 | return ret;
10 | }
11 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0172.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int titleToNumber(string s) {
4 | int ret = 0;
5 | for (auto c: s){
6 | ret *= 26;
7 | ret += (int)(c - 'A' + 1);
8 | }
9 | return ret;
10 | }
11 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0175.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | SELECT
3 | FirstName, LastName, City, State
4 | FROM
5 | Person LEFT OUTER JOIN Address
6 | ON
7 | Person.PersonID = Address.PersonID;
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0176.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | (select distinct salary
4 | from employee
5 | order by salary desc
6 | limit 1, 1)
7 | as SecondHighestSalary;
8 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0178.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | score as 'Score',
4 | dense_rank() over(order by score desc) as 'Rank'
5 | from
6 | scores;
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0179.py:
--------------------------------------------------------------------------------
1 | from functools import cmp_to_key
2 |
3 |
4 | def _cmp(a, b):
5 | ab = a + b
6 | ba = b + a
7 | if ab < ba:
8 | return -1
9 | elif ab == ba:
10 | return 0
11 | else:
12 | return 1
13 |
14 |
15 | class Solution:
16 | def largestNumber(self, nums: List[int]) -> str:
17 | str_nums = list(map(str, nums))
18 | ret = sorted(str_nums, key=cmp_to_key(_cmp), reverse=True)
19 | return ''.join(ret)
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0181.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | a.Name as 'Employee'
4 | from
5 | Employee as a,
6 | Employee as b
7 | where
8 | a.ManagerId = b.Id and a.Salary > b.Salary;
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0182.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select email
3 | from person
4 | group by email
5 | having count(email) > 1;
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0183.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | Name as 'Customers'
4 | from
5 | Customers
6 | where
7 | Customers.Id not in(
8 | select
9 | CustomerId
10 | from
11 | Orders
12 | );
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0184.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | b.Name as Department,
4 | a.Name as Employee,
5 | a.Salary as Salary
6 | from
7 | (select
8 | b.Name as Name,
9 | a.Salary as Salary,
10 | a.DID as DID
11 | from
12 | (select
13 | DepartmentId as DID,
14 | max(Salary) as Salary
15 | from
16 | Employee
17 | group by
18 | DepartmentId) as a,
19 | Employee as b
20 | where
21 | b.Salary = a.Salary and b.DepartmentId = a.DID) as a,
22 | Department as b
23 | where
24 | a.DID = b.Id
25 |
26 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0189.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def rotate(self, nums: List[int], k: int) -> None:
3 | """
4 | Do not return anything, modify nums in-place instead.
5 | """
6 | k = (k + 1) % len(nums)
7 | tmp = nums[k:] + nums[:k]
8 | for idx, _ in enumerate(tmp):
9 | nums[idx] = _
10 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0190.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reverseBits(self, n: int) -> int:
3 | res = 0
4 | for _ in range(32):
5 | tmp = n & 0x80000000
6 | tmp = 1 if tmp else 0
7 | n <<= 1
8 | if tmp:
9 | res += 2 ** _
10 | print(bin(res))
11 | return res
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0191.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def hammingWeight(self, n: int) -> int:
3 | n &= 0xFFFFFFFF
4 | n = bin(n)[2:]
5 | return n.count('1')
6 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0193.sh:
--------------------------------------------------------------------------------
1 | grep "^([0-9]\{3\})\s[0-9]\{3\}-[0-9]\{4\}\b\|^[0-9]\{3\}-[0-9]\{3\}-[0-9]\{4\}$" file.txt
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0195.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | # Read from the file file.txt and output the tenth line to stdout.
3 | tail -n +10 file.txt | head -1
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0197.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | SELECT
3 | a.Id
4 | FROM
5 | Weather as a,
6 | Weather as b
7 | WHERE
8 | DateDiff(a.RecordDate, b.RecordDate) = 1 AND
9 | a.Temperature > b.Temperature;
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0198.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def rob(self, nums: List[int]) -> int:
3 | if not nums:
4 | return 0
5 | preMax = 0
6 | curMax = nums[0]
7 | idx = 1
8 | while idx < len(nums):
9 | preMax, curMax = curMax, max(preMax + nums[idx], curMax)
10 | idx += 1
11 | return max(preMax, curMax)
12 | # def dynamic(idx):
13 | # if idx < 0:
14 | # return 0
15 | # if idx == 0:
16 | # return nums[0]
17 | # return max(nums[idx] + dynamic(idx -2), dynamic(idx - 1))
18 | # return dynamic(len(nums) - 1)
19 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0201.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def rangeBitwiseAnd(self, m: int, n: int) -> int:
3 | zeros = 0
4 | while m != n:
5 | m >>= 1
6 | n >>= 1
7 | zeros += 1
8 | return m << zeros
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0202.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isHappy(self, n: int) -> bool:
3 |
4 | def get_next(num):
5 | return sum([int(_) ** 2 for _ in str(num)])
6 |
7 | visited = set()
8 | while True:
9 | nex = get_next(n)
10 | if nex in visited:
11 | return False
12 | else:
13 | visited.add(nex)
14 | if nex == 1:
15 | return True
16 | n = nex
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0203.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def removeElements(self, head: ListNode, val: int) -> ListNode:
9 | dummy = ListNode(None)
10 | dummy.next = head
11 | pre = dummy
12 | cur = dummy.next
13 | while cur:
14 | if cur.val == val:
15 | pre.next = cur.next
16 | else:
17 | pre = pre.next
18 | cur = cur.next
19 | return dummy.next
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0204.cpp:
--------------------------------------------------------------------------------
1 | bool visited[5000010];
2 |
3 | class Solution {
4 | public:
5 | int countPrimes(int n) {
6 | memset(visited, 0, sizeof(visited));
7 | int cnt = 0;
8 | for(int i = 2; i < n; ++i){
9 | if (!visited[i]){
10 | ++cnt;
11 | int k = 2;
12 | while (i * k < n){
13 | visited[i * k] = true;
14 | ++k;
15 | }
16 | }
17 | }
18 | return cnt;
19 | }
20 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0204.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def countPrimes(self, n: int) -> int:
3 | if n < 2: return 0
4 | res = [1] * n
5 | res[0], res[1] = 0, 0
6 | for i in range(2, int(n ** 0.5) + 1):
7 | # print(res)
8 | if res[i]:
9 | res[i * i: n: i] = [0] * len(res[i * i: n: i])
10 | return sum(res)
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0205.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isIsomorphic(self, s: str, t: str) -> bool:
3 | if len(s) != len(t):
4 | return False
5 | d = {}
6 | used = set()
7 | n = len(s)
8 | for i in range(n):
9 | ss, tt = s[i], t[i]
10 | if ss not in d:
11 | d[ss] = tt
12 | if tt in used:
13 | return False
14 | used.add(tt)
15 | else:
16 | if d[ss] != tt:
17 | return False
18 |
19 | return True
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0209.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int minSubArrayLen(int s, vector& nums) {
4 | int l = 0, r = 0, total = 0;
5 | int ans = INT_MAX;
6 | while(r < nums.size()){
7 | while (r < nums.size() && total < s){
8 | total += nums[r];
9 | ++r;
10 | }
11 | while(l < r && total - nums[l] >= s){
12 | total -= nums[l];
13 | ++l;
14 | }
15 | if(total >= s) ans = min(ans, r - l);
16 | total -= nums[l];
17 | ++l;
18 | }
19 | return ans == INT_MAX? 0: ans;
20 | }
21 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0213.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def rob(self, nums: List[int]) -> int:
3 | if not nums:
4 | return 0
5 |
6 | def rob_once(tmp):
7 | if not tmp:
8 | return 0
9 | preMax = 0
10 | curMax = tmp[0]
11 | i = 1
12 | while i < len(tmp):
13 | preMax, curMax = curMax, max(
14 | preMax + tmp[i], curMax)
15 | i += 1
16 | return max(preMax, curMax)
17 |
18 | return max(nums[0], rob_once(nums[1:]), rob_once(nums[:-1]))
19 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0214.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | string shortestPalindrome(string s)
4 | {
5 | int n = s.size();
6 | cout << n << endl;
7 | string rev(s.rbegin(), s.rend());
8 | string new_s = s + "#" + rev;
9 | int new_n = new_s.size();
10 | vector f(new_n, 0);
11 | cout << f.size() < bool:
3 | res = set()
4 | for _ in nums:
5 | if _ in res:
6 | return True
7 | res.add(_)
8 | return False
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0223.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int:
3 | ret = (D - B) * (C - A) + (H - F) * (G - E)
4 | x1, y1, x2, y2 = max(A, E), max(B, F), min(C, G), min(D, H)
5 | overlap = max(0, y2 - y1) * max(0, x2 - x1)
6 | # print(ret, overlap)
7 | return ret - overlap
8 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0226.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def invertTree(self, root: TreeNode) -> TreeNode:
3 | def helper(node):
4 | if not node:
5 | return
6 | node.left, node.right = node.right, node.left
7 | helper(node.left)
8 | helper(node.right)
9 |
10 | helper(root)
11 | return root
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0228.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def summaryRanges(self, nums: List[int]) -> List[str]:
3 | l, r, n = 0, 0, len(nums)
4 | ret = []
5 | while r < n:
6 | while r + 1 < n and nums[r] + 1 == nums[r + 1]:
7 | r += 1
8 | if nums[r] == nums[l]:
9 | ret.append(str(nums[r]))
10 | else:
11 | ret.append("{}->{}".format(nums[l], nums[r]))
12 | r += 1
13 | l = r
14 | return ret
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0231.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool isPowerOfTwo(int n) {
4 | return n > 0 && !(n & (n - 1));
5 | }
6 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0233.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def countDigitOne(self, n: int) -> int:
3 | tmp = 1
4 | res = 0
5 | while n >= tmp:
6 | a = n // tmp
7 | b = n % tmp
8 | res += (a + 8) // 10 * tmp + (a % 10 == 1) * (b + 1)
9 | tmp *= 10
10 | return res
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0235.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution:
9 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
10 | if p.val > q.val:
11 | p, q = q, p
12 | node = root
13 | while True:
14 | if node.val < p.val:
15 | node = node.right
16 | elif node.val > q.val:
17 | node = node.left
18 | else:
19 | return node
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0237.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def deleteNode(self, node):
9 | """
10 | :type node: ListNode
11 | :rtype: void Do not return anything, modify node in-place instead.
12 | """
13 | node.val = node.next.val
14 | node.next = node.next.next
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0240.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def searchMatrix(self, matrix, target):
3 | """
4 | :type matrix: List[List[int]]
5 | :type target: int
6 | :rtype: bool
7 | """
8 | if not matrix:
9 | return False
10 | row, col = len(matrix), len(matrix[0])
11 | i, j = 0, col - 1
12 | while row > i > -1 and col > j > -1:
13 | if matrix[i][j] == target:
14 | return True
15 | elif matrix[i][j] < target:
16 | i += 1
17 | elif matrix[i][j] > target:
18 | j -= 1
19 | return False
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0242.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isAnagram(self, s: str, t: str) -> bool:
3 | # if not s and not t:
4 | # return True
5 | # if len(s) != len(t):
6 | # return False
7 | # from functools import reduce
8 | # tmp = s + t
9 | # # print(list(tmp))
10 | # res = reduce(lambda x, y: x ^ y, map(ord, list(tmp)))
11 | # return not res
12 | return abs(sum([ord(x) ** 0.5 for x in s]) - sum([ord(y) ** 0.5 for y in t])) < 1e-5
13 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0243.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int shortestDistance(vector& words, string word1, string word2) {
4 | int p1 = -1, p2 = -1;
5 | int ans = INT_MAX;
6 | for(int i = 0; i < words.size(); ++i){
7 | string &tmp = words[i];
8 | if (tmp == word1){
9 | p1 = i;
10 | if (p2 != -1) ans = min(ans, abs(p1 - p2));
11 | }
12 | if (tmp == word2){
13 | p2 = i;
14 | if (p1 != -1) ans = min(ans, abs(p1 - p2));
15 | }
16 | }
17 | return ans;
18 | }
19 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0246.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool isStrobogrammatic(string num) {
4 | unordered_map trans{{'1', '1'}, {'6', '9'}, {'8', '8'}, {'0', '0'}, {'9', '6'}};
5 | int l = 0, r = num.size() - 1;
6 | if (r < 0) return false;
7 | while (l <= r){
8 | if (trans[num[l]] != num[r]) return false;
9 | ++l;
10 | --r;
11 | }
12 | return true;
13 | }
14 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0252.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
6 | if not intervals:
7 | return True
8 | intervals.sort()
9 | end = -1
10 | for interval in intervals:
11 | if interval[0] < end:
12 | return False
13 | end = max(end, interval[1])
14 | return True
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0253.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def minMeetingRooms(self, intervals: List[List[int]]) -> int:
6 | import heapq
7 | if not intervals:
8 | return 0
9 | intervals.sort(key=lambda x: x[0])
10 | rooms = []
11 | heapq.heappush(rooms, intervals[0][1])
12 | for i in intervals[1:]:
13 | if i[0] >= rooms[0]:
14 | heapq.heappop(rooms)
15 | heapq.heappush(rooms, i[1])
16 | return len(rooms)
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0258.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * @lc app=leetcode.cn id=258 lang=cpp
3 | *
4 | * [258] 各位相加
5 | */
6 |
7 | // @lc code=start
8 | class Solution {
9 | public:
10 | int addDigits(int num) {
11 | return (num- 1) % 9 + 1;
12 | }
13 | };
14 | // @lc code=end
15 |
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0259.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int threeSumSmaller(vector& nums, int target) {
4 | sort(nums.begin(), nums.end());
5 | int ans = 0, l = 0, r = nums.size() - 1;
6 | for (int i = 0; i < nums.size(); ++i){
7 | int c = target - nums[i];
8 | int l = i + 1, r = nums.size() - 1;
9 | while (l < r){
10 | if (nums[l] + nums[r] < c){
11 | ans += r - l;
12 | l += 1;
13 | }
14 | else r -= 1;
15 | }
16 | }
17 | return ans;
18 | }
19 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0263.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isUgly(self, num: int) -> bool:
3 | if num < 1:
4 | return False
5 | for i in [2, 3, 5]:
6 | while not num % i:
7 | num /= i
8 | return num == 1
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0266.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * @lc app=leetcode.cn id=266 lang=cpp
3 | *
4 | * [266] 回文排列
5 | */
6 |
7 | // @lc code=start
8 | class Solution {
9 | public:
10 | bool canPermutePalindrome(string s) {
11 | vector cnt(256, 0);
12 | for (auto c: s) ++cnt[c];
13 | int odd = 0;
14 | for(auto i: cnt)
15 | if(i & 1) ++odd;
16 | return odd <= 1;
17 | }
18 | };
19 | // @lc code=end
20 |
21 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0268.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def missingNumber(self, nums: List[int]) -> int:
3 | res = 0
4 | for _ in range(len(nums) + 1):
5 | res += _
6 | return res - sum(nums)
7 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0276.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * @lc app=leetcode.cn id=276 lang=cpp
3 | *
4 | * [276] 栅栏涂色
5 | */
6 |
7 | // @lc code=start
8 | class Solution {
9 | public:
10 | int numWays(int n, int k) {
11 | if (n == 0) return n;
12 | if (n == 1) return k;
13 | int same = k;
14 | int diff = k * (k - 1);
15 | --n;
16 | while (--n){
17 | int tmp = same;
18 | same = diff;
19 | diff = (k - 1) * tmp + (k - 1) * diff;
20 | }
21 | return diff + same;
22 | }
23 | };
24 | // @lc code=end
25 |
26 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0278.py:
--------------------------------------------------------------------------------
1 | # The isBadVersion API is already defined for you.
2 | # @param version, an integer
3 | # @return a bool
4 | # def isBadVersion(version):
5 |
6 | class Solution:
7 | def firstBadVersion(self, n):
8 | """
9 | :type n: int
10 | :rtype: int
11 | """
12 | if not n: return n
13 | l, r = 0, n
14 | while l <= r:
15 | mid = (l + r) // 2
16 | if isBadVersion(mid):
17 | if not mid or not isBadVersion(mid - 1):
18 | return mid
19 | else:
20 | r = mid
21 | else:
22 | l = mid + 1
23 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0279.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def numSquares(self, n: int) -> int:
3 | from queue import Queue
4 | que = Queue()
5 | que.put((n, 0))
6 | while True:
7 | n, step = que.get()
8 | step += 1
9 | for _ in range(int(math.sqrt(n)), 0, -1):
10 | if _ * _ < n:
11 | que.put((n - _ * _, step))
12 | elif _ * _ == n:
13 | return step
14 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0283.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | void moveZeroes(vector& nums) {
4 | int insert_idx = 0, cur = 0;
5 | while(cur < nums.size()){
6 | if (nums[cur]){
7 | nums[insert_idx] = nums[cur];
8 | ++insert_idx;
9 | }
10 | ++cur;
11 | }
12 | for (; insert_idx < nums.size(); ++insert_idx)
13 | nums[insert_idx] = 0;
14 | }
15 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0283.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def moveZeroes(self, nums: List[int]) -> None:
3 | """
4 | Do not return anything, modify nums in-place instead.
5 | """
6 | nums0 = [i for i in nums if not i]
7 | nums1 = [i for i in nums if i]
8 | nums[:] = nums1 + nums0
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0287.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findDuplicate(self, nums: List[int]) -> int:
3 | # fast slow pointer
4 | fast, slow = 0, 0
5 | while True:
6 | fast = nums[nums[fast]]
7 | slow = nums[slow]
8 | if fast == slow:
9 | break
10 | res = 0
11 | while True:
12 | res = nums[res]
13 | slow = nums[slow]
14 | if res == slow:
15 | return res
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0290.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def wordPattern(self, pattern: str, str: str) -> bool:
3 | d = {}
4 | pattern = list(pattern)
5 | str = str.split(' ')
6 | visited = set()
7 | if len(pattern) != len(str):
8 | return False
9 | for (k, v) in zip(pattern, str):
10 | if k not in d:
11 | if v not in visited:
12 | visited.add(v)
13 | else:
14 | return False
15 | d[k] = v
16 | else:
17 | if d[k] != v:
18 | return False
19 | return True
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0292.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def canWinNim(self, n: int) -> bool:
3 | return n & 3
4 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0293.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * @lc app=leetcode.cn id=293 lang=cpp
3 | *
4 | * [293] 翻转游戏
5 | */
6 |
7 | // @lc code=start
8 | class Solution {
9 | public:
10 | vector generatePossibleNextMoves(string s) {
11 | unordered_set pos;
12 | vector ret;
13 | for(int i = 0; i < s.size(); ++i) if(s[i] =='
14 | +') pos.insert(i);
15 | for (auto it: pos){
16 | if (pos.count(it + 1)) ret.push_back(s.substr(0, it) + "--" + s.substr(it + 2, s.size() - 1));
17 | }
18 | return ret;
19 | }
20 | };
21 | // @lc code=end
22 |
23 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0309.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxProfit(self, prices: List[int]) -> int:
3 | if not prices:
4 | return 0
5 | # dp [buy sell cooldown havestock nothavstock]
6 | dp = [-prices[0], 0, float('-inf'), -prices[0], 0]
7 | for i in range(1, len(prices)):
8 | pre = dp[:]
9 | price = prices[i]
10 | dp[0] = pre[4] - price
11 | dp[1] = max(pre[0], pre[3]) + price
12 | dp[2] = pre[1]
13 | dp[3] = max(dp[0], pre[3])
14 | dp[4] = max(pre[1], pre[2], pre[4])
15 | return max(dp[1], dp[2], dp[4])
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0318.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int maxProduct(vector& words) {
4 | vector mask(words.size(), 0);
5 | for (int i = 0; i < words.size(); ++i){
6 | for(char c: words[i]) mask[i] |= 1 << (c - 'a');
7 | }
8 | int ret = 0;
9 | for(int i = 0; i < mask.size(); ++i)
10 | for(int j = i; j < mask.size(); ++j)
11 | if((mask[i] & mask[j]) == 0) ret = max(ret, int(words[i].size() * words[j].size()));
12 | return ret;
13 | }
14 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0319.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def bulbSwitch(self, n: int) -> int:
3 | """
4 | 返回 完全平方数的个数
5 | """
6 | if not n:
7 | return 0
8 | return int(n ** 0.5)
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0322.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def coinChange(self, coins: List[int], amount: int) -> int:
6 | dp = [float('inf')] * (amount + 1)
7 | dp[0] = 0
8 | if amount == 0:
9 | return 0
10 | for coin in coins:
11 | for i in range(coin, amount + 1):
12 | dp[i] = min(dp[i], dp[i - coin] + 1)
13 | return dp[-1] if dp[-1] != float('inf') else -1
14 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0326.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isPowerOfThree(self, n: int) -> bool:
3 | # print(round(math.log(n, 3)))
4 | return n > 0 and 3 ** round(math.log(n, 3)) == n
5 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0327.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
3 | from sortedcontainers import SortedList
4 | prefix, ret = 0, 0
5 | st = SortedList([0])
6 | for num in nums:
7 | prefix += num
8 | ret += st.bisect_right(prefix - lower) - st.bisect_left(prefix - upper)
9 | st.add(prefix)
10 | return ret
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0328.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def oddEvenList(self, head: ListNode) -> ListNode:
9 | if not head:
10 | return head
11 | odd = head
12 | even = head.next
13 | evenHead = even
14 | while even and even.next:
15 | odd.next = even.next
16 | odd = odd.next
17 | even.next = odd.next
18 | even = even.next
19 | odd.next = evenHead
20 | return head
21 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0342.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * @lc app=leetcode.cn id=342 lang=cpp
3 | *
4 | * [342] 4的幂
5 | */
6 |
7 | // @lc code=start
8 | class Solution {
9 | public:
10 | bool isPowerOfFour(int num) {
11 | return num == 1 || (num > 0 && !(num & (num - 1)) && (num & 0x55555555));
12 | }
13 | };
14 | // @lc code=end
15 |
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0343.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def integerBreak(self, n: int) -> int:
3 | dp = [0] * (n + 1)
4 | dp[1] = 1
5 | dp[2] = 1
6 | for i in range(3, n + 1):
7 | for j in range(1, i):
8 | dp[i] = max(max(j, dp[j]) * (i - j), dp[i])
9 | return dp[-1]
10 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0344.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reverseString(self, s: List[str]) -> None:
3 | """
4 | Do not return anything, modify s in-place instead.
5 | """
6 | i, j = 0, len(s) - 1
7 | while i < j:
8 | s[i], s[j] = s[j], s[i]
9 | i += 1
10 | j -= 1
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0347.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3 | from collections import Counter
4 | cnt = Counter(nums)
5 | from heapq import heappush, heappop
6 | heap = []
7 | for key in cnt:
8 | heappush(heap, [-cnt[key], key])
9 | return [heappop(heap)[1] for i in range(k)]
10 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0349.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
6 | return list(set(nums1) & set(nums2))
7 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0350.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector intersect(vector& nums1, vector& nums2) {
4 | vector ret;
5 | unordered_map counter;
6 | for(auto &n: nums1) ++counter[n];
7 | for(auto &n: nums2){
8 | if(counter[n] > 0){
9 | --counter[n];
10 | ret.push_back(n);
11 | }
12 | }
13 | return ret;
14 |
15 | }
16 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0352.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def getSum(self, a: int, b: int) -> int:
3 | a &= 0xFFFFFFFF
4 | b &= 0xFFFFFFFF
5 | # print(a, b)
6 | while b:
7 | carry = a & b
8 | a ^= b
9 | b = ((carry) << 1) & 0xFFFFFFFF
10 | # print((a, b))
11 | return a if a < 0x80000000 else ~(a ^ 0xFFFFFFFF)
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0354.py:
--------------------------------------------------------------------------------
1 | from bisect import bisect_left
2 |
3 |
4 | class Solution:
5 | def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
6 | envelopes.sort(key=lambda x: [x[0], -x[1]])
7 |
8 | def lcs(nums):
9 | cells = []
10 | for idx, val in enumerate(nums):
11 | if not cells or val > cells[-1]:
12 | cells.append(val)
13 | continue
14 | cells[bisect_left(cells, val)] = val
15 | return len(cells)
16 |
17 | nums = [_[1] for _ in envelopes]
18 | return lcs(nums)
19 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0357.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int countNumbersWithUniqueDigits(int n) {
4 | int pre = 1, cur = 1;
5 | for (int i = 0; i < min(n, 10); ++i){
6 | if (i < 2) cur *= 9;
7 | else cur *= 10 - i;
8 | pre += cur;
9 | }
10 | return pre;
11 | }
12 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0367.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool isPerfectSquare(int num) {
4 | if (num < 0) return false;
5 | int l = 0, r = num;
6 | while (l <= r){
7 | long int mid = l + (r - l >> 1);
8 | if (mid * mid < num) l = mid + 1;
9 | else if (mid * mid > num) r = mid - 1;
10 | else return true;
11 | }
12 | return false;
13 |
14 | }
15 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0371.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def getSum(self, a: int, b: int) -> int:
3 | a &= 0xFFFFFFFF
4 | b &= 0xFFFFFFFF
5 | while b:
6 | carry = a & b
7 | a = a ^ b
8 | b = ((carry) << 1) & 0xFFFFFFFF
9 | return a if a < 0x80000000 else ~(a ^ 0xFFFFFFFF)
10 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0374.py:
--------------------------------------------------------------------------------
1 | # The guess API is already defined for you.
2 | # @param num, your guess
3 | # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
4 | # def guess(num: int) -> int:
5 |
6 | class Solution:
7 | def guessNumber(self, n: int) -> int:
8 | l = 0
9 | r = n
10 | while l <= r:
11 | mid = (l + r) // 2
12 | cmp = guess(mid)
13 | if cmp == 1:
14 | l = mid + 1
15 | elif cmp == -1:
16 | r = mid - 1
17 | else:
18 | return mid
19 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0375.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def getMoneyAmount(self, n: int) -> int:
3 | @functools.lru_cache(None)
4 | def dp(i, j):
5 | if i >= j:
6 | return 0
7 | if i + 1 == j:
8 | return i
9 | ret = float('inf')
10 | for k in range(i, j + 1):
11 | ret = min(ret, k + max(dp(i, k - 1), dp(k + 1, j)))
12 | return ret
13 |
14 | return dp(1, n)
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0383.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def canConstruct(self, ransomNote: str, magazine: str) -> bool:
3 | from collections import Counter
4 | cnt1 = Counter(ransomNote)
5 | cnt2 = Counter(magazine)
6 | for k in cnt1:
7 | if k not in cnt2 or cnt1[k] > cnt2[k]:
8 | return False
9 | return True
10 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0387.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def firstUniqChar(self, s: str) -> int:
3 | d = {}
4 | for _ in s:
5 | if _ not in d:
6 | d[_] = 1
7 | else:
8 | d[_] += 1
9 | for idx, _ in enumerate(s):
10 | if d[_] == 1: return idx
11 | return -1
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0389.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * @lc app=leetcode.cn id=389 lang=cpp
3 | *
4 | * [389] 找不同
5 | */
6 |
7 | // @lc code=start
8 | class Solution {
9 | public:
10 | char findTheDifference(string s, string t) {
11 | char v = 0;
12 | for (char c: s) v ^= c;
13 | for (char c: t) v ^= c;
14 | return v;
15 | }
16 | };
17 | // @lc code=end
18 |
19 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0392.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * @lc app=leetcode.cn id=392 lang=cpp
3 | *
4 | * [392] 判断子序列
5 | */
6 |
7 | // @lc code=start
8 | class Solution {
9 | public:
10 | bool isSubsequence(string s, string t) {
11 | int m = s.size(), n = t.size(), i = 0, j = 0;
12 |
13 | while (j < n){
14 | if(t[j] == s[i]){++j; ++i;}
15 | else ++j;
16 | if (i == m) return true;
17 | }
18 | return j == n && i == m;
19 | }
20 | };
21 | // @lc code=end
22 |
23 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0395.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def longestSubstring(self, s: str, k: int) -> int:
3 | if len(s) < k:
4 | return 0
5 | t = min(set(s), key=s.count)
6 | if s.count(t) >= k:
7 | return len(s)
8 | return max([self.longestSubstring(ss, k) for ss in s.split(t)])
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0405.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * @lc app=leetcode.cn id=405 lang=cpp
3 | *
4 | * [405] 数字转换为十六进制数
5 | */
6 |
7 | // @lc code=start
8 | class Solution {
9 | public:
10 | string toHex(int num) {
11 | string ret;
12 | for(int i = 7; i > -1; --i){
13 | int cur = ((unsigned)num & (0xf << (i * 4))) >> (i * 4);
14 | cout << cur << endl;
15 | if (ret.size() == 0 && cur == 0) continue;
16 | if (cur < 10) ret += to_string(cur);
17 | else ret += 'a' + cur - 10;
18 | }
19 | return ret.size()? ret: "0";
20 |
21 | }
22 | };
23 | // @lc code=end
24 |
25 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0406.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
3 | if not people:
4 | return []
5 | people.sort(key=lambda x: [-x[0], x[1]])
6 | ret = []
7 | for p in people:
8 | ret.insert(p[1], p)
9 | return ret
10 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0409.py:
--------------------------------------------------------------------------------
1 | from collections import Counter
2 |
3 |
4 | class Solution:
5 | def longestPalindrome(self, s: str) -> int:
6 | c = Counter(s)
7 | # print(c)
8 | res = sum([i >> 1 << 1 for i in c.values()])
9 | odd = 1 if any([i & 1 for i in c.values()]) else 0
10 | # print(odd)
11 | return res + odd
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0412.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def fizzBuzz(self, n: int) -> List[str]:
3 | if not n: return []
4 | res = []
5 | d = {3: 'Fizz', 5: 'Buzz'}
6 | for _ in range(1, n + 1):
7 | tmp = ''
8 | for key in d:
9 | if _ % key == 0:
10 | tmp += d[key]
11 | if not tmp:
12 | tmp = str(_)
13 | res.append(tmp)
14 | return res
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0415.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def addStrings(self, num1: str, num2: str) -> str:
3 | l1, l2, carry = len(num1) - 1, len(num2) - 1, 0
4 | res = ''
5 | while l1 > -1 or l2 > -1:
6 | n1 = int(num1[l1]) if l1 > -1 else 0
7 | n2 = int(num2[l2]) if l2 > -1 else 0
8 | tmp = n1 + n2 + carry
9 | carry = tmp // 10
10 | res = str(tmp % 10) + res
11 | l1 -= 1
12 | l2 -= 1
13 | return '1' + res if carry else res
14 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0434.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * @lc app=leetcode.cn id=434 lang=cpp
3 | *
4 | * [434] 字符串中的单词数
5 | */
6 |
7 | // @lc code=start
8 | class Solution {
9 | public:
10 | int countSegments(string s) {
11 | int j = 0;
12 | int cnt = 0;
13 | while (j < s.size()){
14 | if (s[j] == ' ') ++j;
15 | else{
16 | ++cnt;
17 | while(j < s.size() && s[j] != ' ') ++j;
18 | }
19 | }
20 | return cnt;
21 | }
22 | };
23 | // @lc code=end
24 |
25 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0441.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def arrangeCoins(self, n: int) -> int:
3 | k = 1
4 | while n >= k:
5 | n -= k
6 | k += 1
7 | return k - 1
8 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0442.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findDuplicates(self, nums: List[int]) -> List[int]:
3 | ret = set()
4 | idx = 0
5 | while idx < len(nums):
6 | # print(idx, nums)
7 | val = nums[idx]
8 | target_idx = val - 1
9 | # print(val, target_idx, idx)
10 | if target_idx == idx:
11 | idx += 1
12 | elif nums[target_idx] == val:
13 | ret.add(val)
14 | idx += 1
15 | else:
16 | nums[idx], nums[target_idx] = nums[target_idx], nums[idx]
17 | return list(ret)
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0447.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def numberOfBoomerangs(self, points: List[List[int]]) -> int:
3 | from collections import defaultdict
4 | n = len(points)
5 | dist = defaultdict(int)
6 | res = 0
7 | for i in range(n):
8 | dist.clear()
9 | for j in range(n):
10 | if j == i:
11 | continue
12 | dis = (points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2
13 | dist[dis] += 1
14 | for v in dist.values():
15 | res += v * v - v
16 | return res
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0451.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def frequencySort(self, s: str) -> str:
3 | if not s:
4 | return s
5 | from collections import Counter
6 | cnt = Counter(s)
7 | res = ''
8 | k_v = sorted([(k, v) for k, v in cnt.items()], key=lambda x: -x[1])
9 | for (k, v) in k_v:
10 | res += k * v
11 | return res
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0452.cpp:
--------------------------------------------------------------------------------
1 | bool cmp(const vector &a, const vector & b){
2 | return a[1] < b[1];
3 | }
4 |
5 | class Solution {
6 | public:
7 | int findMinArrowShots(vector>& points) {
8 | if (points.size() == 0) return 0;
9 | sort(points.begin(), points.end(), cmp);
10 | int cnt = 1;
11 | int r = points[0][1];
12 | for(auto &p: points){
13 | if (p[0] > r){
14 | ++cnt;
15 | r = p[1];
16 | }
17 | }
18 | return cnt;
19 | }
20 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0455.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int findContentChildren(vector& g, vector& s) {
4 | sort(g.begin(), g.end());
5 | sort(s.begin(), s.end());
6 | int i = 0, j = 0, cnt = 0;
7 | while(i< g.size() && j < s.size()){
8 | if (g[i] <= s[j]){
9 | ++cnt;
10 | ++i;
11 | ++j;
12 | }
13 | else{
14 | ++j;
15 | }
16 | }
17 | return cnt;
18 | }
19 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0459.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def repeatedSubstringPattern(self, s: str) -> bool:
3 | return s in (s + s)[1:-1]
4 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0461.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def hammingDistance(self, x: int, y: int) -> int:
3 | # if x == y:
4 | # return 0
5 | # x &= 0xFFFFFFFF
6 | # y &= 0xFFFFFFFF
7 | # x, y = bin(x)[2:], bin(y)[2:]
8 | # x = x.rjust(32, '0')
9 | # y = y.rjust(32, '0')
10 | # res = 0
11 | # for i, j in zip(x, y):
12 | # # print(i, j )
13 | # if i != j:
14 | # res += 1
15 | # return res
16 | return bin(x ^ y).count('1')
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0482.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | string licenseKeyFormatting(string S, int K) {
4 | string ret;
5 | int cnt = 0;
6 | for(auto it = S.rbegin(); it != S.rend(); ++it){
7 | if(isalnum(*it)) {
8 | if(cnt == K){ret += '-'; cnt = 0;}
9 | ret += toupper(*it);
10 | ++cnt;
11 | }
12 | }
13 | return {ret.rbegin(), ret.rend()};
14 | }
15 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0485.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
3 | if not nums:
4 | return 0
5 | l, r = 0, 0
6 | res = 0
7 | while r < len(nums):
8 | if nums[l] == 1:
9 | if nums[r] == 1:
10 | res = max(res, r - l + 1)
11 | r += 1
12 | else:
13 | l = r + 1
14 | r = l
15 | else:
16 | l += 1
17 | r = l
18 | return res
19 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0487.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int findMaxConsecutiveOnes(vector& nums) {
4 | int ret = 0, cur = 0, pcur = -1;
5 | for(auto n: nums){
6 | if(n == 0){
7 | ret = max(ret, pcur + cur + 1);
8 | pcur = cur;
9 | cur = 0;
10 | }
11 | else{
12 | ++cur;
13 | }
14 | }
15 | if(pcur != -1) ret = max(ret, pcur + cur + 1);
16 | else ret = max(ret, cur);
17 |
18 | return ret;
19 |
20 | }
21 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0494.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findTargetSumWays(self, nums: List[int], S: int) -> int:
3 | d = {}
4 | n = len(nums)
5 |
6 | def dfs(idx, cur):
7 | if idx != n and (idx, cur) not in d:
8 | d[(idx, cur)] = dfs(idx + 1, cur + nums[idx]) + dfs(idx + 1, cur - nums[idx])
9 | # print(idx, cur, d.get((idx, cur)))
10 | return d.get((idx, cur), int(cur == S))
11 |
12 | return dfs(0, 0)
13 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0495.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
3 | res = 0
4 | n = len(timeSeries)
5 | for idx, val in enumerate(timeSeries):
6 | if idx < n - 1 and val + duration > timeSeries[idx + 1]:
7 | res += timeSeries[idx + 1] - val
8 | else:
9 | res += duration
10 | return res
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0496.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
3 | stack, hashmap = [], {}
4 | for num in nums2:
5 | while stack and stack[-1] < num:
6 | hashmap[stack.pop()] = num
7 | stack.append(num)
8 | return [hashmap.get(num, - 1) for num in nums1]
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0502.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
6 | c_p = list(zip(Capital, Profits))
7 | import heapq
8 | heapq.heapify(c_p)
9 | heap = []
10 | res = W
11 | for i in range(k):
12 | while c_p and c_p[0][0] <= res:
13 | heapq.heappush(heap, -heapq.heappop(c_p)[1])
14 | if heap:
15 | res -= heapq.heappop(heap)
16 | return res
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0503.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def nextGreaterElements(self, nums: List[int]) -> List[int]:
3 | nums += nums
4 | res = [-1] * len(nums)
5 | stack = []
6 | for idx, num in enumerate(nums):
7 | while stack and stack[-1][0] < num:
8 | _, iidx = stack.pop()
9 | res[iidx] = num
10 | stack.append([num, idx])
11 | return res[: len(res) // 2]
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0504.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def convertToBase7(self, num: int) -> str:
3 | if num == 0:
4 | return '0'
5 | res = ''
6 | ispos = True
7 | if num < 0:
8 | ispos = False
9 | num = abs(num)
10 | while num:
11 | res = str(num - num // 7 * 7) + res
12 | num //= 7
13 | if not ispos:
14 | res = '-' + res
15 | return res
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0509.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def fib(self, N: int) -> int:
3 | memory = {0: 0, 1: 1}
4 |
5 | def helper(n):
6 | print(memory)
7 | if n in memory:
8 | return memory[n]
9 | tmp = helper(n - 1) + helper(n - 2)
10 | memory[n] = tmp
11 | return tmp
12 |
13 | return helper(N)
14 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0511.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | player_id, min(event_date) as first_login
4 | from
5 | Activity
6 | group by
7 | player_id;
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0512.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | player_id, device_id
4 | from
5 | activity
6 | where (player_id, event_date) in (
7 | select player_id, min(event_date)
8 | from
9 | activity
10 | group by player_id
11 | );
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0518.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int change(int amount, vector& coins) {
4 | vector res(amount+1, 0);
5 | res[0] = 1;
6 | for (int coin: coins){
7 | if (coin ==0) continue;
8 | for (int i=coin; i TreeNode:
10 | tmp = 0
11 |
12 | def helper(node):
13 | nonlocal tmp
14 | if node:
15 | helper(node.right)
16 | tmp += node.val
17 | node.val = tmp
18 | helper(node.left)
19 |
20 | helper(root)
21 | return root
22 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0557.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reverseWords(self, s: str) -> str:
3 | res, blank = '', False
4 | for _ in s[::-1]:
5 | res += _
6 | return ' '.join(res.split()[::-1])
7 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0559.py:
--------------------------------------------------------------------------------
1 | """
2 | # Definition for a Node.
3 | class Node:
4 | def __init__(self, val=None, children=None):
5 | self.val = val
6 | self.children = children
7 | """
8 |
9 |
10 | class Solution:
11 | def maxDepth(self, root: 'Node') -> int:
12 |
13 | def helper(node):
14 | if not node:
15 | return 0
16 | if not node.children:
17 | return 1
18 | return max([helper(child) for child in node.children]) + 1
19 |
20 | return helper(root)
21 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0561.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def arrayPairSum(self, nums: List[int]) -> int:
3 | nums.sort()
4 | return sum([nums[_] for _ in range(0, len(nums), 2)])
5 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0563.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution:
9 | def findTilt(self, root: TreeNode) -> int:
10 | ret = 0
11 |
12 | def helper(node):
13 | nonlocal ret
14 | if not node: return 0
15 | l = helper(node.left)
16 | r = helper(node.right)
17 | ret += abs(l - r);
18 | return l + r + node.val
19 |
20 | helper(root)
21 | return ret
22 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0577.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | name, bonus
4 | from employee left outer join bonus
5 | on employee.empid = bonus.empid
6 | where bonus is null or bonus < 1000;
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0584.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | name
4 | from
5 | customer
6 | where
7 | referee_id <> 2 or referee_id is null;
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0586.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | customer_number
4 | from
5 | orders
6 | group by
7 | customer_number
8 | order by
9 | count(*) desc
10 | limit 0, 1;
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0595.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | name, population, area
4 | from
5 | world
6 | where
7 | population > 25000000 or area > 3000000
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0596.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select
3 | class
4 | from
5 | courses
6 | group by class
7 | having count(distinct student) > 4;
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0599.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
3 | res = []
4 | d1 = {k: v for k, v in zip(list1, range(len(list1)))}
5 | d2 = {k: v for k, v in zip(list2, range(len(list2)))}
6 | rests = set(list1) & set(list2)
7 | minval = float('inf')
8 | for rest in rests:
9 | cur = d1[rest] + d2[rest]
10 | if cur < minval:
11 | res = []
12 | minval = cur
13 | res.append(rest)
14 | elif cur == minval:
15 | res.append(rest)
16 | return res
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0603.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select distinct a.seat_id
3 | from
4 | cinema as a,
5 | cinema as b
6 | where
7 | a.free = 1 and b.free = 1 and (a.seat_id + 1 = b.seat_id or a.seat_id - 1 = b.seat_id);
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0605.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
3 | cnt, pre = 0, 0
4 | length = len(flowerbed)
5 | flowers = flowerbed + [0]
6 | for idx, _ in enumerate(flowerbed):
7 | next_ = flowers[idx]
8 | if not _:
9 | print(cnt, idx, pre, flowers[idx + 1])
10 | if not pre and not flowers[idx + 1]:
11 | cnt += 1
12 | pre = 1
13 | else:
14 | pre = _
15 | else:
16 | pre = _
17 |
18 | print(cnt)
19 | return cnt >= n
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0622.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/LeetCodeSolutions/LeetCode_0622.py
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0649.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 |
4 | class Solution:
5 | def predictPartyVictory(self, senate: str) -> str:
6 | qs = deque()
7 | qd = deque()
8 | for i, s in enumerate(senate):
9 | if s == 'R':
10 | qs.append(i);
11 | else:
12 | qd.append(i);
13 | n = len(senate)
14 | while qs and qd:
15 | s, d = qs.popleft(), qd.popleft()
16 | if s < d:
17 | qs.append(s + n);
18 | else:
19 | qd.append(d + n);
20 | if qs: return 'Radiant'
21 | return 'Dire'
22 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0650.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minSteps(self, n):
3 | """
4 | :type n: int
5 | :rtype: int
6 | """
7 | num = 0
8 | d = 2
9 | ans = 0
10 | while n > 1:
11 | while n % d == 0:
12 | ans += d
13 | n /= d
14 | d += 1
15 | return ans
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0651.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxA(self, N: int) -> int:
3 | dp = [0, 1]
4 | for i in range(2, N + 1):
5 | dp.append(dp[-1] + 1)
6 | for k in range(i - 2, 0, -1):
7 | dp[-1] = max(dp[-1], dp[k] * (i - k - 1))
8 | return dp[-1]
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0657.py:
--------------------------------------------------------------------------------
1 | import collections
2 |
3 |
4 | class Solution:
5 | def judgeCircle(self, moves: str) -> bool:
6 | counter = collections.Counter(moves)
7 | if counter.get('U', 0) != counter.get('D', 0):
8 | return False
9 | if counter.get('L', 0) != counter.get('R', 0):
10 | return False
11 | return True
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0674.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int findLengthOfLCIS(vector& nums) {
4 | int ret = 0;
5 | int l = 0, r = 0;
6 | while(r < nums.size()){
7 | if(r > 0 && nums[r] <= nums[r - 1]) l = r;
8 | ret = max(r - l + 1, ret);
9 | ++r;
10 | }
11 | return ret;
12 |
13 | }
14 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0680.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def validPalindrome(self, s: str) -> bool:
3 | i = 0
4 | j = len(s) - 1
5 | while i < j:
6 | if s[i] == s[j]:
7 | i += 1
8 | j -= 1
9 | else:
10 | a = s[i + 1: j + 1]
11 | b = s[i: j]
12 | return a == a[::-1] or b == b[::-1]
13 | return True
14 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0683.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int kEmptySlots(vector& bulbs, int K) {
4 | set f;
5 | for(int i = 0; i < bulbs.size(); ++i){
6 | auto b = bulbs[i];
7 | auto it = f.insert(b).first;
8 | if(it != f.end()){
9 | auto nxt = next(it);
10 | if (*nxt - *it == K + 1) return i + 1;
11 |
12 | }
13 | if(it != f.begin()){
14 | auto pre = prev(it);
15 | if(*it - *pre == K + 1) return i + 1;
16 | }
17 | }
18 | return -1;
19 | }
20 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0692.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 | import collections
3 |
4 |
5 | class Solution:
6 | def topKFrequent(self, words: List[str], k: int) -> List[str]:
7 | counter = collections.Counter(words)
8 | heap = [[-v, k] for (k, v) in counter.items()]
9 | import heapq
10 | heapq.heapify(heap)
11 | return [heapq.heappop(heap)[1] for _ in range(k)]
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0700.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution:
9 | def searchBST(self, root: TreeNode, val: int) -> TreeNode:
10 | if not root:
11 | return None
12 | if root.val == val:
13 | return root
14 | return self.searchBST(root.left, val) if root.val > val else self.searchBST(root.right, val)
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0704.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def search(self, nums: List[int], target: int) -> int:
3 | l, r = 0, len(nums)
4 | if l == r:
5 | return -1
6 | while l < r:
7 | mid = (l + r) // 2
8 | if nums[mid] < target:
9 | l = mid + 1
10 | elif nums[mid] > target:
11 | r = mid
12 | else:
13 | return mid
14 | return -1
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0709.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def toLowerCase(self, str: str) -> str:
3 | res = ''
4 | for s in str:
5 | if 'A' <= s <= 'Z':
6 | res += chr(ord(s) + 32)
7 | else:
8 | res += s
9 | return res
10 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0714.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxProfit(self, prices: List[int], fee: int) -> int:
3 | if not prices:
4 | return 0
5 | # [0 buy, 1 sell, 2 have, 3 not]
6 | dp = [-prices[0] - fee, 0, -prices[0] - fee, 0]
7 | for i in range(1, len(prices)):
8 | pre = dp[:]
9 | dp[0] = max(pre[1], pre[3]) - prices[i] - fee
10 | dp[1] = max(pre[0], pre[2]) + prices[i]
11 | dp[2] = max(pre[2], dp[0])
12 | dp[3] = max(dp[1], pre[3])
13 | return max(dp[1], dp[3])
14 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0717.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isOneBitCharacter(self, bits):
3 | """
4 | :type bits: List[int]
5 | :rtype: bool
6 | """
7 | i = 0
8 | flag = False
9 | while (i < len(bits)):
10 | if bits[i] == 1:
11 | i += 2
12 | else:
13 | i += 1
14 | if i == len(bits):
15 | flag = True
16 | return flag
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0724.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def pivotIndex(self, nums: List[int]) -> int:
3 | if not nums:
4 | return -1
5 | mid = 0
6 | left = 0
7 | right = sum(nums[mid + 1:])
8 | if left == right:
9 | return mid
10 | while mid < len(nums) - 1 and left != right:
11 | left += nums[mid]
12 | right -= nums[mid + 1]
13 | # print(left, right, mid)
14 | mid += 1
15 | if left == right:
16 | return mid
17 | return -1
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0739.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector dailyTemperatures(vector& T) {
4 | int n = T.size();
5 | vector res(n, 0);
6 | vector> stack;
7 | for(int i = n - 1; i > -1; --i){
8 | while (!stack.empty() && T[i] >= stack.back().first) stack.pop_back();
9 | if(stack.empty()) res[i] = 0;
10 | else res[i] = stack.back().second - i;
11 | stack.push_back(make_pair(T[i], i));
12 | }
13 | return res;
14 |
15 | }
16 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0739.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def dailyTemperatures(self, T: List[int]) -> List[int]:
6 | """
7 | Use stack
8 | """
9 | ans = [0] * len(T)
10 | stack = []
11 | for _ in range(len(T) - 1, -1, -1):
12 | while stack and T[_] >= T[stack[-1]]:
13 | stack.pop()
14 | if stack:
15 | ans[_] = stack[-1] - _
16 | stack.append(_)
17 | return ans
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0744.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def nextGreatestLetter(self, letters: List[str], target: str) -> str:
3 | lo, hi = 0, len(letters)
4 | while lo < hi:
5 | mid = (lo + hi) // 2
6 | if letters[mid] <= target:
7 | lo = mid + 1
8 | else:
9 | hi = mid
10 | return letters[lo % len(letters)]
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0746.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int minCostClimbingStairs(vector& cost) {
4 | int a = cost[0], b = cost[1];
5 | for(int i = 2; i < cost.size(); ++i){
6 | int c = min(a, b) + cost[i];
7 | a = b;
8 | b = c;
9 | }
10 | return min(a, b);
11 | }
12 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0753.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def crackSafe(self, n: int, k: int) -> str:
3 | seen = set()
4 | highest = 10 ** (n - 1)
5 | ret = []
6 |
7 | def dfs(node):
8 | for x in range(k):
9 | _node = node * 10 + x
10 | if _node not in seen:
11 | seen.add(_node)
12 | dfs(_node % highest)
13 | ret.append(str(x))
14 |
15 | dfs(0)
16 | # print(ret)
17 | return ''.join(ret) + '0' * (n - 1)
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0769.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int maxChunksToSorted(vector& arr) {
4 | int n = arr.size();
5 | int cnt = 0;
6 | int maxV = 0;
7 | for (int i = 0; i < n; ++ i){
8 | maxV = max(maxV, arr[i]);
9 | if (i >= maxV) ++cnt;
10 | }
11 | return cnt;
12 | }
13 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0771.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def numJewelsInStones(self, J: str, S: str) -> int:
3 | hashset = set(J)
4 | res = 0
5 | for s in S:
6 | if s in hashset:
7 | res += 1
8 | return res
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0787.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | const int INF = 1e9;
4 | int findCheapestPrice(int n, vector>& flights, int src, int dst, int K) {
5 | K = min(K, n - 2);
6 | vector dp(n, INF);
7 | dp[src] = 0;
8 | for (int k = 0; k <= K; ++k) {
9 | vector dp1 = dp;
10 | for(auto& e: flights) {
11 | if (dp1[e[0]] == INF) continue;
12 | dp1[e[1]] = min(dp1[e[1]], dp[e[0]] + e[2]);
13 | }
14 | swap(dp1, dp);
15 | }
16 | return dp[dst] == INF ? -1 : dp[dst];
17 | }
18 | };
19 |
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0788.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def rotatedDigits(self, N: int) -> int:
3 | d = dict(zip([0, 1, 2, 5, 6, 8, 9], [0, 1, 5, 2, 9, 8, 6]))
4 | cnt = 0
5 | for i in range(1, N + 1):
6 | str_i = str(i)
7 | tmp = ''
8 | isvalid = True
9 | for s in str_i:
10 | if int(s) in d:
11 | tmp += str(d[int(s)])
12 | else:
13 | isvalid = False
14 | break
15 | if isvalid and tmp != str_i:
16 | cnt += 1
17 | return cnt
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0830.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def largeGroupPositions(self, s: str) -> List[List[int]]:
3 | l, r, n = 0, 0, len(s)
4 | ret = []
5 | while r < n:
6 | while r < n and s[l] == s[r]:
7 | r += 1;
8 | if r - l > 2:
9 | ret.append([l, r - 1])
10 | l = r
11 | return ret
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0836.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
6 | return not (
7 | rec1[3] <= rec2[1] or
8 | rec1[1] >= rec2[3] or
9 | rec1[0] >= rec2[2] or
10 | rec1[2] <= rec2[0])
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0841.py:
--------------------------------------------------------------------------------
1 | import collections
2 |
3 |
4 | class Solution:
5 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
6 | visited = set()
7 | n = len(rooms)
8 | que = collections.deque()
9 | que.append(0)
10 | visited.add(0)
11 | while que:
12 | _r = que.popleft()
13 | for _room in rooms[_r]:
14 | if _room not in visited:
15 | visited.add(_room)
16 | que.append(_room)
17 | return len(visited) == n
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0844.py:
--------------------------------------------------------------------------------
1 | def _pre(s):
2 | stack = []
3 | for c in s:
4 | if c == '#':
5 | if stack:
6 | stack.pop()
7 | else:
8 | stack.append(c)
9 | return stack
10 |
11 |
12 | class Solution:
13 | def backspaceCompare(self, S: str, T: str) -> bool:
14 | return _pre(S) == _pre(T)
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0852.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int peakIndexInMountainArray(vector& A) {
4 | int ret = 0;
5 | for(int idx = 0; idx != A.size(); ++idx){
6 | if (idx == 0 || idx == A.size() - 1) continue;
7 | if (A[idx] > A[idx - 1] && A[idx] > A[idx + 1]){
8 | ret = idx;
9 | break;
10 | }
11 | }
12 | return ret;
13 | }
14 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0856.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def scoreOfParentheses(self, S: str) -> int:
3 | stack = [0]
4 | for s in S:
5 | if s == '(':
6 | stack.append(0)
7 | else:
8 | tmp = max(2 * stack.pop(), 1)
9 | stack[-1] += tmp
10 | return stack[0]
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0868.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def binaryGap(self, N: int) -> int:
3 | str_n = bin(N)[2:]
4 | ans = 0
5 | idxs = []
6 | for idx, val in enumerate(str_n):
7 | if val == '1':
8 | if idxs:
9 | ans = max(ans, idx - idxs[-1])
10 | idxs.append(idx)
11 | return ans
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0872.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def leafSimilar(self, root1, root2):
3 | def dfs(node):
4 | if node:
5 | if not node.left and not node.right:
6 | yield node.val
7 | yield from dfs(node.left)
8 | yield from dfs(node.right)
9 |
10 | return list(dfs(root1)) == list(dfs(root2))
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0876.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | class ListNode:
3 | def __init__(self, x):
4 | self.val = x
5 | self.next = None
6 |
7 |
8 | class Solution:
9 | def middleNode(self, head: ListNode) -> ListNode:
10 | dummy = ListNode(None)
11 | dummy.next = head
12 | p = pp = dummy
13 | while pp:
14 | p = p.next
15 | if pp.next:
16 | pp = pp.next.next
17 | else:
18 | pp = pp.next
19 | return p
20 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0901.py:
--------------------------------------------------------------------------------
1 | class StockSpanner:
2 |
3 | def __init__(self):
4 | self.stack = []
5 |
6 | def next(self, price: int) -> int:
7 | d = 1
8 | while self.stack and price >= self.stack[-1][0]:
9 | d += self.stack.pop()[1]
10 | self.stack.append([price, d])
11 | return d
12 |
13 | # Your StockSpanner object will be instantiated and called as such:
14 | # obj = StockSpanner()
15 | # param_1 = obj.next(price)
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0904.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int totalFruit(vector& tree) {
4 | int ret = 0, l = 0, r = 0;
5 | unordered_map counter;
6 | while (r < tree.size()){
7 | ++counter[tree[r]];
8 | while (counter.size() > 2){
9 | --counter[tree[l]];
10 | if(counter[tree[l]] == 0) counter.erase(tree[l]);
11 | ++l;
12 | }
13 | ret = max(ret, r - l + 1);
14 | ++r;
15 | }
16 | return ret;
17 | }
18 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0914.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def hasGroupsSizeX(self, deck: List[int]) -> bool:
3 | n = len(deck)
4 | if n < 2:
5 | return False
6 | from collections import Counter
7 | counter = Counter(deck)
8 | nums = list(counter.values())
9 | import math
10 | for idx, val in enumerate(nums):
11 | if idx == 0:
12 | cur = val
13 | else:
14 | cur = math.gcd(cur, val)
15 | if cur < 2:
16 | return False
17 | return True
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0922.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector sortArrayByParityII(vector& A) {
4 | vector odd;
5 | for(int i = 0; i < A.size(); i += 2){
6 | if (A[i]&1) odd.push_back(i);
7 | }
8 | int t = 0;
9 | for (int j = 1; j < A.size(); j += 2){
10 | if ((A[j] & 1) == 0){
11 | swap(A[j], A[odd[t]]);
12 | ++t;
13 | }
14 | }
15 | return A;
16 | }
17 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0937.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reorderLogFiles(self, logs: List[str]) -> List[str]:
3 | nums = []
4 | alphas = []
5 | for strs in logs:
6 | if '0' <= strs[-1] <= '9':
7 | nums.append(strs)
8 | else:
9 | alphas.append(strs)
10 | alphas.sort(key=lambda x: x.split(None, 1)[::-1])
11 | return alphas + nums
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0941.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def validMountainArray(self, A: List[int]) -> bool:
3 | if len(A) < 3:
4 | return False
5 | mid, m = -1, -1
6 | for idx, val in enumerate(A):
7 | if val > m:
8 | m = val
9 | mid = idx
10 | if mid == 0 or mid == len(A) - 1:
11 | return False
12 | for k in range(mid + 1, len(A)):
13 | if A[k] >= A[k - 1]:
14 | return False
15 | for k in range(0, mid):
16 | if A[k] >= A[k + 1]:
17 | return False
18 | return True
19 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0946.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
3 | if not pushed and not popped:
4 | return True
5 | aux = []
6 | idx = 0
7 | for _ in pushed:
8 | aux.append(_)
9 | while aux and aux[-1] == popped[idx]:
10 | aux.pop()
11 | idx += 1
12 | return not aux
13 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0953.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def isAlienSorted(self, words: List[str], order: str) -> bool:
6 | return words == sorted(words, key=lambda x: list(map(order.index, x)))
7 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0954.cpp:
--------------------------------------------------------------------------------
1 | bool cmp(int a, int b){
2 | if (a * b <= 0) return a < b;
3 | if (a < 0) return abs(a) < abs(b);
4 | return a < b;
5 | }
6 |
7 | class Solution {
8 | public:
9 | bool canReorderDoubled(vector& A) {
10 | sort(A.begin(), A.end(), cmp);
11 | for(auto v: A) cout << v << ' ';
12 | unordered_map cnt;
13 | for(int i = 0; i < A.size(); ++i){
14 | if (A[i] == 0) continue;
15 | if (cnt[A[i]]) --cnt[A[i]];
16 | else ++cnt[A[i] * 2];
17 | }
18 | for(auto &kv: cnt) if (kv.second) return false;
19 | return true;
20 | }
21 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0962.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxWidthRamp(self, A: List[int]) -> int:
3 | ans = 0
4 | stack = []
5 | for idx, val in enumerate(A):
6 | if not stack or stack[-1][0] > val:
7 | stack.append([val, idx])
8 | n = len(A)
9 | for i in range(n - 1, -1, -1):
10 | if stack and i == stack[-1][1]:
11 | stack.pop()
12 | while stack and A[i] >= stack[-1][0]:
13 | ans = max(ans, i - stack[-1][1])
14 | stack.pop()
15 | return ans
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0974.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def subarraysDivByK(self, A: List[int], K: int) -> int:
3 | d = {0: 1}
4 | m, ans = 0, 0
5 | for elem in A:
6 | m = (m + elem) % K
7 | t = d.get(m, 0);
8 | ans += t
9 | d[m] = t + 1
10 | return ans
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0976.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int largestPerimeter(vector& A) {
4 | sort(A.begin(), A.end());
5 | for(int i = A.size() - 1; i >= 2; --i){
6 | if (A[i - 2] + A[i - 1] > A[i])
7 | return A[i - 2] + A[i - 1] + A[i];
8 | }
9 | return 0;
10 | }
11 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0977.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def sortedSquares(self, A: List[int]) -> List[int]:
3 | A.sort(key=lambda x: abs(x))
4 | return [i ** 2 for i in A]
5 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0989.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector addToArrayForm(vector& A, int K) {
4 | vector ans;
5 | int i = A.size() - 1, carry = 0;
6 | while (i > -1 || K || carry){
7 | int x = i < A.size()? A[i]: 0;
8 | int y = K % 10;
9 | int t = x + y + carry;
10 | ans.push_back(t % 10);
11 | carry = t / 10;
12 | K /= 10;
13 | --i;
14 | }
15 | return {ans.rbegin(), ans.rend()};
16 | }
17 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0991.py:
--------------------------------------------------------------------------------
1 | #
2 | # @lc app=leetcode.cn id=991 lang=python3
3 | #
4 | # [991] 坏了的计算器
5 | #
6 |
7 | # @lc code=start
8 | class Solution:
9 | def brokenCalc(self, X: int, Y: int) -> int:
10 | ret = 0
11 | while Y > X:
12 | if Y & 1:
13 | Y += 1
14 | else:
15 | Y //= 2
16 | ret += 1
17 | return ret + X - Y
18 | # @lc code=end
19 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_0997.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int findJudge(int N, vector>& trust) {
4 | vector idegree(N, 0), odegree(N, 0);
5 | for(auto a: trust){
6 | int i = a[0] - 1, j = a[1] - 1;
7 | ++odegree[i];
8 | ++idegree[j];
9 | }
10 | for(int i = 0; i < N; ++i){
11 | if (idegree[i] == N - 1 && odegree[i] == 0) return i + 1;
12 | }
13 | return -1;
14 | }
15 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1002.py:
--------------------------------------------------------------------------------
1 | from collections import Counter
2 |
3 |
4 | class Solution:
5 | def commonChars(self, A: List[str]) -> List[str]:
6 | ret = Counter(A[0])
7 | for word in A[1:]:
8 | tmp = Counter(word)
9 | r = {}
10 | for k in ret:
11 | if k in tmp:
12 | r[k] = min(ret[k], tmp[k])
13 | ret = r
14 | s = ""
15 | for k in ret:
16 | s += k * ret[k]
17 | return list(s)
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1013.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def canThreePartsEqualSum(self, A: List[int]) -> bool:
6 | sums = sum(A)
7 | if sums % 3:
8 | return False
9 | sums //= 3
10 | cur_sum, cnt = 0, 0
11 | for tmp in A:
12 | cur_sum += tmp
13 | if cur_sum == sums:
14 | cnt += 1
15 | cur_sum = 0
16 | return cnt >= 3
17 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1014.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int maxScoreSightseeingPair(vector& A) {
4 | int n = A.size(), pmax = A[0];
5 | int ans = 0;
6 | for (int i = 1; i < n; ++i){
7 | ans = max(pmax + A[i] - i, ans);
8 | pmax = max(pmax, A[i] + i);
9 | }
10 | return ans;
11 | }
12 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1018.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def prefixesDivBy5(self, A: List[int]) -> List[bool]:
3 | prefix = []
4 | for idx, val in enumerate(A):
5 | if idx == 0:
6 | prefix.append(val)
7 | else:
8 | prefix.append(val + (prefix[-1] << 1))
9 | res = []
10 | for v in prefix:
11 | res.append(v % 5 == 0)
12 | return res
13 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1024.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def videoStitching(self, clips: List[List[int]], T: int) -> int:
3 | maxn = [0] * T
4 | for a, b in clips:
5 | if a < T:
6 | maxn[a] = max(maxn[a], b)
7 | last = pre = ret = 0
8 | for i in range(T):
9 | last = max(last, maxn[i])
10 | if i == last:
11 | return -1
12 | if i == pre:
13 | ret += 1
14 | pre = last
15 | return ret
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1033.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def numMovesStones(self, a: int, b: int, c: int) -> List[int]:
3 | a, b, c = sorted([a, b, c])
4 | maximum_moves = c - b - 1 + b - a - 1
5 | if c - b == 1 and b - a == 1:
6 | minimum_moves = 0
7 | elif c - b == 2 or b - a == 2:
8 | minimum_moves = 1
9 | elif c - b == 1 or b - a == 1:
10 | minimum_moves = 1
11 | else:
12 | minimum_moves = 2
13 |
14 | return [minimum_moves, maximum_moves]
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1035.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int maxUncrossedLines(vector& A, vector& B) {
4 | int m = A.size(), n = B.size();
5 | vector > dp(m + 1, vector(n + 1, 0));
6 | for (int i = 1; i <= m; ++ i)
7 | for(int j = 1; j <=n; ++ j){
8 | if (A[i - 1] == B[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
9 | else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
10 | }
11 | return dp.back().back();
12 | }
13 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1041.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool isRobotBounded(string instructions) {
4 | int dirs[4][2] = { {1, 0}, {0, -1}, {-1, 0}, {0, 1}};
5 | int x = 0, y = 0, d = 0;
6 | for(auto ins: instructions){
7 | if (ins == 'G'){
8 | x += dirs[d][0];
9 | y += dirs[d][1];
10 | }
11 | else{
12 | if (ins == 'L') d = (d + 3) % 4;
13 | else d = (d + 1) % 4;
14 | }
15 | }
16 | return (x == 0 && y == 0) || (d != 0);
17 | }
18 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1056.cpp:
--------------------------------------------------------------------------------
1 | const int dict[] ={0, 1, -1, -1, -1, -1, 9, -1, 8, 6};
2 | class Solution {
3 | public:
4 | bool confusingNumber(int N) {
5 | int tmp = N, ret = 0;
6 | while(tmp){
7 | if (dict[tmp % 10] == -1){
8 | return false;
9 | }
10 | ret *= 10;
11 | ret += dict[tmp % 10];
12 | tmp /= 10;
13 | }
14 | return ret != N;
15 | }
16 | };l
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1062.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def longestRepeatingSubstring(self, S: str) -> int:
3 | lo, hi = 1, len(S)
4 |
5 | def isRepeat(l):
6 | n = len(S)
7 | visietd = set()
8 | for i in range(0, n - l + 1):
9 | tmp = S[i: i + l]
10 | if tmp in visietd:
11 | return True
12 | visietd.add(tmp)
13 | return False
14 |
15 | while lo < hi:
16 | mid = (lo + hi) // 2
17 | if isRepeat(mid):
18 | lo = mid + 1
19 | else:
20 | hi = mid
21 | return lo - 1
22 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1071.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def gcdOfStrings(self, str1: str, str2: str) -> str:
3 | n = math.gcd(len(str1), len(str2))
4 | if str1 + str2 == str2 + str1:
5 | return str1[:n]
6 | return ''
7 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1079.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def numTilePossibilities(self, tiles: str) -> int:
3 | used = set([''])
4 | c = list(tiles)
5 | v = [False] * len(c)
6 | ret = 0
7 |
8 | def helper(cur):
9 | nonlocal ret
10 | if cur not in used:
11 | ret += 1
12 | used.add(cur)
13 | for idx, v_ in enumerate(v):
14 | if not v_:
15 | v[idx] = True
16 | helper(cur + c[idx])
17 | v[idx] = False
18 |
19 | helper('')
20 | return ret
21 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1082.sql:
--------------------------------------------------------------------------------
1 | # Write your MySQL query statement below
2 | select seller_id
3 | from sales
4 | group by seller_id
5 | having sum(price) =
6 | (select sum(price) as sellsum
7 | from sales
8 | group by seller_id
9 | order by sellsum desc
10 | limit 1);
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1094.py:
--------------------------------------------------------------------------------
1 | from collections import defaultdict
2 |
3 |
4 | class Solution:
5 | def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
6 | d = defaultdict(int)
7 | for n, s, e in trips:
8 | d[s] += n
9 | d[e] -= n
10 | kvs = list(d.items())
11 | kvs.sort()
12 | cur = 0
13 | for _, n in kvs:
14 | cur += n
15 | if cur > capacity:
16 | return False
17 | return True
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1099.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def twoSumLessThanK(self, A: List[int], K: int) -> int:
3 | A.sort()
4 | n = len(A)
5 | ans = -1
6 | for l in range(n - 1):
7 | r = n - 1
8 | while l < r:
9 | tmp = A[l] + A[r]
10 | if tmp >= K:
11 | r -= 1
12 | else:
13 | ans = max(tmp, ans)
14 | break
15 | return ans
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1109.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector corpFlightBookings(vector>& bookings, int n) {
4 | vector ret(n, 0);
5 | for (auto &b: bookings){
6 | ret[b[0] - 1] += b[2];
7 | if (b[1] < n){
8 | ret[b[1]] -= b[2];
9 | }
10 | }
11 | for(int i = 1; i < n; ++i) ret[i] += ret[i - 1];
12 | return ret;
13 | }
14 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1111.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def maxDepthAfterSplit(self, seq: str) -> List[int]:
6 | res = []
7 | d = 0
8 | for s in seq:
9 | if s == '(':
10 | d += 1
11 | res.append(d % 2)
12 | else:
13 | res.append(d % 2)
14 | d -= 1
15 | return res
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1134.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool isArmstrong(int N) {
4 | int t = N, k = 0, ret = 0;
5 | while (t){
6 | ++k;
7 | t /= 10;
8 | }
9 | t = N;
10 | while(t){
11 | int c = t % 10;
12 | ret += pow(c, k);
13 | t /= 10;
14 | }
15 | return ret == N;
16 | }
17 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1154.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int dayOfYear(string date) {
4 | int months[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
5 | int year = stoi(date.substr(0, 4)), month = stoi(date.substr(5, 2)), day = stoi(date.substr(8, 2));
6 | bool isleap = false;
7 | if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) isleap = true;
8 | if (isleap) ++months[2];
9 | int ret = 0;
10 | for(int i = 1; i < month; ++i) ret += months[i];
11 | ret += day;
12 | return ret;
13 | }
14 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1160.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def countCharacters(self, words: List[str], chars: str) -> int:
6 | ans = 0
7 | cnt = collections.Counter(chars)
8 | for w in words:
9 | c = collections.Counter(w)
10 | if all([c[i] <= cnt[i] for i in c]):
11 | ans += len(w)
12 | return ans
13 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1190.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reverseParentheses(self, s: str) -> str:
3 | stack = []
4 | for _ in s:
5 | if _ == ')':
6 | tmp = stack.pop()
7 | stack2 = []
8 | while tmp != '(':
9 | stack2.append(tmp)
10 | tmp = stack.pop()
11 | stack.extend(stack2)
12 | else:
13 | stack.append(_)
14 | return ''.join(stack)
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1207.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def uniqueOccurrences(self, arr: List[int]) -> bool:
3 | counter = collections.Counter(arr)
4 | s = set()
5 | for k, v in counter.items():
6 | if v not in s:
7 | s.add(v)
8 | else:
9 | return False
10 | return True
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1229.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:
3 | slots1.sort()
4 | slots2.sort()
5 | i = j = 0
6 | while i < len(slots1) and j < len(slots2):
7 | s1, e1 = slots1[i]
8 | s2, e2 = slots2[j]
9 | ss = max(s1, s2)
10 | ee = min(e1, e2)
11 | if ee - ss >= duration:
12 | return [ss, ss + duration]
13 | if e1 < e2:
14 | i += 1
15 | else:
16 | j += 1
17 | return []
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1232.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool checkStraightLine(vector>& coordinates) {
4 | int x1 = coordinates[0][0], y1 = coordinates[0][1], x2 = coordinates[1][0], y2 = coordinates[1][1];
5 | for(int i = 2; i < coordinates.size(); ++i){
6 | int x = coordinates[i][0], y = coordinates[i][1];
7 | if ((y2 - y1) * (x - x1) == (y - y1) * (x2 - x1)) continue;
8 | return false;
9 | }
10 | return true;
11 | }
12 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1232.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
3 | if len(coordinates) < 3:
4 | return True
5 | p0, p1 = coordinates[0], coordinates[1]
6 |
7 | def helper(p):
8 | return (p[0] - p0[0]) * (p1[1] - p0[1]) == (p[1] - p0[1]) * (p1[0] - p0[0])
9 |
10 | for p in coordinates[2:]:
11 | if not helper(p):
12 | return False
13 | return True
14 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1248.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int numberOfSubarrays(vector& nums, int k) {
4 | int n = nums.size();
5 | int odd[n + 2], cnt = 0, res = 0;
6 | for (int i = 0; i != nums.size(); ++i){
7 | if (nums[i] &1) odd[++cnt] = i;
8 | }
9 | odd[0] = -1; odd[++cnt] = n;
10 | for(int i = 0; i + k + 1 <= cnt; ++i){
11 | res += (odd[i + 1] - odd[i]) * (odd[i + k + 1] - odd[i + k]);
12 | }
13 | return res;
14 | }
15 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1249.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minRemoveToMakeValid(self, s: str) -> str:
3 | stack = []
4 | res = [''] * len(s)
5 | for idx, val in enumerate(s):
6 | if val == '(':
7 | stack.append([idx, '('])
8 | res[idx] = '('
9 | elif val == ')':
10 | if stack:
11 | stack.pop()
12 | res[idx] = ')'
13 | else:
14 | res[idx] = val
15 | for tmp in stack:
16 | res[tmp[0]] = ''
17 | return ''.join(res)
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1257.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findSmallestRegion(self, regions: List[List[str]], region1: str, region2: str) -> str:
3 | for r in regions[::-1]:
4 | if region1 in r:
5 | region1 = r[0]
6 | if region2 in r:
7 | region2 = r[0]
8 | if region1 == region2:
9 | return region1
10 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1260.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
3 | m, n = len(grid), len(grid[0])
4 | if k == m * n:
5 | return grid
6 | k %= m * n
7 | tmp = []
8 | for _ in grid:
9 | tmp += _
10 | tmp = tmp[-k:] + tmp[:-k]
11 | res = [[0] * n for _ in range(m)]
12 | for idx, val in enumerate(tmp):
13 | res[idx // n][idx - idx // n * n] = val
14 | return res
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1299.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def replaceElements(self, arr: List[int]) -> List[int]:
3 | n = len(arr)
4 | for i in range(n - 1, -1, -1):
5 | if i == n - 1:
6 | premax = arr[i]
7 | arr[i] = -1
8 | else:
9 | cmax = max(premax, arr[i])
10 | arr[i] = premax
11 | premax = cmax
12 | return arr
13 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1323.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int maximum69Number (int num) {
4 | int cnt = 0, k = -1;
5 | int tmp = num;
6 | while(tmp){
7 | if(tmp % 10 == 6){
8 | k = cnt;
9 | }
10 | ++cnt;
11 | tmp /= 10;
12 | }
13 | if (k != -1){
14 | return num + 3 * pow(10, k);
15 | }
16 | return num;
17 | }
18 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1333.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> \
3 | List[int]:
4 | restaurants = [item for item in restaurants if (veganFriendly == 0 or item[2] == 1) and
5 | item[3] <= maxPrice and item[4] <= maxDistance]
6 | return [i[0] for i in sorted(restaurants, key=lambda x: [-x[1], -x[0]])]
7 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1365.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
3 | maxn = max(nums)
4 | cnt = [0] * (maxn + 1)
5 | for val in nums:
6 | cnt[val] += 1
7 | pre = 0
8 | for idx, val in enumerate(cnt):
9 | cnt[idx] = pre
10 | pre += val
11 | return [cnt[i] for i in nums]
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1428.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
3 | row, col = binaryMatrix.dimensions()
4 | i, j = 0, col - 1
5 | while -1 < i < row and -1 < j < col:
6 | if binaryMatrix.get(i, j) == 1:
7 | j -= 1
8 | else:
9 | i += 1
10 | if j == col - 1:
11 | return -1
12 | else:
13 | return j + 1
14 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1431.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
3 | m = max(candies)
4 | return [_ + extraCandies >= m for _ in candies]
5 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1441.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def buildArray(self, target: List[int], n: int) -> List[str]:
3 | if not target:
4 | return []
5 | n = max(target)
6 | target = set(target)
7 | res = []
8 | for i in range(1, n + 1):
9 | if i in target:
10 | res.append('Push')
11 | else:
12 | res.append('Push')
13 | res.append('Pop')
14 | return res
15 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1446.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxPower(self, s: str) -> int:
3 | res = 1
4 | cnt = 0
5 | for idx, val in enumerate(s):
6 | if idx == 0:
7 | cnt += 1
8 | continue
9 | if val == s[idx - 1]:
10 | cnt += 1
11 | res = max(res, cnt)
12 | else:
13 | res = max(res, cnt)
14 | cnt = 1
15 | return res
16 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1447.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def simplifiedFractions(self, n: int) -> List[str]:
3 | if n == 1:
4 | return []
5 | res = []
6 | import math
7 | for a in range(2, n + 1):
8 | for b in range(1, a):
9 | if math.gcd(a, b) == 1:
10 | res.append(str(b) + '/' + str(a))
11 | return res
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1449.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def largestNumber(self, cost: List[int], target: int) -> str:
3 | f = [-1] * (target + 1)
4 | f[0] = 0
5 | for i in range(8, -1, -1):
6 | for v in range(cost[i], target + 1):
7 | f[v] = max(f[v], f[v - cost[i]] * 10 + i + 1)
8 | return str(f[-1]) if f[-1] >= 0 else '0'
9 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1450.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
3 | cnt = 0
4 | for item in zip(startTime, endTime):
5 | if item[0] <= queryTime <= item[1]:
6 | cnt += 1
7 | return cnt
8 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1451.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def arrangeWords(self, text: str) -> str:
3 | text = text[0].lower() + text[1:]
4 | s = text.split(' ')
5 | ss = []
6 | for idx, val in enumerate(s):
7 | ss.append([val, idx])
8 | ss.sort(key=lambda x: [len(x[0]), x[1]])
9 | ret = ' '.join([_[0] for _ in ss])
10 | return ret[0].upper() + ret[1:]
11 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1452.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
3 | fs = [set(_) for _ in favoriteCompanies]
4 | n = len(favoriteCompanies)
5 | flag = [True] * n
6 | for idx, s in enumerate(fs):
7 | for j in range(n):
8 | if idx != j and flag[idx] and flag[j] and s.issubset(fs[j]):
9 | flag[idx] = False
10 | break
11 | return [idx for idx, val in enumerate(flag) if val]
12 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1455.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
3 | sentence = sentence.split()
4 | for idx, s in enumerate(sentence):
5 | if s.startswith(searchWord):
6 | return idx + 1
7 | return -1
8 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1456.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxVowels(self, s: str, k: int) -> int:
3 | vowel = set(list("aeiou"))
4 | cnt = 0
5 | l, r = 0, k - 1;
6 | cur = 0
7 | for i in range(l, r + 1):
8 | if s[i] in vowel:
9 | cur += 1
10 | cnt = max(cur, cnt)
11 | while r < len(s) - 1:
12 | # print(l, r)
13 | r += 1
14 | if s[r] in vowel:
15 | cur += 1
16 | if s[l] in vowel:
17 | cur -= 1
18 | l += 1
19 | if cur > cnt:
20 | cnt = cur
21 | return cnt
22 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1467.py:
--------------------------------------------------------------------------------
1 | import math
2 | import itertools
3 |
4 |
5 | class Solution:
6 | def getProbability(self, balls: List[int]) -> float:
7 |
8 | def multional(nums):
9 | return math.factorial(sum(nums)) / math.prod([math.factorial(_) for _ in nums])
10 |
11 | n, cnt = sum(balls) / 2, 0
12 | t = [range(_ + 1) for _ in balls]
13 | t = list(itertools.product(*t))
14 | for i in range(len(t)):
15 | if sum(t[i]) == n and t[i].count(0) == t[-i - 1].count(0):
16 | cnt += multional(t[i]) * multional(t[-i - 1])
17 | return cnt / multional(balls)
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1486.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def xorOperation(self, n: int, start: int) -> int:
3 | nums = [start + 2 * i for i in range(n)];
4 | ret = 0;
5 | for val in nums:
6 | ret ^= val
7 | return ret
8 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1498.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def numSubseq(self, nums: List[int], target: int) -> int:
3 | nums.sort()
4 | if nums[0] * 2 > target:
5 | return 0
6 | MOD = 10 ** 9 + 7
7 | left = 0
8 | right = len(nums) - 1
9 | ret = 0
10 | while left <= right:
11 | if nums[left] + nums[right] <= target:
12 | ret += 2 ** (right - left)
13 | ret %= MOD
14 | left += 1
15 | else:
16 | right -= 1
17 | return ret
18 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1513.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int numSub(string s) {
4 | int ret = 0, pre = 0;
5 | const int M = 1e9 + 7;
6 | for(auto &c: s){
7 | if (c == '0') pre = 0;
8 | else{
9 | int cur = pre + 1;
10 | cur %= M;
11 | pre = cur;
12 | ret = (ret + cur) % M;
13 | }
14 | }
15 | return ret;
16 | }
17 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1608.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def specialArray(self, nums: List[int]) -> int:
3 | for x in range(101):
4 | if sum([num >= x for num in nums]) == x:
5 | return x
6 | return -1
7 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1611.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minimumOneBitOperations(self, n: int) -> int:
3 | """
4 | Gray Code
5 | :param n:
6 | :return:
7 | """
8 | tmp = n
9 | cnt = 0
10 | while tmp:
11 | tmp >>= 1
12 | cnt += 1
13 | ret = 0
14 | for i in range(cnt - 1, -1, -1):
15 | c = (n >> i) & 1
16 | t = ret & 1 ^ c
17 | ret = (ret << 1) + t
18 | return ret
19 |
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1650.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | // Definition for a Node.
3 | class Node {
4 | public:
5 | int val;
6 | Node* left;
7 | Node* right;
8 | Node* parent;
9 | };
10 | */
11 |
12 | class Solution {
13 | public:
14 | Node* lowestCommonAncestor(Node* p, Node * q) {
15 | unordered_set st;
16 | while(p != nullptr){
17 | st.insert(p->val);
18 | p = p->parent;
19 | }
20 | while (q != nullptr){
21 | if (st.count(q->val))
22 | return q;
23 | q = q->parent;
24 | }
25 | return nullptr;
26 | }
27 | };
--------------------------------------------------------------------------------
/LeetCodeSolutions/LeetCode_1673.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def mostCompetitive(self, nums: List[int], k: int) -> List[int]:
3 | stack = []
4 | for idx, val in enumerate(nums):
5 | while stack and val < stack[-1] and len(stack) + len(nums) - idx - 1 >= k:
6 | stack.pop()
7 | stack.append(val)
8 | return stack[:k]
9 |
--------------------------------------------------------------------------------
/Notes/@classmethod 多态总结.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/@classmethod 多态总结.pdf
--------------------------------------------------------------------------------
/Notes/Buffon’s Needle 问题.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/Buffon’s Needle 问题.pdf
--------------------------------------------------------------------------------
/Notes/CentOS 非root服务器配置.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/CentOS 非root服务器配置.pdf
--------------------------------------------------------------------------------
/Notes/DeepGlint AI编程练习赛 对抗性攻击.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/DeepGlint AI编程练习赛 对抗性攻击.pdf
--------------------------------------------------------------------------------
/Notes/LeetCode 0406 根据身高重建队列.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/LeetCode 0406 根据身高重建队列.pdf
--------------------------------------------------------------------------------
/Notes/Python property 介绍.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/Python property 介绍.pdf
--------------------------------------------------------------------------------
/Notes/[CV] Anchor-Free Target Assignment 高斯核半径.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/[CV] Anchor-Free Target Assignment 高斯核半径.pdf
--------------------------------------------------------------------------------
/Notes/[CV] Rotated IoU 如何计算带旋转矩形之间的重叠面积.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/[CV] Rotated IoU 如何计算带旋转矩形之间的重叠面积.pdf
--------------------------------------------------------------------------------
/Notes/古董键盘题解.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/古董键盘题解.pdf
--------------------------------------------------------------------------------
/Notes/快速幂和矩阵快速幂.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/快速幂和矩阵快速幂.pdf
--------------------------------------------------------------------------------
/Notes/快速计算灰度图 bounding box 内部的方差.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/快速计算灰度图 bounding box 内部的方差.pdf
--------------------------------------------------------------------------------
/Notes/感知机建模及对偶形式.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/感知机建模及对偶形式.pdf
--------------------------------------------------------------------------------
/Notes/最小二乘法解的矩阵形式.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/最小二乘法解的矩阵形式.pdf
--------------------------------------------------------------------------------
/Notes/树状数组归并排序应用计算数组的小和.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/树状数组归并排序应用计算数组的小和.pdf
--------------------------------------------------------------------------------
/Notes/欧拉通路回路和一笔画问题.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/欧拉通路回路和一笔画问题.pdf
--------------------------------------------------------------------------------
/Notes/深度学习中需要的矩阵计算.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/深度学习中需要的矩阵计算.pdf
--------------------------------------------------------------------------------
/Notes/组合数学常用公式.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/组合数学常用公式.pdf
--------------------------------------------------------------------------------
/Notes/统计学习方法概论.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/统计学习方法概论.pdf
--------------------------------------------------------------------------------
/Notes/记录一次失败的字节跳动面试.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/记录一次失败的字节跳动面试.pdf
--------------------------------------------------------------------------------
/Notes/零神模拟面试总结.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/Notes/零神模拟面试总结.pdf
--------------------------------------------------------------------------------
/data_structures/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lih627/python-algorithm-templates/a61fd583e33a769b44ab758990625d3381793768/data_structures/__init__.py
--------------------------------------------------------------------------------
/geometry/rectangler_in_rectangr.py:
--------------------------------------------------------------------------------
1 | """
2 | https://stackoverflow.com/questions/13784274/detect-if-one-rect-can-be-put-into-another-rect
3 | detect-if-one-rect-can-be-put-into-another-rect
4 |
5 |
6 | See Rectangles in Rectangles for more details
7 | """
8 |
9 |
10 | def pq_in_ab(a, b, p, q):
11 | a, b = max(a, b), min(a, b)
12 | p, q = max(p, q), min(p, q)
13 | return p <= a and q <= b or (p > a and (p ** 2 + q ** 2) * b >=
14 | 2 * p * q * a + (p ** 2 - q ** 2) *
15 | (q ** 2 + p ** 2 - a ** 2) ** 0.5)
16 |
--------------------------------------------------------------------------------
/maths/Euclidean_algorithm.py:
--------------------------------------------------------------------------------
1 | """
2 | 欧几里得算法/ 辗转相除法
3 |
4 | gcd(a, b) = gcd(a, a mod b)
5 | """
6 |
7 |
8 | # def gcd(a, b):
9 | # if b == 0:
10 | # return a
11 | # if a % b:
12 | # return gcd(b, a % b)
13 | # return b
14 |
15 | def gcd(x, y):
16 | if y == 0:
17 | return x
18 | else:
19 | return gcd(y, x % y)
20 |
21 |
22 | if __name__ == '__main__':
23 | print(gcd(2, 5))
24 | print(gcd(10, 0))
25 | print(gcd(2, 4))
26 |
27 |
--------------------------------------------------------------------------------
/maths/bezouts.py:
--------------------------------------------------------------------------------
1 | """
2 | LeetCode_365 水壶问题
3 | 有两个容量分别为 x 升 和 y 升 的水壶以及无限多的水。
4 | 请判断能否通过使用这两个水壶,从而可以得到恰好 z 升 的水?
5 |
6 | 如果可以,最后请用以上水壶中的一或两个来盛放取得的 z 升水。
7 | """
8 |
9 | import math
10 |
11 |
12 | def canMeasureWater(x: int, y: int, z: int) -> bool:
13 | if x + y < z:
14 | return False
15 | if x == 0 or y == 0:
16 | return z == 0 or x + y == z
17 | return z % math.gcd(x, y) == 0
18 |
--------------------------------------------------------------------------------
/maths/find_prime_in_N.py:
--------------------------------------------------------------------------------
1 | """
2 | sieve of Eratosthenes
3 | 埃氏筛
4 | """
5 |
6 |
7 | def countPrimes(n: int) -> int:
8 | if n < 2: return 0
9 | res = [1] * n
10 | res[0], res[1] = 0, 0
11 | for i in range(2, int(n ** 0.5) + 1):
12 | # print(res)
13 | if res[i]:
14 | res[i * i: n: i] = [0] * len(res[i * i: n: i])
15 | return sum(res)
16 |
--------------------------------------------------------------------------------
/string/LCS.py:
--------------------------------------------------------------------------------
1 | """
2 | Longest Common Sbusequence
3 | 最长公共字符列长度
4 | 输入:text1 = "abcde", text2 = "ace"
5 | 输出:3
6 | 解释:最长公共子序列是 "ace",它的长度为 3
7 | """
8 |
9 |
10 | def lcs(text1, text2):
11 | '''
12 | DP
13 | '''
14 | len1 = len(text1)
15 | len2 = len(text2)
16 | dp = [[0 for _ in range(len2 + 1)] for _ in range(len1 + 1)]
17 | for i in range(1, len1 + 1):
18 | for j in range(1, len2 + 1):
19 | if text1[i - 1] == text2[j - 1]:
20 | dp[i][j] = dp[i - 1][j - 1] + 1
21 | else:
22 | dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
23 | return dp[-1][-1]
24 |
--------------------------------------------------------------------------------
/其他面试题/README.md:
--------------------------------------------------------------------------------
1 | # 说明
2 |
3 | 这里面的题都是从网上或者自己做的一些面试题, 有一些附上了思路和代码.
4 | 但是由于没有评测系统, 不清楚会出现什么样的问题.
5 |
--------------------------------------------------------------------------------
/其他面试题/士兵分组.py:
--------------------------------------------------------------------------------
1 | """
2 | 微软 2020 笔试
3 | 输入N个士兵的能力值, 分成X组,
4 | 要求每组人数相同, 并且每组中
5 | 每个人的能力值都不相同,
6 | 返回每组的最大能力值和最小能力值之差的和的最小值
7 | 如果不能分组, 返回 -1
8 |
9 | 测试用例 1
10 | 输入 [1, 1], 1
11 | 输出 -1,
12 | 只能分成 [1, 1] 一个队伍, 队员能力值相同, 无法分, 返回 -1
13 |
14 | 测试用例 2
15 | 输入 [5, 5, 10, 10, 4, 8, 3, 6, 4, 8, 3, 6], 3
16 | 输出 15
17 | 12个人分成3组, 产生能力和最小值的分组情况如下:
18 | [3, 4, 5, 6] 6 - 3= 3
19 | [3, 4, 8, 10] 10 - 3 = 7
20 | [5, 6, 8, 10] 10 - 5 = 5
21 | 输出 3 + 7 + 5 = 15
22 |
23 | """
24 |
--------------------------------------------------------------------------------
/其他面试题/表达式组合.py:
--------------------------------------------------------------------------------
1 | """
2 | 给定一个字符串"123456789"
3 | 在任意字符中间插入 + - * / 四种运算符
4 | 使最火的计算结果等于 50
5 | 例如 1*2*3*4-56-7+89 = 50
6 | 输出所有可能的表达式
7 | """
8 |
9 | import itertools
10 |
11 |
12 | def make_50():
13 | nums = [str(_) for _ in range(1, 10)]
14 | ops = ['+', '-', '*', '//', '']
15 | for op in itertools.product(*([ops for _ in range(8)])):
16 | cur = ''.join([op[i // 2] if i & 1 else nums[i // 2] for i in range(17)])
17 | if eval(cur) == 50:
18 | print(cur)
19 |
20 |
21 | if __name__ == '__main__':
22 | make_50()
23 |
--------------------------------------------------------------------------------
/其他面试题/装备掉落.py:
--------------------------------------------------------------------------------
1 | """
2 | 打怪, 必掉1 件装备
3 | a 0.8, b 0.2
4 | 问获得 ab 的期望
5 | """
6 | import random
7 | import numpy as np
8 |
9 |
10 | def solve():
11 | for k in range(10):
12 | res = []
13 | for i in range(100000):
14 | cnt = 0
15 | ab = [0, 0]
16 | while True:
17 | cnt += 1
18 | if random.random() > 0.2:
19 | ab[0] = 1
20 | else:
21 | ab[1] = 1
22 | if sum(ab) == 2:
23 | break
24 | res.append(cnt)
25 | print(np.mean(res))
26 |
27 |
28 | if __name__ == '__main__':
29 | res = solve()
30 |
--------------------------------------------------------------------------------
/剑指Offer/No_03.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findRepeatNumber(self, nums: List[int]) -> int:
3 | s = set()
4 | for _ in nums:
5 | if _ not in s:
6 | s.add(_)
7 | else:
8 | return _
9 |
--------------------------------------------------------------------------------
/剑指Offer/No_04.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
3 | if not matrix:
4 | return False
5 | row, col = len(matrix), len(matrix[0])
6 | i, j = 0, col - 1
7 | while row > i > -1 and col > j > -1:
8 | if matrix[i][j] == target:
9 | return True
10 | elif matrix[i][j] < target:
11 | i += 1
12 | elif matrix[i][j] > target:
13 | j -= 1
14 | return False
15 |
--------------------------------------------------------------------------------
/剑指Offer/No_05.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def replaceSpace(self, s: str) -> str:
3 | res = ''
4 | for _ in s:
5 | if _ == ' ':
6 | res += '%20'
7 | else:
8 | res += _
9 | return res
10 |
--------------------------------------------------------------------------------
/剑指Offer/No_06.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def reversePrint(self, head: ListNode) -> List[int]:
9 | from collections import deque
10 | q = deque()
11 | while head:
12 | q.appendleft(head.val)
13 | head = head.next
14 | return list(q)
15 |
--------------------------------------------------------------------------------
/剑指Offer/No_10_1.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def fib(self, n: int) -> int:
3 | pre = 1
4 | ppre = 0
5 | if n < 2:
6 | return n
7 | n -= 1
8 | while n:
9 | cur = pre + ppre
10 | pre, ppre = cur, pre
11 | n -= 1
12 | return cur % (10 ** 9 + 7)
13 |
--------------------------------------------------------------------------------
/剑指Offer/No_10_2.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def numWays(self, n: int) -> int:
3 | if n < 2:
4 | return 1
5 | pre = 1
6 | ppre = 1
7 | n -= 1
8 | while n:
9 | cur = pre + ppre
10 | pre, ppre = cur, pre
11 | n -= 1
12 | return cur % (10 ** 9 + 7)
13 |
--------------------------------------------------------------------------------
/剑指Offer/No_11.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minArray(self, numbers: List[int]) -> int:
3 | return min(numbers)
4 |
5 | def minArray2(self, numbers: List[int]) -> int:
6 | l, r = 0, len(numbers) - 1
7 | while l < r:
8 | mid = (l + r) // 2
9 | if numbers[mid] > numbers[r]:
10 | l = mid + 1
11 | elif numbers[mid] < numbers[r]:
12 | r = mid
13 | else:
14 | r -= 1
15 | return numbers[l]
16 |
--------------------------------------------------------------------------------
/剑指Offer/No_14_1.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def cuttingRope(self, n: int) -> int:
3 | if n < 4:
4 | return n - 1
5 | lst = n % 3
6 | if lst == 1:
7 | return 3 ** (n // 3 - 1) * 4
8 | elif lst == 0:
9 | return 3 ** (n // 3)
10 | else:
11 | return 3 ** (n // 3) * lst
12 |
--------------------------------------------------------------------------------
/剑指Offer/No_14_2.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def cuttingRope(self, n: int) -> int:
3 | if n < 4:
4 | return n - 1
5 | lst = n % 3
6 | if lst == 1:
7 | res = 3 ** (n // 3 - 1) * 4
8 | elif lst == 0:
9 | res = 3 ** (n // 3)
10 | else:
11 | res = 3 ** (n // 3) * lst
12 | return res % (10 ** 9 + 7)
13 |
--------------------------------------------------------------------------------
/剑指Offer/No_15.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def hammingWeight(self, n: int) -> int:
3 | n &= 0xFFFFFFFF
4 | cnt = 0
5 | while n:
6 | if n & 1:
7 | cnt += 1
8 | n >>= 1
9 | return cnt
10 |
--------------------------------------------------------------------------------
/剑指Offer/No_16.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def myPow(self, x: float, n: int) -> float:
3 | if not n:
4 | return 1
5 | ispos = n > 0
6 | n = abs(n)
7 | tmp = x
8 | res = 1
9 | while n > 0:
10 | if n & 1:
11 | res *= tmp
12 | n >>= 1
13 | tmp *= tmp
14 | if not ispos:
15 | res = 1 / res
16 | return res
17 |
--------------------------------------------------------------------------------
/剑指Offer/No_17.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def printNumbers(self, n: int) -> List[int]:
3 | return list(range(1, 10 ** n))
4 |
--------------------------------------------------------------------------------
/剑指Offer/No_18.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def deleteNode(self, head: ListNode, val: int) -> ListNode:
9 | dummy = ListNode(None)
10 | dummy.next = head
11 | pre = dummy
12 | cur = head
13 | while cur.val != val:
14 | cur = cur.next
15 | pre = pre.next
16 | pre.next = pre.next.next
17 | return dummy.next
18 |
--------------------------------------------------------------------------------
/剑指Offer/No_21.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def exchange(self, nums: List[int]) -> List[int]:
3 | if not nums:
4 | return nums
5 | n = len(nums)
6 | i, j = 0, n - 1
7 | while i < j:
8 | if nums[j] & 1:
9 | nums[i], nums[j] = nums[j], nums[i]
10 | i += 1
11 | else:
12 | j -= 1
13 | return nums
14 |
--------------------------------------------------------------------------------
/剑指Offer/No_22.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
9 | if not head:
10 | return head
11 | res, p = head, head
12 | while k:
13 | p = p.next
14 | k -= 1
15 | while p:
16 | res = res.next
17 | p = p.next
18 | return res
19 |
--------------------------------------------------------------------------------
/剑指Offer/No_24.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def reverseList(self, head: ListNode) -> ListNode:
9 |
10 | def reverse(node):
11 | if not node:
12 | return None
13 | if not node.next:
14 | return node
15 | last = reverse(node.next)
16 | node.next.next = node
17 | node.next = None
18 | return last
19 |
20 | return reverse(head)
21 |
--------------------------------------------------------------------------------
/剑指Offer/No_25.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
9 | dummy = ListNode(None)
10 | p = dummy
11 | while l1 and l2:
12 | if l1.val <= l2.val:
13 | p.next = l1
14 | l1 = l1.next
15 | else:
16 | p.next = l2
17 | l2 = l2.next
18 | p = p.next
19 | if l1 or l2:
20 | p.next = l1 if l1 else l2
21 | return dummy.next
22 |
--------------------------------------------------------------------------------
/剑指Offer/No_31.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
3 | if not pushed and not popped:
4 | return True
5 | aux = []
6 | idx = 0
7 | for _ in pushed:
8 | aux.append(_)
9 | while aux and aux[-1] == popped[idx]:
10 | aux.pop()
11 | idx += 1
12 | return not aux
13 |
--------------------------------------------------------------------------------
/剑指Offer/No_38.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def permutation(self, s: str) -> List[str]:
3 | # import itertools
4 | # res = {*map(''.join, itertools.permutations(s))}
5 | # return res
6 | elems = list(s)
7 | elems.sort()
8 | res = []
9 |
10 | def helper(tmps, s):
11 | if not tmps:
12 | res.append(s)
13 | for idx, _ in enumerate(tmps):
14 | if idx > 0 and _ == tmps[idx - 1]:
15 | continue
16 | helper(tmps[:idx] + tmps[idx + 1:], s + _)
17 |
18 | helper(elems, '')
19 | return res
20 |
--------------------------------------------------------------------------------
/剑指Offer/No_39.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def majorityElement(self, nums: List[int]) -> int:
3 | n = len(nums)
4 | d = {}
5 | for _ in nums:
6 | if _ not in d:
7 | d[_] = 1
8 | if d[_] > n // 2:
9 | return _
10 | else:
11 | d[_] += 1
12 | if d[_] > n // 2:
13 | return _
14 |
--------------------------------------------------------------------------------
/剑指Offer/No_42.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxSubArray(self, nums: List[int]) -> int:
3 | pre_sum = nums[0]
4 | cur_sum = 0
5 | for _ in nums:
6 | cur_sum += _
7 | pre_sum = max(pre_sum, cur_sum)
8 | if cur_sum <= 0:
9 | cur_sum = 0
10 | return pre_sum
11 |
--------------------------------------------------------------------------------
/剑指Offer/No_43.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def countDigitOne(self, n: int) -> int:
3 | cnt = 0
4 | tmp = 1
5 | while n >= tmp:
6 | a = n // tmp
7 | b = n % tmp
8 | cnt += (a + 8) // 10 * tmp + (a % 10 == 1) * (b + 1)
9 | tmp *= 10
10 | return cnt
11 |
--------------------------------------------------------------------------------
/剑指Offer/No_44.py:
--------------------------------------------------------------------------------
1 | import itertools
2 |
3 |
4 | class Solution:
5 | def findNthDigit(self, n: int) -> int:
6 | if n < 10:
7 | return n
8 | for digits in itertools.count(1):
9 | first_num = 10 ** (digits - 1)
10 | if n <= 9 * first_num * digits:
11 | n -= 1
12 | return int(str(first_num + n // digits)[n % digits])
13 | n -= 9 * first_num * digits
14 |
--------------------------------------------------------------------------------
/剑指Offer/No_45.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minNumber(self, nums: List[int]) -> str:
3 | import functools
4 | def compare(x, y):
5 | if int(x + y) < int(y + x):
6 | return -1
7 | if int(x + y) > int(y + x):
8 | return 1
9 | return 0
10 |
11 | tmp = [str(_) for _ in nums]
12 | tmp.sort(key=functools.cmp_to_key(compare))
13 | return ''.join(tmp)
14 |
--------------------------------------------------------------------------------
/剑指Offer/No_46.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def translateNum(self, num: int) -> int:
3 | cnt = 0
4 |
5 | def helper(s):
6 | nonlocal cnt
7 | if not s:
8 | cnt += 1
9 | return
10 | helper(s[1:])
11 | if len(s) > 1:
12 | if '09' < s[:2] < '26':
13 | helper(s[2:])
14 |
15 | helper(str(num))
16 | return cnt
17 |
--------------------------------------------------------------------------------
/剑指Offer/No_47.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxValue(self, grid: List[List[int]]) -> int:
3 | if not grid:
4 | return 0
5 | m, n = len(grid), len(grid[0])
6 | dp = [0] * n
7 | for idx, _ in enumerate(grid[0]):
8 | if idx == 0:
9 | dp[idx] = _
10 | else:
11 | dp[idx] = _ + dp[idx - 1]
12 | for i in range(1, m):
13 | for j in range(n):
14 | if j == 0:
15 | dp[j] += grid[i][j]
16 | else:
17 | dp[j] = max(dp[j - 1], dp[j]) + grid[i][j]
18 | return dp[-1]
19 |
--------------------------------------------------------------------------------
/剑指Offer/No_48.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def lengthOfLongestSubstring(self, s: str) -> int:
3 | Set = set()
4 | left, right, longest = 0, 0, 0
5 | while right < len(s):
6 | while s[right] in Set:
7 | Set.remove(s[left])
8 | left += 1
9 | Set.add(s[right])
10 | right += 1
11 | longest = max(right - left, longest)
12 | return longest
13 |
--------------------------------------------------------------------------------
/剑指Offer/No_49.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def nthUglyNumber(self, n: int) -> int:
3 | if not n:
4 | return 0
5 | res = [0] * n
6 | res[0] = 1
7 | p2 = p3 = p5 = 0
8 | for idx in range(1, n):
9 | r2 = res[p2] * 2
10 | r3 = res[p3] * 3
11 | r5 = res[p5] * 5
12 | res[idx] = min(r2, r3, r5)
13 | if res[idx] == r2: p2 += 1
14 | if res[idx] == r3: p3 += 1
15 | if res[idx] == r5: p5 += 1
16 | return res[-1]
17 |
--------------------------------------------------------------------------------
/剑指Offer/No_50.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def firstUniqChar(self, s: str) -> str:
3 | if not s:
4 | return " "
5 | from collections import Counter
6 | counter = Counter(list(s))
7 | for _ in s:
8 | if counter[_] == 1:
9 | return _
10 | return ' '
11 |
--------------------------------------------------------------------------------
/剑指Offer/No_52.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
9 | nodea, nodeb = headA, headB
10 | while nodea != nodeb:
11 | nodea = nodea.next if nodea else headB
12 | nodeb = nodeb.next if nodeb else headA
13 | return nodea
14 |
--------------------------------------------------------------------------------
/剑指Offer/No_53_2.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def missingNumber(self, nums: List[int]) -> int:
3 | n = len(nums)
4 | from functools import reduce
5 | return reduce(lambda x, y: x ^ y, nums + list(range(n + 1)))
6 |
--------------------------------------------------------------------------------
/剑指Offer/No_54.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution:
9 | def kthLargest(self, root: TreeNode, k: int) -> int:
10 | if not root:
11 | return None
12 | stack = []
13 | node = root
14 | while stack or node:
15 | while node:
16 | stack.append(node)
17 | node = node.right
18 | k -= 1
19 | node = stack.pop()
20 | if k == 0:
21 | return node.val
22 | node = node.left
23 |
--------------------------------------------------------------------------------
/剑指Offer/No_55_2.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution:
9 | def isBalanced(self, root: TreeNode) -> bool:
10 |
11 | def balanced(node):
12 | if not node:
13 | return True, 0
14 | lb, l = balanced(node.left)
15 | rb, r = balanced(node.right)
16 | if lb and rb and abs(l - r) < 2:
17 | return True, max(l, r) + 1
18 | else:
19 | return False, 0
20 |
21 | return balanced(root)[0]
22 |
--------------------------------------------------------------------------------
/剑指Offer/No_56_1.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def singleNumbers(self, nums: List[int]) -> List[int]:
3 | from functools import reduce
4 | tmp = reduce(lambda x, y: x ^ y, nums)
5 | cnt = 0
6 | while tmp & 1 == 0:
7 | cnt += 1
8 | tmp >>= 1
9 | tmp1, tmp2 = 0, 0
10 | for _ in nums:
11 | if (_ >> cnt) & 1:
12 | tmp1 ^= _
13 | else:
14 | tmp2 ^= _
15 | return [tmp1, tmp2]
16 |
--------------------------------------------------------------------------------
/剑指Offer/No_56_2.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def singleNumber(self, nums: List[int]) -> int:
3 | from collections import Counter
4 | cnt = Counter(nums)
5 | for k, v in cnt.items():
6 | if v == 1:
7 | return k
8 |
9 | def singleNumber_v2(self, nums: List[int]) -> int:
10 | # add bit operation solution
11 | res = 0
12 | for i in range(32):
13 | cnt = 0
14 | bit = 1 << i
15 | for _ in nums:
16 | if bit & _:
17 | cnt += 1
18 | if cnt % 3 != 0:
19 | res |= bit
20 | return res
21 |
--------------------------------------------------------------------------------
/剑指Offer/No_57_1.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def twoSum(self, nums: List[int], target: int) -> List[int]:
3 | d = {}
4 | for idx, _ in enumerate(nums):
5 | if _ not in d:
6 | d[target - _] = _
7 | else:
8 | return [d[_], _]
9 |
--------------------------------------------------------------------------------
/剑指Offer/No_57_2.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findContinuousSequence(self, target: int) -> List[List[int]]:
3 | from collections import deque
4 | if target == 1:
5 | return []
6 | res = []
7 | tmp = deque()
8 | cur_sum = 0
9 | for i in range(1, target // 2 + 2):
10 | cur_sum += i
11 | tmp.append(i)
12 | while cur_sum > target:
13 | cur_sum -= tmp.popleft()
14 | if cur_sum == target:
15 | res.append(list(tmp))
16 | return res
17 |
--------------------------------------------------------------------------------
/剑指Offer/No_58_1.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reverseWords(self, s: str) -> str:
3 | return ' '.join(s.split()[::-1])
4 |
--------------------------------------------------------------------------------
/剑指Offer/No_58_2.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reverseLeftWords(self, s: str, n: int) -> str:
3 | return s[n:] + s[:n]
4 |
--------------------------------------------------------------------------------
/剑指Offer/No_60.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def twoSum(self, n: int) -> List[float]:
3 | l = 6 * n + 1
4 | dp = [0] * l
5 | dp[1: 7] = [1] * 6
6 | left = 1
7 | for i in range(2, n + 1):
8 | left = i
9 | right = i * 6
10 | while right >= left:
11 | _ = right - 6 if right >= 6 else 0
12 | dp[right] = sum(dp[_: right])
13 | right -= 1
14 | print('1', dp)
15 | dp[:left] = [0] * left
16 | res = dp[left:]
17 | all_nums = 6 ** n
18 | res = [_ / all_nums for _ in res]
19 | return res
20 |
--------------------------------------------------------------------------------
/剑指Offer/No_61.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isStraight(self, nums: List[int]) -> bool:
3 | nums.sort()
4 | cnt_0 = 0
5 | for idx in range(len(nums) - 1):
6 | if nums[idx] == 0:
7 | cnt_0 += 1
8 | continue
9 | if nums[idx] == nums[idx + 1]:
10 | return False
11 | if nums[idx + 1] - nums[idx] > 1:
12 | cnt_0 -= nums[idx + 1] - nums[idx] - 1
13 | return cnt_0 > -1
14 |
--------------------------------------------------------------------------------
/剑指Offer/No_62.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def lastRemaining(self, n: int, m: int) -> int:
3 | res = 0
4 | for i in range(2, n + 1):
5 | res = (res + m) % i
6 | return res
7 |
--------------------------------------------------------------------------------
/剑指Offer/No_63.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxProfit(self, prices: List[int]) -> int:
3 | curr_max = 0
4 | maxs = [1 for _ in range(len(prices) - 1)]
5 | for i in range(len(prices) - 2, -1, -1):
6 | if curr_max < prices[i + 1]:
7 | curr_max = prices[i + 1]
8 | maxs[i] = curr_max
9 | # print(maxs)
10 | stack = [-float('inf')]
11 | for i in range(len(prices) - 1):
12 | if maxs[i] - prices[i] > stack[-1]:
13 | stack.append(maxs[i] - prices[i])
14 | return stack[-1] if stack[-1] > 0 else 0
15 |
--------------------------------------------------------------------------------
/剑指Offer/No_64.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def sumNums(self, n: int) -> int:
3 | return n and n + self.sumNums(n - 1)
4 |
--------------------------------------------------------------------------------
/剑指Offer/No_65.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def add(self, a: int, b: int) -> int:
3 | a &= 0xFFFFFFFF
4 | b &= 0xFFFFFFFF
5 | while b:
6 | carry = a & b
7 | a ^= b
8 | b = ((carry) << 1) & 0xFFFFFFFF
9 | return a if a < 0x80000000 else ~(a ^ 0xFFFFFFFF)
10 |
--------------------------------------------------------------------------------
/剑指Offer/No_68_1.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution:
9 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
10 | while root:
11 | if root.val > p.val and root.val > q.val:
12 | root = root.left
13 | elif root.val < p.val and root.val < q.val:
14 | root = root.right
15 | else:
16 | return root
17 |
--------------------------------------------------------------------------------
/程序员面试金典/No_01_01.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | unordered_set st;
3 | public:
4 | bool isUnique(string astr) {
5 | for (auto c: astr){
6 | if (st.count(c)) return false;
7 | st.insert(c);
8 | }
9 | return true;
10 | }
11 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_01_02.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool CheckPermutation(string s1, string s2) {
4 | unordered_map dict;
5 | if (s1.size() != s2.size()) return false;
6 | for (auto c: s1){
7 | dict[c] += 1;
8 | }
9 | for (auto c: s2){
10 | if (dict[c]) dict[c] -= 1;
11 | else return false;
12 | }
13 | return true;
14 | }
15 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_01_03.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | string replaceSpaces(string S, int length) {
4 | string res;
5 | int cnt = 0;
6 | for(auto c: S){
7 | if (cnt == length) break;
8 | if (c == ' '){res += "%20";}
9 | else res += c;
10 | ++cnt;
11 | }
12 | return res;
13 | }
14 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_01_04.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool canPermutePalindrome(string s) {
4 | unordered_map counter;
5 | for (auto c: s) ++counter[c];
6 | int odd = 0;
7 | for (auto it: counter){
8 | if (it.second & 1) ++odd;
9 | if (odd > 1) return false;
10 | }
11 | return true;
12 | }
13 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_01_06.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | string compressString(string S) {
4 | int cnt = 0;
5 | string res;
6 | for (int i = 0; i < S.size(); ++i){
7 | if (i == 0) ++cnt;
8 | if (i > 0){
9 | if(S[i] == S[i - 1]) ++cnt;
10 | else{
11 | res += S[i - 1] + to_string(cnt);
12 | cnt = 1;
13 | }
14 | }
15 | if(i == S.size() - 1) res += S[i] + to_string(cnt);
16 | }
17 | return res.size() < S.size()? res: S;
18 | }
19 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_01_06.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def compressString(self, S: str) -> str:
3 | i = j = 0
4 | n = len(S)
5 | res = ''
6 | cnt = 0
7 | while i < n:
8 | if j == n:
9 | res += str(j - i)
10 | break
11 | if i == j:
12 | res += S[i]
13 | j += 1
14 | elif S[i] == S[j]:
15 | j += 1
16 | else:
17 | res += str(j - i)
18 | i = j
19 | if len(res) < n:
20 | return res
21 | else:
22 | return S
23 |
--------------------------------------------------------------------------------
/程序员面试金典/No_01_07.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 |
4 | class Solution:
5 | def rotate(self, matrix: List[List[int]]) -> None:
6 | """
7 | Do not return anything, modify matrix in-place instead.
8 | """
9 | row, col = len(matrix), len(matrix[0])
10 | for i in range(row // 2):
11 | for j in range(col):
12 | matrix[i][j], matrix[row - 1 - i][j] = matrix[row - 1 - i][j], matrix[i][j]
13 |
14 | for i in range(row):
15 | for j in range(i):
16 | matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
17 |
--------------------------------------------------------------------------------
/程序员面试金典/No_01_09.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool isFlipedString(string s1, string s2) {
4 | if (s1.length() != s2.length()) return false;
5 | s1 += s1;
6 | return s1.find(s2) != -1;
7 | }
8 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_02.08.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * struct ListNode {
4 | * int val;
5 | * ListNode *next;
6 | * ListNode(int x) : val(x), next(NULL) {}
7 | * };
8 | */
9 | class Solution {
10 | public:
11 | ListNode *detectCycle(ListNode *head) {
12 | ListNode *f = head, *s = head;
13 | while (f && f->next){
14 | s = s->next;
15 | f = f->next->next;
16 | if (s == f) break;
17 | }
18 | if (!(f && f->next)) return NULL;
19 | s = head;
20 | while(s != f){
21 | s = s->next;
22 | f = f->next;
23 | }
24 | return s;
25 | }
26 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_02_02.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * struct ListNode {
4 | * int val;
5 | * ListNode *next;
6 | * ListNode(int x) : val(x), next(NULL) {}
7 | * };
8 | */
9 | class Solution {
10 | public:
11 | int kthToLast(ListNode* head, int k) {
12 | ListNode *s = head, *f = head;
13 | while (k--){
14 | f = f->next;
15 | }
16 | while (f){
17 | s = s->next;
18 | f = f->next;
19 | }
20 | return s->val;
21 | }
22 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_02_03.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * struct ListNode {
4 | * int val;
5 | * ListNode *next;
6 | * ListNode(int x) : val(x), next(NULL) {}
7 | * };
8 | */
9 | class Solution {
10 | public:
11 | void deleteNode(ListNode* node) {
12 | ListNode *pre = node;
13 | while (node->next){
14 | pre = node;
15 | node->val = node->next->val;
16 | node = node->next;
17 | }
18 | pre->next = nullptr;
19 | }
20 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_02_07.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * struct ListNode {
4 | * int val;
5 | * ListNode *next;
6 | * ListNode(int x) : val(x), next(NULL) {}
7 | * };
8 | */
9 | class Solution {
10 | public:
11 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
12 | ListNode *a = headA, *b = headB;
13 | while (a != b){
14 | a = a? a->next: headB;
15 | b = b? b->next: headA;
16 | }
17 | return a;
18 | }
19 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_04_08.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * struct TreeNode {
4 | * int val;
5 | * TreeNode *left;
6 | * TreeNode *right;
7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 | * };
9 | */
10 | class Solution {
11 | public:
12 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
13 | if(!root || root == p || root == q) return root;
14 | TreeNode* left = lowestCommonAncestor(root->left, p, q);
15 | TreeNode* right = lowestCommonAncestor(root->right, p, q);
16 | if(left && right) return root;
17 | return left? left: right;
18 | }
19 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_04_12.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.left = None
6 | # self.right = None
7 |
8 | class Solution:
9 | def pathSum(self, root: TreeNode, sum: int) -> int:
10 | ret = 0
11 |
12 | def helper(node, nums):
13 | if node:
14 | nums = [node.val + item for item in nums] + [node.val]
15 | return nums.count(sum) + helper(node.left, nums) + helper(node.right, nums)
16 | return 0
17 |
18 | return helper(root, [])
19 |
--------------------------------------------------------------------------------
/程序员面试金典/No_05_01.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def insertBits(self, N: int, M: int, i: int, j: int) -> int:
3 | m = 0
4 | for _ in range(i, j + 1):
5 | m <<= 1
6 | m += 1
7 | N &= 0xFFFFFFFF ^ (m << i)
8 | return N | (M << i)
9 |
--------------------------------------------------------------------------------
/程序员面试金典/No_05_02.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def printBin(self, num: float) -> str:
3 | ret = "0."
4 | for i in range(32):
5 | c = num * 2
6 | if c >= 1.0:
7 | c -= 1
8 | ret += '1'
9 | else:
10 | ret += '0'
11 | if abs(c) < 1e-8:
12 | return ret
13 | num = c
14 | return 'ERROR'
15 |
--------------------------------------------------------------------------------
/程序员面试金典/No_05_03.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reverseBits(self, num: int) -> int:
3 | num &= 0xFFFFFFFF
4 | a, na = 0, 0
5 | ret = 0
6 | while num:
7 | if num & 1:
8 | a += 1
9 | na += 1
10 | else:
11 | a = na + 1
12 | na = 0
13 | ret = max(a, na, ret)
14 | num >>= 1
15 | ret = max(ret, na + 1)
16 | return min(ret, 32)
17 |
--------------------------------------------------------------------------------
/程序员面试金典/No_08_01.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def waysToStep(self, n: int) -> int:
3 | MOD = 1000000007
4 | pre = [1, 2, 4]
5 | if n <= 3:
6 | return pre[n - 1]
7 | for i in range(4, n + 1):
8 | cur = sum(pre) % MOD
9 | pre = pre[1:] + [cur]
10 | return pre[-1]
11 |
--------------------------------------------------------------------------------
/程序员面试金典/No_08_03.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findMagicIndex(self, nums: List[int]) -> int:
3 | for idx, val in enumerate(nums):
4 | if idx == val:
5 | return idx
6 | return -1
7 |
--------------------------------------------------------------------------------
/程序员面试金典/No_08_04.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def subsets(self, nums: List[int]) -> List[List[int]]:
3 | ret = []
4 | n = len(nums)
5 | for i in range(2 ** n):
6 | tmp = []
7 | idx = 0
8 | while i:
9 | if i & 1:
10 | tmp.append(nums[idx])
11 | i >>= 1
12 | idx += 1
13 | ret.append(tmp)
14 | return ret
15 |
--------------------------------------------------------------------------------
/程序员面试金典/No_10_05.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findString(self, words: List[str], s: str) -> int:
3 | for idx, w in enumerate(words):
4 | if w == s:
5 | return idx
6 | return -1
7 |
--------------------------------------------------------------------------------
/程序员面试金典/No_10_11.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | void wiggleSort(vector& nums) {
4 | for(int i = 1; i < nums.size(); ++i){
5 | if(i & 1){
6 | if(nums[i] < nums[i - 1]) swap(nums[i], nums[i - 1]);
7 | }
8 | else{
9 | if(nums[i] > nums[i - 1]) swap(nums[i], nums[i - 1]);
10 | }
11 | }
12 | }
13 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_16_01.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector swapNumbers(vector& numbers) {
4 | // A = A ^ B
5 | // B = A ^ B
6 | // A = A ^ B
7 | numbers[0] ^= numbers[1];
8 | numbers[1] ^= numbers[0];
9 | numbers[0] ^= numbers[1];
10 | return numbers;
11 | }
12 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_16_05.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int trailingZeroes(int n) {
4 | int ret = 0;
5 | while(n){
6 | n /= 5;
7 | ret += n;
8 | }
9 | return ret;
10 | }
11 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_16_06.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int smallestDifference(vector& a, vector& b) {
4 | using ll = long long;
5 | sort(a.begin(), a.end());
6 | sort(b.begin(), b.end());
7 | int l = 0, r = 0;
8 | ll ret = abs(ll(a[0]) - b[0]);
9 | int na = a.size(), nb = b.size();
10 | while (l < na && r < nb){
11 | ret = min(ll(ret), abs(ll(a[l]) - b[r]));
12 | if (a[l] < b[r])++l;
13 | else if(a[l] > b[r])++r;
14 | else break;
15 | }
16 | return ret;
17 | }
18 | };
--------------------------------------------------------------------------------
/程序员面试金典/No_16_07.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maximum(self, a: int, b: int) -> int:
3 | return (abs(a - b) + a + b) // 2
4 |
--------------------------------------------------------------------------------
/程序员面试金典/No_16_11.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector divingBoard(int shorter, int longer, int k) {
4 | vector ret;
5 | if (k == 0) return {};
6 | int delta = longer - shorter;
7 | int base = shorter * k;
8 | ret.push_back(base);
9 | if(delta == 0) return ret;
10 | for(int i = 1; i < k + 1; ++i){
11 | base += delta;
12 | ret.push_back(base);
13 | }
14 | return ret;
15 | }
16 | };
--------------------------------------------------------------------------------