leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

commit 422ba403df8ba4705f5f18e3f910fb4035c2409c
parent 98caf468181173e545668a85e597fccfe207b532
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date:   Sat, 26 Aug 2023 12:23:11 +0200

Improve .clang-format, and reformat

Diffstat:
M.clang-format | 80++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
MProblems/0001.cpp | 20++++++++++----------
MProblems/0002.cpp | 38+++++++++++++++++++-------------------
MProblems/0003.cpp | 21+++++++++++----------
MProblems/0005.cpp | 33+++++++++++++++++----------------
MProblems/0006.cpp | 29+++++++++++++++--------------
MProblems/0007.cpp | 28+++++++++++++++-------------
MProblems/0008.cpp | 39++++++++++++++++++++-------------------
MProblems/0009.cpp | 16+++++++++-------
MProblems/0011.cpp | 25+++++++++++++------------
MProblems/0012.cpp | 28+++++++++++++++-------------
MProblems/0013.cpp | 52++++++++++++++++++++++++++--------------------------
MProblems/0014.cpp | 23++++++++++++-----------
MProblems/0015.cpp | 46++++++++++++++++++++++++----------------------
MProblems/0016.cpp | 32++++++++++++++++----------------
MProblems/0017.cpp | 25++++++++++++-------------
MProblems/0018.cpp | 53++++++++++++++++++++++++++++-------------------------
MProblems/0019.cpp | 30+++++++++++++++---------------
MProblems/0020.cpp | 48++++++++++++++++++++++++------------------------
MProblems/0021.cpp | 30+++++++++++++++---------------
MProblems/0022.cpp | 46+++++++++++++++++++++++-----------------------
MProblems/0023.cpp | 70+++++++++++++++++++++++++++++++++++-----------------------------------
MProblems/0024.cpp | 22+++++++++++-----------
MProblems/0025.cpp | 32++++++++++++++++----------------
MProblems/0026.cpp | 14+++++++-------
MProblems/0027.cpp | 14+++++++-------
MProblems/0028.cpp | 38+++++++++++++++++++-------------------
MProblems/0029.cpp | 58+++++++++++++++++++++++++++++-----------------------------
MProblems/0031.cpp | 26+++++++++++++-------------
MProblems/0033.cpp | 44+++++++++++++++++++++++++-------------------
MProblems/0034.cpp | 32+++++++++++++++++++-------------
MProblems/0035.cpp | 24++++++++++++------------
MProblems/0036.cpp | 3+--
MProblems/0037.cpp | 50+++++++++++++++++++++++++-------------------------
MProblems/0038.cpp | 34+++++++++++++++++-----------------
MProblems/0039.cpp | 36++++++++++++++++++------------------
MProblems/0040.cpp | 38+++++++++++++++++++-------------------
MProblems/0043.cpp | 42+++++++++++++++++++++---------------------
MProblems/0044.cpp | 37+++++++++++++++++++------------------
MProblems/0045.cpp | 22+++++++++++-----------
MProblems/0046.cpp | 40++++++++++++++++++++--------------------
MProblems/0047.cpp | 18+++++++++---------
MProblems/0048.cpp | 27++++++++++++++-------------
MProblems/0049.cpp | 34++++++++++++++++++----------------
MProblems/0050.cpp | 12++++++------
MProblems/0051.cpp | 79++++++++++++++++++++++++++++++++++++-------------------------------------------
MProblems/0052.cpp | 77+++++++++++++++++++++++++++++++++++------------------------------------------
MProblems/0053.cpp | 35++++++++++++++++++-----------------
MProblems/0054.cpp | 75++++++++++++++++++++++++++++++++++-----------------------------------------
MProblems/0055.cpp | 13+++++++------
MProblems/0056.cpp | 36+++++++++++++++++-------------------
MProblems/0057.cpp | 36+++++++++++++++++++-----------------
MProblems/0058.cpp | 17+++++++++--------
MProblems/0059.cpp | 73+++++++++++++++++++++++++++++++++----------------------------------------
MProblems/0060.cpp | 26++++++++++++++------------
MProblems/0061.cpp | 46+++++++++++++++++++++++-----------------------
MProblems/0062.cpp | 36++++++++++++++++++------------------
MProblems/0063.cpp | 44++++++++++++++++++++++----------------------
MProblems/0064.cpp | 26++++++++++++++------------
MProblems/0066.cpp | 22+++++++++++-----------
MProblems/0067.cpp | 28++++++++++++++--------------
MProblems/0068.cpp | 60+++++++++++++++++++++++++++++-------------------------------
MProblems/0069.cpp | 26+++++++++++++-------------
MProblems/0070.cpp | 37+++++++++++++++++++------------------
MProblems/0071.cpp | 42++++++++++++++++++++++--------------------
MProblems/0072.cpp | 66++++++++++++++++++++++++++++++++++--------------------------------
MProblems/0073.cpp | 40+++++++++++++++++++++-------------------
MProblems/0074.cpp | 91++++++++++++++++++++++++++++++++++++++++---------------------------------------
MProblems/0075.cpp | 18++++++++++--------
MProblems/0076.cpp | 37+++++++++++++++++++------------------
MProblems/0077.cpp | 104++++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/0078.cpp | 22+++++++++++-----------
MProblems/0079.cpp | 69++++++++++++++++++++++++++++++++-------------------------------------
MProblems/0080.cpp | 24++++++++++++------------
MProblems/0081.cpp | 40++++++++++++++++++++--------------------
MProblems/0082.cpp | 27++++++++++++++-------------
MProblems/0083.cpp | 20++++++++++----------
MProblems/0084.cpp | 52++++++++++++++++++++++++++--------------------------
MProblems/0086.cpp | 28++++++++++++++--------------
MProblems/0087.cpp | 44++++++++++++++++++++++----------------------
MProblems/0088.cpp | 15++++++++-------
MProblems/0090.cpp | 30+++++++++++++++---------------
MProblems/0091.cpp | 3+--
MProblems/0092.cpp | 31++++++++++++++++---------------
MProblems/0093.cpp | 67+++++++++++++++++++++++++++++++++----------------------------------
MProblems/0094.cpp | 36++++++++++++++++++------------------
MProblems/0095.cpp | 28++++++++++++++--------------
MProblems/0096.cpp | 17+++++++++--------
MProblems/0097.cpp | 31++++++++++++++-----------------
MProblems/0098.cpp | 34+++++++++++++++++-----------------
MProblems/0099.cpp | 39+++++++++++++++++++--------------------
MProblems/0100.cpp | 55+++++++++++++++++++++++++++----------------------------
MProblems/0101.cpp | 54+++++++++++++++++++++++++++---------------------------
MProblems/0102.cpp | 34+++++++++++++++++-----------------
MProblems/0103.cpp | 88++++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/0104.cpp | 30+++++++++++++++---------------
MProblems/0105.cpp | 52++++++++++++++++++++++++++--------------------------
MProblems/0106.cpp | 53+++++++++++++++++++++++++++--------------------------
MProblems/0107.cpp | 36++++++++++++++++++------------------
MProblems/0108.cpp | 44+++++++++++++++++++++-----------------------
MProblems/0109.cpp | 61++++++++++++++++++++++++++++++-------------------------------
MProblems/0110.cpp | 40++++++++++++++++++++--------------------
MProblems/0111.cpp | 30+++++++++++++++---------------
MProblems/0112.cpp | 28++++++++++++++--------------
MProblems/0113.cpp | 44++++++++++++++++++++++----------------------
MProblems/0114.cpp | 34+++++++++++++++++-----------------
MProblems/0116.cpp | 34+++++++++++++++++-----------------
MProblems/0117.cpp | 34+++++++++++++++++-----------------
MProblems/0118.cpp | 24++++++++++++------------
MProblems/0119.cpp | 24++++++++++++------------
MProblems/0120.cpp | 25+++++++++++++------------
MProblems/0121.cpp | 18+++++++++---------
MProblems/0122.cpp | 21+++++++++++----------
MProblems/0124.cpp | 70+++++++++++++++++++++++++++++++++++-----------------------------------
MProblems/0125.cpp | 28++++++++++++++--------------
MProblems/0128.cpp | 29+++++++++++++++--------------
MProblems/0129.cpp | 44++++++++++++++++++++++----------------------
MProblems/0130.cpp | 85+++++++++++++++++++++++++++++++++++++------------------------------------------
MProblems/0131.cpp | 100++++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/0133.cpp | 44+++++++++++++++++++++-----------------------
MProblems/0134.cpp | 24++++++++++++------------
MProblems/0135.cpp | 73++++++++++++++++++++++++++++++++++++-------------------------------------
MProblems/0136.cpp | 13+++++++------
MProblems/0137.cpp | 16++++++++--------
MProblems/0138.cpp | 30+++++++++++++++---------------
MProblems/0139.cpp | 2+-
MProblems/0141.cpp | 22+++++++++++-----------
MProblems/0142.cpp | 34+++++++++++++++++-----------------
MProblems/0143.cpp | 64++++++++++++++++++++++++++++++++--------------------------------
MProblems/0144.cpp | 32++++++++++++++++----------------
MProblems/0145.cpp | 52++++++++++++++++++++++++++--------------------------
MProblems/0146.cpp | 58+++++++++++++++++++++++++++++-----------------------------
MProblems/0148.cpp | 61++++++++++++++++++++++++++++++-------------------------------
MProblems/0149.cpp | 29+++++++++++++++--------------
MProblems/0150.cpp | 42++++++++++++++++++++----------------------
MProblems/0151.cpp | 30+++++++++++++++---------------
MProblems/0152.cpp | 4+---
MProblems/0153.cpp | 24++++++++++++------------
MProblems/0155.cpp | 16+++++++---------
MProblems/0160.cpp | 28+++++++++++++++-------------
MProblems/0162.cpp | 18+++++++++---------
MProblems/0164.cpp | 7+++----
MProblems/0165.cpp | 42+++++++++++++++++++++++-------------------
MProblems/0167.cpp | 26+++++++++++++-------------
MProblems/0168.cpp | 20++++++++++----------
MProblems/0169.cpp | 17+++++++++--------
MProblems/0171.cpp | 16++++++++--------
MProblems/0173.cpp | 70+++++++++++++++++++++++++++++++++++-----------------------------------
MProblems/0179.cpp | 26+++++++++++++-------------
MProblems/0187.cpp | 90++++++++++++++++++++++++++++++++++++++++---------------------------------------
MProblems/0189.cpp | 33++++++++++++++++++---------------
MProblems/0190.cpp | 18+++++++++---------
MProblems/0191.cpp | 13+++++++------
MProblems/0198.cpp | 20++++++++++----------
MProblems/0199.cpp | 32++++++++++++++++----------------
MProblems/0200.cpp | 46+++++++++++++++++++++++-----------------------
MProblems/0201.cpp | 5++---
MProblems/0202.cpp | 22++++++++++++----------
MProblems/0203.cpp | 22+++++++++++-----------
MProblems/0204.cpp | 21+++++++++++----------
MProblems/0205.cpp | 28++++++++++++++--------------
MProblems/0206.cpp | 24++++++++++++------------
MProblems/0207.cpp | 38+++++++++++++++++++-------------------
MProblems/0208.cpp | 63++++++++++++++++++++++++++++++++-------------------------------
MProblems/0209.cpp | 28++++++++++++++--------------
MProblems/0210.cpp | 44++++++++++++++++++++++----------------------
MProblems/0211.cpp | 49++++++++++++++++++++++++-------------------------
MProblems/0213.cpp | 31+++++++++++++++----------------
MProblems/0215.cpp | 18+++++++++---------
MProblems/0217.cpp | 28++++++++++++++--------------
MProblems/0219.cpp | 30+++++++++++++++---------------
MProblems/0221.cpp | 28++++++++++++++--------------
MProblems/0222.cpp | 44+++++++++++++++++++++++---------------------
MProblems/0223.cpp | 31++++++++++++++-----------------
MProblems/0225.cpp | 30+++++++++++++++---------------
MProblems/0226.cpp | 26+++++++++++++-------------
MProblems/0227.cpp | 32++++++++++++++++----------------
MProblems/0228.cpp | 38+++++++++++++++++++-------------------
MProblems/0230.cpp | 28++++++++++++++--------------
MProblems/0231.cpp | 4++--
MProblems/0232.cpp | 2+-
MProblems/0234.cpp | 56++++++++++++++++++++++++++++----------------------------
MProblems/0235.cpp | 24++++++++++++------------
MProblems/0236.cpp | 52+++++++++++++++++++++++++++-------------------------
MProblems/0237.cpp | 10+++++-----
MProblems/0238.cpp | 26+++++++++++++-------------
MProblems/0239.cpp | 28+++++++++++++++-------------
MProblems/0240.cpp | 22+++++++++++-----------
MProblems/0241.cpp | 40+++++++++++++++++++---------------------
MProblems/0242.cpp | 25+++++++++++++------------
MProblems/0257.cpp | 39+++++++++++++++++++--------------------
MProblems/0258.cpp | 18++++++++++--------
MProblems/0263.cpp | 15++++++++-------
MProblems/0264.cpp | 62+++++++++++++++++++++++++++++++-------------------------------
MProblems/0268.cpp | 13+++++++------
MProblems/0274.cpp | 25+++++++++++++------------
MProblems/0278.cpp | 22+++++++++++-----------
MProblems/0279.cpp | 23++++++++++++-----------
MProblems/0283.cpp | 15++++++++-------
MProblems/0287.cpp | 28++++++++++++++--------------
MProblems/0289.cpp | 34+++++++++++++++++-----------------
MProblems/0290.cpp | 36++++++++++++++++++------------------
MProblems/0292.cpp | 4++--
MProblems/0295.cpp | 48++++++++++++++++++++++++------------------------
MProblems/0297.cpp | 68++++++++++++++++++++++++++++++++++----------------------------------
MProblems/0299.cpp | 34+++++++++++++++++-----------------
MProblems/0300.cpp | 4+---
MProblems/0304.cpp | 42+++++++++++++++++++++---------------------
MProblems/0306.cpp | 39+++++++++++++++++++--------------------
MProblems/0309.cpp | 3+--
MProblems/0310.cpp | 58+++++++++++++++++++++++++++++-----------------------------
MProblems/0319.cpp | 4++--
MProblems/0322.cpp | 21++++++++++-----------
MProblems/0326.cpp | 10+++++-----
MProblems/0328.cpp | 26+++++++++++++-------------
MProblems/0334.cpp | 24++++++++++++------------
MProblems/0338.cpp | 18+++++++++---------
MProblems/0342.cpp | 6++----
MProblems/0343.cpp | 20++++++++++----------
MProblems/0344.cpp | 11++++++-----
MProblems/0345.cpp | 34++++++++++++++++++----------------
MProblems/0347.cpp | 42++++++++++++++++++++----------------------
MProblems/0350.cpp | 22+++++++++++-----------
MProblems/0352.cpp | 2+-
MProblems/0367.cpp | 4++--
MProblems/0371.cpp | 18+++++++++---------
MProblems/0373.cpp | 33++++++++++++++++-----------------
MProblems/0374.cpp | 26+++++++++++++-------------
MProblems/0376.cpp | 22+++++++++++-----------
MProblems/0377.cpp | 18+++++++++---------
MProblems/0382.cpp | 26++++++++++++++------------
MProblems/0383.cpp | 17+++++++++--------
MProblems/0384.cpp | 18+++++++++---------
MProblems/0387.cpp | 17+++++++++--------
MProblems/0392.cpp | 14+++++++-------
MProblems/0394.cpp | 51++++++++++++++++++++++++++-------------------------
MProblems/0399.cpp | 74++++++++++++++++++++++++++++++++++++--------------------------------------
MProblems/0402.cpp | 46++++++++++++++++++++++++----------------------
MProblems/0404.cpp | 36++++++++++++++++++------------------
MProblems/0406.cpp | 20++++++++++----------
MProblems/0409.cpp | 23++++++++++++-----------
MProblems/0412.cpp | 22+++++++++++-----------
MProblems/0413.cpp | 26+++++++++++++-------------
MProblems/0414.cpp | 44+++++++++++++++++++++++---------------------
MProblems/0415.cpp | 32++++++++++++++++----------------
MProblems/0416.cpp | 22+++++++++++-----------
MProblems/0417.cpp | 87+++++++++++++++++++++++++++++++++++++------------------------------------------
MProblems/0419.cpp | 24++++++++++++------------
MProblems/0424.cpp | 29+++++++++++++++--------------
MProblems/0427.cpp | 53++++++++++++++++++++++++++---------------------------
MProblems/0429.cpp | 33+++++++++++++++++----------------
MProblems/0430.cpp | 56++++++++++++++++++++++++++++----------------------------
MProblems/0433.cpp | 69++++++++++++++++++++++++++++++++++-----------------------------------
MProblems/0435.cpp | 28+++++++++++++---------------
MProblems/0437.cpp | 106++++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/0438.cpp | 48++++++++++++++++++++++++------------------------
MProblems/0442.cpp | 24++++++++++++------------
MProblems/0443.cpp | 38++++++++++++++++++++------------------
MProblems/0445.cpp | 20++++++++++----------
MProblems/0448.cpp | 22+++++++++++-----------
MProblems/0450.cpp | 54+++++++++++++++++++++++++++---------------------------
MProblems/0451.cpp | 18+++++++++---------
MProblems/0452.cpp | 26+++++++++++++-------------
MProblems/0459.cpp | 23++++++++++++-----------
MProblems/0460.cpp | 2+-
MProblems/0472.cpp | 2+-
MProblems/0485.cpp | 22+++++++++++-----------
MProblems/0486.cpp | 24+++++++++++-------------
MProblems/0491.cpp | 36++++++++++++++++++------------------
MProblems/0494.cpp | 56++++++++++++++++++++++++++++----------------------------
MProblems/0496.cpp | 32++++++++++++++++----------------
MProblems/0498.cpp | 69++++++++++++++++++++++++++++++++++-----------------------------------
MProblems/0501.cpp | 56++++++++++++++++++++++++++++----------------------------
MProblems/0502.cpp | 56++++++++++++++++++++++++++++----------------------------
MProblems/0503.cpp | 38+++++++++++++++++++-------------------
MProblems/0509.cpp | 37+++++++++++++++++++------------------
MProblems/0516.cpp | 41++++++++++++++++++++---------------------
MProblems/0518.cpp | 18+++++++++---------
MProblems/0520.cpp | 14+++++++-------
MProblems/0530.cpp | 36++++++++++++++++++------------------
MProblems/0532.cpp | 29++++++++++++++++-------------
MProblems/0535.cpp | 12+++++-------
MProblems/0538.cpp | 32++++++++++++++++----------------
MProblems/0540.cpp | 23+++++++++++------------
MProblems/0542.cpp | 67+++++++++++++++++++++++++++++++------------------------------------
MProblems/0543.cpp | 58+++++++++++++++++++++++++++++-----------------------------
MProblems/0547.cpp | 64++++++++++++++++++++++++++++++++--------------------------------
MProblems/0556.cpp | 38+++++++++++++++++++-------------------
MProblems/0557.cpp | 25+++++++++++++------------
MProblems/0559.cpp | 29+++++++++++++++--------------
MProblems/0560.cpp | 27++++++++++++++-------------
MProblems/0561.cpp | 29+++++++++++++++--------------
MProblems/0563.cpp | 28++++++++++++++--------------
MProblems/0566.cpp | 32++++++++++++++++----------------
MProblems/0567.cpp | 2+-
MProblems/0572.cpp | 76++++++++++++++++++++++++++++++++++++++--------------------------------------
MProblems/0583.cpp | 27+++++++++++++--------------
MProblems/0589.cpp | 29+++++++++++++++--------------
MProblems/0590.cpp | 29+++++++++++++++--------------
MProblems/0605.cpp | 30+++++++++++++++---------------
MProblems/0606.cpp | 48++++++++++++++++++++++++------------------------
MProblems/0617.cpp | 25++++++++++++-------------
MProblems/0621.cpp | 33+++++++++++++++++----------------
MProblems/0637.cpp | 40++++++++++++++++++++--------------------
MProblems/0646.cpp | 43+++++++++++++++++++++----------------------
MProblems/0649.cpp | 31++++++++++++++++---------------
MProblems/0652.cpp | 51+++++++++++++++++++++++++--------------------------
MProblems/0653.cpp | 41+++++++++++++++++++++--------------------
MProblems/0654.cpp | 56++++++++++++++++++++++++++++----------------------------
MProblems/0662.cpp | 38+++++++++++++++++++-------------------
MProblems/0664.cpp | 34+++++++++++++++++-----------------
MProblems/0669.cpp | 60++++++++++++++++++++++++++++++------------------------------
MProblems/0671.cpp | 36++++++++++++++++++------------------
MProblems/0673.cpp | 35+++++++++++++++++------------------
MProblems/0684.cpp | 48++++++++++++++++++++++++------------------------
MProblems/0688.cpp | 34+++++++++++++++++-----------------
MProblems/0692.cpp | 81++++++++++++++++++++++++++++++++++++++++++-------------------------------------
MProblems/0695.cpp | 2+-
MProblems/0700.cpp | 18+++++++++---------
MProblems/0701.cpp | 22+++++++++++-----------
MProblems/0703.cpp | 23++++++++++++-----------
MProblems/0704.cpp | 24++++++++++++------------
MProblems/0705.cpp | 51+++++++++++++++++++++++++--------------------------
MProblems/0706.cpp | 54+++++++++++++++++++++++++++---------------------------
MProblems/0707.cpp | 137++++++++++++++++++++++++++++++++++++++++---------------------------------------
MProblems/0712.cpp | 38+++++++++++++++++++-------------------
MProblems/0713.cpp | 26+++++++++++++-------------
MProblems/0714.cpp | 3+--
MProblems/0724.cpp | 18+++++++++---------
MProblems/0733.cpp | 71+++++++++++++++++++++++++++++++++++------------------------------------
MProblems/0735.cpp | 13++++++++-----
MProblems/0739.cpp | 30+++++++++++++++---------------
MProblems/0740.cpp | 27++++++++++++++-------------
MProblems/0743.cpp | 39++++++++++++++++++++-------------------
MProblems/0744.cpp | 30+++++++++++++++---------------
MProblems/0746.cpp | 32++++++++++++++++----------------
MProblems/0747.cpp | 28++++++++++++++--------------
MProblems/0752.cpp | 54+++++++++++++++++++++++++++---------------------------
MProblems/0763.cpp | 47++++++++++++++++++++++++-----------------------
MProblems/0767.cpp | 53+++++++++++++++++++++++++++--------------------------
MProblems/0783.cpp | 36++++++++++++++++++------------------
MProblems/0784.cpp | 33+++++++++++++++++----------------
MProblems/0785.cpp | 40++++++++++++++++++++--------------------
MProblems/0787.cpp | 47+++++++++++++++++++++++------------------------
MProblems/0797.cpp | 60++++++++++++++++++++++++++++++------------------------------
MProblems/0802.cpp | 119++++++++++++++++++++++++++++++++++++++++---------------------------------------
MProblems/0807.cpp | 14+++++++-------
MProblems/0808.cpp | 24+++++++++++-------------
MProblems/0811.cpp | 33+++++++++++++++++----------------
MProblems/0814.cpp | 54+++++++++++++++++++++++++++---------------------------
MProblems/0815.cpp | 50+++++++++++++++++++++++++-------------------------
MProblems/0837.cpp | 26+++++++++++++-------------
MProblems/0839.cpp | 79+++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/0841.cpp | 32++++++++++++++++----------------
MProblems/0844.cpp | 60++++++++++++++++++++++++++++++------------------------------
MProblems/0846.cpp | 87++++++++++++++++++++++++++++++++++++++-----------------------------------------
MProblems/0851.cpp | 46+++++++++++++++++++++++-----------------------
MProblems/0852.cpp | 24++++++++++++------------
MProblems/0853.cpp | 64++++++++++++++++++++++++++++++++--------------------------------
MProblems/0859.cpp | 38+++++++++++++++++++-------------------
MProblems/0861.cpp | 32++++++++++++++++----------------
MProblems/0863.cpp | 86++++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/0872.cpp | 40+++++++++++++++++++---------------------
MProblems/0875.cpp | 25+++++++++++++------------
MProblems/0876.cpp | 22+++++++++++-----------
MProblems/0879.cpp | 30+++++++++++++++---------------
MProblems/0881.cpp | 22+++++++++++-----------
MProblems/0884.cpp | 32+++++++++++++++++---------------
MProblems/0885.cpp | 35+++++++++++++++++------------------
MProblems/0886.cpp | 50+++++++++++++++++++++++++-------------------------
MProblems/0890.cpp | 47+++++++++++++++++++++++------------------------
MProblems/0894.cpp | 52+++++++++++++++++++++++++---------------------------
MProblems/0897.cpp | 36++++++++++++++++++------------------
MProblems/0901.cpp | 32++++++++++++++++----------------
MProblems/0904.cpp | 64++++++++++++++++++++++++++++++++--------------------------------
MProblems/0905.cpp | 18+++++++++---------
MProblems/0909.cpp | 62+++++++++++++++++++++++++++++++-------------------------------
MProblems/0912.cpp | 7+++----
MProblems/0915.cpp | 28++++++++++++++--------------
MProblems/0918.cpp | 26+++++++++++++-------------
MProblems/0920.cpp | 24++++++++++++------------
MProblems/0921.cpp | 28++++++++++++++--------------
MProblems/0926.cpp | 20++++++++++----------
MProblems/0931.cpp | 41+++++++++++++++++++++--------------------
MProblems/0933.cpp | 15++++++++-------
MProblems/0934.cpp | 96++++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/0938.cpp | 36++++++++++++++++++------------------
MProblems/0941.cpp | 22++++++++++++----------
MProblems/0944.cpp | 22+++++++++++-----------
MProblems/0946.cpp | 44++++++++++++++++++++++----------------------
MProblems/0947.cpp | 52++++++++++++++++++++++++++--------------------------
MProblems/0950.cpp | 33++++++++++++++++-----------------
MProblems/0953.cpp | 17+++++++++--------
MProblems/0956.cpp | 28++++++++++++++--------------
MProblems/0958.cpp | 34+++++++++++++++++-----------------
MProblems/0959.cpp | 115++++++++++++++++++++++++++++++++++++++-----------------------------------------
MProblems/0965.cpp | 30+++++++++++++++---------------
MProblems/0973.cpp | 27++++++++++++++-------------
MProblems/0974.cpp | 24++++++++++++------------
MProblems/0977.cpp | 51++++++++++++++++++++++++++-------------------------
MProblems/0980.cpp | 101++++++++++++++++++++++++++++++++++++++-----------------------------------------
MProblems/0983.cpp | 29+++++++++++++++--------------
MProblems/0986.cpp | 42+++++++++++++++++++++---------------------
MProblems/0989.cpp | 22+++++++++++-----------
MProblems/0990.cpp | 47+++++++++++++++++++++++------------------------
MProblems/0993.cpp | 46+++++++++++++++++++++++-----------------------
MProblems/0994.cpp | 2+-
MProblems/0997.cpp | 26+++++++++++++-------------
MProblems/1008.cpp | 35++++++++++++++++++-----------------
MProblems/1011.cpp | 29+++++++++++++++--------------
MProblems/1014.cpp | 2+-
MProblems/1019.cpp | 30+++++++++++++++---------------
MProblems/1020.cpp | 62+++++++++++++++++++++++++++++++-------------------------------
MProblems/1022.cpp | 36++++++++++++++++++------------------
MProblems/1026.cpp | 45++++++++++++++++++---------------------------
MProblems/1027.cpp | 43++++++++++++++++++++++---------------------
MProblems/1035.cpp | 30++++++++++++++----------------
MProblems/1038.cpp | 32++++++++++++++++----------------
MProblems/1042.cpp | 37+++++++++++++++++++------------------
MProblems/1046.cpp | 32++++++++++++++++----------------
MProblems/1047.cpp | 30+++++++++++++++---------------
MProblems/1051.cpp | 18+++++++++---------
MProblems/1061.cpp | 45++++++++++++++++++++++++---------------------
MProblems/1071.cpp | 6+++---
MProblems/1079.cpp | 38+++++++++++++++++++-------------------
MProblems/1089.cpp | 44++++++++++++++++++++++----------------------
MProblems/1091.cpp | 52++++++++++++++++++++++------------------------------
MProblems/1095.cpp | 14+++++++-------
MProblems/1099.cpp | 18+++++++++---------
MProblems/1104.cpp | 30+++++++++++++++---------------
MProblems/1111.cpp | 20++++++++++----------
MProblems/1125.cpp | 54+++++++++++++++++++++++++++---------------------------
MProblems/1129.cpp | 58++++++++++++++++++++++++++++++----------------------------
MProblems/1137.cpp | 43++++++++++++++++++++++---------------------
MProblems/1140.cpp | 32++++++++++++++++----------------
MProblems/1143.cpp | 52+++++++++++++++++++++++++---------------------------
MProblems/1146.cpp | 53++++++++++++++++++++++++-----------------------------
MProblems/1161.cpp | 40++++++++++++++++++++--------------------
MProblems/1162.cpp | 64++++++++++++++++++++++++++++++++--------------------------------
MProblems/1187.cpp | 51+++++++++++++++++++++++++--------------------------
MProblems/1202.cpp | 65++++++++++++++++++++++++++++++++++-------------------------------
MProblems/1203.cpp | 89+++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/1209.cpp | 30+++++++++++++++---------------
MProblems/1218.cpp | 20++++++++++----------
MProblems/1232.cpp | 22+++++++++++-----------
MProblems/1249.cpp | 33+++++++++++++++++----------------
MProblems/1254.cpp | 60++++++++++++++++++++++++++++++------------------------------
MProblems/1261.cpp | 40++++++++++++++++++++--------------------
MProblems/1277.cpp | 44+++++++++++++++++++++-----------------------
MProblems/1282.cpp | 34+++++++++++++++++-----------------
MProblems/1286.cpp | 45+++++++++++++++++++++++----------------------
MProblems/1290.cpp | 13+++++++------
MProblems/1302.cpp | 32++++++++++++++++----------------
MProblems/1305.cpp | 90++++++++++++++++++++++++++++++++++++++++---------------------------------------
MProblems/1311.cpp | 62++++++++++++++++++++++++++++++++------------------------------
MProblems/1312.cpp | 22+++++++++++-----------
MProblems/1314.cpp | 52++++++++++++++++++++++++++--------------------------
MProblems/1315.cpp | 48++++++++++++++++++++++++------------------------
MProblems/1318.cpp | 26+++++++++++++-------------
MProblems/1319.cpp | 66+++++++++++++++++++++++++++++++++---------------------------------
MProblems/1323.cpp | 18+++++++++---------
MProblems/1325.cpp | 54++++++++++++++++++++++++++----------------------------
MProblems/1329.cpp | 66++++++++++++++++++++++++++++++++++--------------------------------
MProblems/1334.cpp | 94++++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/1337.cpp | 36++++++++++++++++++------------------
MProblems/1339.cpp | 74+++++++++++++++++++++++++++++++++++++-------------------------------------
MProblems/1342.cpp | 22+++++++++++-----------
MProblems/1345.cpp | 83++++++++++++++++++++++++++++++++++++++++---------------------------------------
MProblems/1346.cpp | 21++++++++++-----------
MProblems/1347.cpp | 22+++++++++++-----------
MProblems/1351.cpp | 26+++++++++++++-------------
MProblems/1361.cpp | 84++++++++++++++++++++++++++++++++++++++-----------------------------------------
MProblems/1367.cpp | 54++++++++++++++++++++++++++++--------------------------
MProblems/1372.cpp | 26+++++++++++++-------------
MProblems/1373.cpp | 81+++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/1376.cpp | 45++++++++++++++++++++++-----------------------
MProblems/1379.cpp | 31+++++++++++++++----------------
MProblems/1381.cpp | 31++++++++++++++++---------------
MProblems/1382.cpp | 72+++++++++++++++++++++++++++++++++++-------------------------------------
MProblems/1396.cpp | 32+++++++++++++++-----------------
MProblems/1402.cpp | 17+++++++++--------
MProblems/1406.cpp | 27++++++++++++++-------------
MProblems/1409.cpp | 25+++++++++++++------------
MProblems/1415.cpp | 42+++++++++++++++++++++---------------------
MProblems/1416.cpp | 34+++++++++++++++++-----------------
MProblems/1418.cpp | 56+++++++++++++++++++++++++++++---------------------------
MProblems/1425.cpp | 25+++++++++++++------------
MProblems/1431.cpp | 16++++++++--------
MProblems/1436.cpp | 20++++++++++----------
MProblems/1438.cpp | 32+++++++++++++++++---------------
MProblems/1441.cpp | 24++++++++++++------------
MProblems/1442.cpp | 27++++++++++++++-------------
MProblems/1443.cpp | 66+++++++++++++++++++++++++++++++++---------------------------------
MProblems/1444.cpp | 55+++++++++++++++++++++++++++----------------------------
MProblems/1448.cpp | 32+++++++++++++++-----------------
MProblems/1456.cpp | 30++++++++++++++----------------
MProblems/1462.cpp | 151++++++++++++++++++++++++++++++++++++++++---------------------------------------
MProblems/1466.cpp | 48++++++++++++++++++++++++------------------------
MProblems/1470.cpp | 12++++++------
MProblems/1472.cpp | 50++++++++++++++++++++++++++------------------------
MProblems/1476.cpp | 15+++++++--------
MProblems/1480.cpp | 27++++++++++++++-------------
MProblems/1489.cpp | 98+++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/1491.cpp | 18+++++++++---------
MProblems/1493.cpp | 20++++++++++----------
MProblems/1498.cpp | 33+++++++++++++++++----------------
MProblems/1502.cpp | 20++++++++++----------
MProblems/1514.cpp | 56++++++++++++++++++++++++++++----------------------------
MProblems/1519.cpp | 61+++++++++++++++++++++++++++++++------------------------------
MProblems/1523.cpp | 6++----
MProblems/1529.cpp | 18+++++++++---------
MProblems/1539.cpp | 12++++++------
MProblems/1544.cpp | 24++++++++++++------------
MProblems/1547.cpp | 33++++++++++++++++-----------------
MProblems/1551.cpp | 10+++++-----
MProblems/1557.cpp | 19++++++++++---------
MProblems/1561.cpp | 18+++++++++---------
MProblems/1567.cpp | 4+---
MProblems/1569.cpp | 54+++++++++++++++++++++++++++---------------------------
MProblems/1572.cpp | 15++++++++-------
MProblems/1575.cpp | 29++++++++++++++---------------
MProblems/1579.cpp | 96+++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/1584.cpp | 95++++++++++++++++++++++++++++++++++++++-----------------------------------------
MProblems/1601.cpp | 41++++++++++++++++++++---------------------
MProblems/1603.cpp | 17++++++++---------
MProblems/1605.cpp | 22+++++++++++-----------
MProblems/1609.cpp | 44++++++++++++++++++++++----------------------
MProblems/1615.cpp | 30+++++++++++++++---------------
MProblems/1626.cpp | 33+++++++++++++++++----------------
MProblems/1630.cpp | 35+++++++++++++++++------------------
MProblems/1637.cpp | 22++++++++++++----------
MProblems/1639.cpp | 63+++++++++++++++++++++++++++++++--------------------------------
MProblems/1641.cpp | 15++++++++-------
MProblems/1646.cpp | 30+++++++++++++++---------------
MProblems/1669.cpp | 25++++++++++++++-----------
MProblems/1672.cpp | 13+++++++------
MProblems/1675.cpp | 34+++++++++++++++++-----------------
MProblems/1689.cpp | 6++----
MProblems/1696.cpp | 25+++++++++++++------------
MProblems/1697.cpp | 83+++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/1700.cpp | 32++++++++++++++++----------------
MProblems/1704.cpp | 20+++++++++-----------
MProblems/1706.cpp | 45+++++++++++++++++++++++----------------------
MProblems/1721.cpp | 24+++++++++++++-----------
MProblems/1722.cpp | 86++++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/1732.cpp | 13+++++++------
MProblems/1751.cpp | 93+++++++++++++++++++++++++++++++++++++------------------------------------------
MProblems/1768.cpp | 26++++++++++++++------------
MProblems/1769.cpp | 26+++++++++++++-------------
MProblems/1786.cpp | 127+++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/1791.cpp | 28++++++++++++++--------------
MProblems/1799.cpp | 31+++++++++++++++----------------
MProblems/1802.cpp | 30++++++++++++++----------------
MProblems/1817.cpp | 36++++++++++++++++++------------------
MProblems/1822.cpp | 16++++++++--------
MProblems/1823.cpp | 42++++++++++++++++++++++--------------------
MProblems/1828.cpp | 11+++++------
MProblems/1829.cpp | 18+++++++++---------
MProblems/1833.cpp | 16++++++++--------
MProblems/1834.cpp | 55++++++++++++++++++++++++++++---------------------------
MProblems/1857.cpp | 72++++++++++++++++++++++++++++++++++++------------------------------------
MProblems/1870.cpp | 15++++++++-------
MProblems/1877.cpp | 15++++++++-------
MProblems/1910.cpp | 12++++++------
MProblems/1926.cpp | 58++++++++++++++++++++++++++++------------------------------
MProblems/1962.cpp | 48+++++++++++++++++++++++++-----------------------
MProblems/1964.cpp | 42+++++++++++++++++++++---------------------
MProblems/1970.cpp | 99+++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/1971.cpp | 43++++++++++++++++++++++---------------------
MProblems/1976.cpp | 60++++++++++++++++++++++++++++++------------------------------
MProblems/1991.cpp | 18+++++++++---------
MProblems/2023.cpp | 23++++++++++++-----------
MProblems/2024.cpp | 26+++++++++++++-------------
MProblems/2039.cpp | 49++++++++++++++++++++++++-------------------------
MProblems/2044.cpp | 24++++++++++++------------
MProblems/2073.cpp | 20++++++++++----------
MProblems/2079.cpp | 24++++++++++++------------
MProblems/2085.cpp | 22++++++++++++----------
MProblems/2090.cpp | 34+++++++++++++++++-----------------
MProblems/2095.cpp | 28++++++++++++++--------------
MProblems/2101.cpp | 63+++++++++++++++++++++++++++++++--------------------------------
MProblems/2115.cpp | 76++++++++++++++++++++++++++++++++++++++--------------------------------------
MProblems/2120.cpp | 43++++++++++++++++++++-----------------------
MProblems/2125.cpp | 29+++++++++++++++--------------
MProblems/2130.cpp | 52++++++++++++++++++++++++++--------------------------
MProblems/2131.cpp | 41+++++++++++++++++++++--------------------
MProblems/2140.cpp | 21++++++++++-----------
MProblems/2141.cpp | 26+++++++++++++-------------
MProblems/2149.cpp | 15++++++++-------
MProblems/2161.cpp | 36+++++++++++++++++++-----------------
MProblems/2177.cpp | 12++++++------
MProblems/2181.cpp | 32++++++++++++++++----------------
MProblems/2187.cpp | 25+++++++++++++------------
MProblems/2192.cpp | 39++++++++++++++++++++-------------------
MProblems/2215.cpp | 120+++++++++++++++++++++++++++++++++++++++++--------------------------------------
MProblems/2218.cpp | 24+++++++++++-------------
MProblems/2221.cpp | 16++++++++--------
MProblems/2235.cpp | 4++--
MProblems/2236.cpp | 6++----
MProblems/2243.cpp | 25+++++++++++++------------
MProblems/2244.cpp | 21+++++++++++----------
MProblems/2246.cpp | 63++++++++++++++++++++++++++++++++-------------------------------
MProblems/2265.cpp | 56++++++++++++++++++++++++++++----------------------------
MProblems/2272.cpp | 37+++++++++++++++++++------------------
MProblems/2275.cpp | 17+++++++++--------
MProblems/2279.cpp | 26+++++++++++++-------------
MProblems/2285.cpp | 27++++++++++++++-------------
MProblems/2294.cpp | 16++++++++--------
MProblems/2300.cpp | 20+++++++++-----------
MProblems/2305.cpp | 43+++++++++++++++++++++----------------------
MProblems/2306.cpp | 67+++++++++++++++++++++++++++++++++++--------------------------------
MProblems/2316.cpp | 70+++++++++++++++++++++++++++++++++++-----------------------------------
MProblems/2317.cpp | 13+++++++------
MProblems/2326.cpp | 77+++++++++++++++++++++++++++++++++++------------------------------------------
MProblems/2328.cpp | 49+++++++++++++++++++++++++------------------------
MProblems/2331.cpp | 18+++++++++---------
MProblems/2336.cpp | 28++++++++++++++--------------
MProblems/2343.cpp | 7+++----
MProblems/2348.cpp | 20++++++++++----------
MProblems/2352.cpp | 24+++++++++++++-----------
MProblems/2359.cpp | 39++++++++++++++++++++-------------------
MProblems/2360.cpp | 54+++++++++++++++++++++++++++---------------------------
MProblems/2368.cpp | 49++++++++++++++++++++++++-------------------------
MProblems/2369.cpp | 38+++++++++++++++++++-------------------
MProblems/2374.cpp | 30+++++++++++++++---------------
MProblems/2375.cpp | 56++++++++++++++++++++++++++++----------------------------
MProblems/2390.cpp | 78+++++++++++++++++++++++++++++++++++++++---------------------------------------
MProblems/2391.cpp | 22+++++++++++-----------
MProblems/2396.cpp | 15++++++++-------
MProblems/2405.cpp | 30+++++++++++++++---------------
MProblems/2415.cpp | 33+++++++++++++++++----------------
MProblems/2421.cpp | 84+++++++++++++++++++++++++++++++++++++++++--------------------------------------
MProblems/2428.cpp | 20+++++++++-----------
MProblems/2433.cpp | 16++++++++--------
MProblems/2439.cpp | 16++++++++--------
MProblems/2442.cpp | 24+++++++++++++-----------
MProblems/2444.cpp | 30+++++++++++++++---------------
MProblems/2448.cpp | 48++++++++++++++++++++++++------------------------
MProblems/2461.cpp | 28++++++++++++++--------------
MProblems/2462.cpp | 40+++++++++++++++++++++-------------------
MProblems/2465.cpp | 16++++++++--------
MProblems/2466.cpp | 22+++++++++++-----------
MProblems/2467.cpp | 111+++++++++++++++++++++++++++++++++++++++----------------------------------------
MProblems/2477.cpp | 54+++++++++++++++++++++++++++---------------------------
MProblems/2482.cpp | 34+++++++++++++++++-----------------
MProblems/2492.cpp | 52++++++++++++++++++++++++++--------------------------
MProblems/2497.cpp | 41+++++++++++++++++++++--------------------
MProblems/2542.cpp | 39++++++++++++++++++++-------------------
MProblems/2545.cpp | 14++++++--------
MProblems/2551.cpp | 20+++++++++++---------
MProblems/2610.cpp | 24++++++++++++------------
MProblems/2616.cpp | 36++++++++++++++++++------------------
MProblems/2657.cpp | 41++++++++++++++++++++---------------------
MProblems/2785.cpp | 30+++++++++++++++---------------
MProblems/2807.cpp | 28++++++++++++++--------------
MTemplates/MST_pq.cpp | 20++++++++++----------
MTemplates/MST_vector.cpp | 18+++++++++---------
MTemplates/Union_Find.cpp | 42++++++++++++++++++++----------------------
MTemplates/bfs_floodfill.cpp | 29++++++++++++-----------------
MTemplates/bfs_floodfill_recursive.cpp | 25++++++++++---------------
660 files changed, 12063 insertions(+), 12028 deletions(-)

diff --git a/.clang-format b/.clang-format @@ -1,26 +1,45 @@ --- Language: Cpp -# BasedOnStyle: LLVM +# BasedOnStyle: Microsoft AccessModifierOffset: -2 -AlignAfterOpenBracket: true -AlignArrayOfStructures: Right -AlignConsecutiveMacros: true -AlignConsecutiveAssignments: None -AlignConsecutiveBitFields: None -AlignConsecutiveDeclarations: None +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false AlignEscapedNewlines: Right AlignOperands: Align AlignTrailingComments: true AllowAllArgumentsOnNextLine: true -AllowAllConstructorInitializersOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true -AllowShortEnumsOnASingleLine: true -AllowShortBlocksOnASingleLine: true +AllowShortEnumsOnASingleLine: false +AllowShortBlocksOnASingleLine: Never AllowShortCaseLabelsOnASingleLine: true -AllowShortFunctionsOnASingleLine: All +AllowShortFunctionsOnASingleLine: true AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: true -AllowShortLoopsOnASingleLine: true +AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false @@ -32,7 +51,7 @@ BinPackParameters: true BraceWrapping: AfterCaseLabel: false AfterClass: false - AfterControlStatement: Never + AfterControlStatement: false AfterEnum: false AfterFunction: false AfterNamespace: false @@ -49,8 +68,8 @@ BraceWrapping: SplitEmptyRecord: true SplitEmptyNamespace: true BreakBeforeBinaryOperators: None -BreakBeforeConceptDeclarations: true -BreakBeforeBraces: Attach +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Custom BreakBeforeInheritanceComma: false BreakInheritanceList: BeforeColon BreakBeforeTernaryOperators: true @@ -58,10 +77,10 @@ BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeColon BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true -ColumnLimit: 80 +ColumnLimit: 110 CommentPragmas: '^ IWYU pragma:' +QualifierAlignment: Leave CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true @@ -71,6 +90,10 @@ DisableFormat: false EmptyLineAfterAccessModifier: Never EmptyLineBeforeAccessModifier: LogicalBlock ExperimentalAutoDetectBinPacking: false +PackConstructorInitializers: BinPack +BasedOnStyle: '' +ConstructorInitializerAllOnOneLineOrOnePerLine: false +AllowAllConstructorInitializersOnNextLine: true FixNamespaceComments: true ForEachMacros: - foreach @@ -100,9 +123,10 @@ IndentCaseBlocks: false IndentGotoLabels: true IndentPPDirectives: None IndentExternBlock: AfterExternBlock -IndentRequires: false -IndentWidth: 2 +IndentRequiresClause: true +IndentWidth: 4 IndentWrappedFunctionNames: false +InsertBraces: false InsertTrailingCommas: None JavaScriptQuotes: Leave JavaScriptWrapImports: true @@ -121,15 +145,19 @@ PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 -PenaltyReturnTypeOnItsOwnLine: 60 +PenaltyReturnTypeOnItsOwnLine: 1000 PenaltyIndentedWhitespace: 0 PointerAlignment: Right PPIndentWidth: -1 ReferenceAlignment: Pointer ReflowComments: true +RemoveBracesLLVM: false +RequiresClausePosition: OwnLine +SeparateDefinitionBlocks: Leave ShortNamespaceLines: 1 SortIncludes: CaseSensitive SortJavaStaticImport: Before @@ -143,6 +171,16 @@ SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false SpaceAroundPointerQualifiers: Default SpaceBeforeRangeBasedForLoopColon: true SpaceInEmptyBlock: false @@ -165,7 +203,7 @@ StatementAttributeLikeMacros: StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION -TabWidth: 8 +TabWidth: 4 UseCRLF: false UseTab: Never WhitespaceSensitiveMacros: diff --git a/Problems/0001.cpp b/Problems/0001.cpp @@ -1,12 +1,12 @@ class Solution { -public: - vector<int> twoSum(vector<int> &nums, int target) { - unordered_map<int, int> um; - for (int i = 0; i < nums.size(); i++) - if (um.find(target - nums[i]) != um.end()) - return {um[target - nums[i]], i}; - else - um.insert(make_pair(nums[i], i)); - return {}; - } + public: + vector<int> twoSum(vector<int> &nums, int target) { + unordered_map<int, int> um; + for (int i = 0; i < nums.size(); i++) + if (um.find(target - nums[i]) != um.end()) + return {um[target - nums[i]], i}; + else + um.insert(make_pair(nums[i], i)); + return {}; + } }; diff --git a/Problems/0002.cpp b/Problems/0002.cpp @@ -1,23 +1,23 @@ class Solution { -public: - ListNode *addTwoNumbers(ListNode *list1, ListNode *list2) { - ListNode *head, *t; - t = head = new ListNode(); + public: + ListNode *addTwoNumbers(ListNode *list1, ListNode *list2) { + ListNode *head, *t; + t = head = new ListNode(); - int add = 0; - while (list1 || list2 || add) { - if (list1) { - add += list1->val; - list1 = list1->next; - } - if (list2) { - add += list2->val; - list2 = list2->next; - } - t = t->next = new ListNode(add % 10); - add /= 10; - } + int add = 0; + while (list1 || list2 || add) { + if (list1) { + add += list1->val; + list1 = list1->next; + } + if (list2) { + add += list2->val; + list2 = list2->next; + } + t = t->next = new ListNode(add % 10); + add /= 10; + } - return head->next; - } + return head->next; + } }; diff --git a/Problems/0003.cpp b/Problems/0003.cpp @@ -1,13 +1,14 @@ class Solution { -public: - int lengthOfLongestSubstring(string s) { - int maxi = 0; - unordered_set<char> us; - for (int i = 0, j = 0; j < size(s); j++) { - while (us.count(s[j])) us.erase(s[i++]); - maxi = max(j - i + 1, maxi); - us.insert(s[j]); + public: + int lengthOfLongestSubstring(string s) { + int maxi = 0; + unordered_set<char> us; + for (int i = 0, j = 0; j < size(s); j++) { + while (us.count(s[j])) + us.erase(s[i++]); + maxi = max(j - i + 1, maxi); + us.insert(s[j]); + } + return maxi; } - return maxi; - } }; diff --git a/Problems/0005.cpp b/Problems/0005.cpp @@ -1,20 +1,21 @@ class Solution { - const string len(const string &s, int a, int b) { - while (a >= 0 && b < s.size() && s[a] == s[b]) a--, b++; - return s.substr(a + 1, b - a - 1); - } + const string len(const string &s, int a, int b) { + while (a >= 0 && b < s.size() && s[a] == s[b]) + a--, b++; + return s.substr(a + 1, b - a - 1); + } -public: - string longestPalindrome(string s) { - string res = "", t; - s.push_back(' '); - for (int i = 0; i < s.size(); i++) { - t = len(s, i, i); - if (t.size() > res.size()) res = t; - if (s[i] != s[i + 1]) continue; - t = len(s, i, i + 1); - if (t.size() > res.size()) res = t; + public: + string longestPalindrome(string s) { + string res = "", t; + s.push_back(' '); + for (int i = 0; i < s.size(); i++) { + t = len(s, i, i); + if (t.size() > res.size()) res = t; + if (s[i] != s[i + 1]) continue; + t = len(s, i, i + 1); + if (t.size() > res.size()) res = t; + } + return res; } - return res; - } }; diff --git a/Problems/0006.cpp b/Problems/0006.cpp @@ -1,18 +1,19 @@ class Solution { -public: - string convert(string s, int numRows) { - if (numRows == 1) return s; - vector<string> mat(numRows); + public: + string convert(string s, int numRows) { + if (numRows == 1) return s; + vector<string> mat(numRows); - int mode = 1, x = 0; - for (char c : s) { - mat[x].push_back(c); - x += mode; - if (x == numRows - 1 || x == 0) mode *= -1; - } + int mode = 1, x = 0; + for (char c : s) { + mat[x].push_back(c); + x += mode; + if (x == numRows - 1 || x == 0) mode *= -1; + } - string res = ""; - for (const auto &r : mat) res += r; - return res; - } + string res = ""; + for (const auto &r : mat) + res += r; + return res; + } }; diff --git a/Problems/0007.cpp b/Problems/0007.cpp @@ -1,19 +1,21 @@ class Solution { -public: - int reverse(int x) { - if (x == INT_MIN || x == INT_MAX) return 0; + public: + int reverse(int x) { + if (x == INT_MIN || x == INT_MAX) return 0; - bool neg = false; - unsigned long res = 0; + bool neg = false; + unsigned long res = 0; - if (x < 0) { - neg = true; - x = -x; - } + if (x < 0) { + neg = true; + x = -x; + } - do { res = res * 10 + x % 10; } while ((x /= 10) > 0); + do { + res = res * 10 + x % 10; + } while ((x /= 10) > 0); - if (res > INT_MAX) return 0; - return !neg ? res : -res; - } + if (res > INT_MAX) return 0; + return !neg ? res : -res; + } }; diff --git a/Problems/0008.cpp b/Problems/0008.cpp @@ -1,23 +1,24 @@ class Solution { -public: - int myAtoi(string s) { - if (s == "-91283472332") return INT_MIN; - cout << INT_MAX << endl; - int i = 0, neg = 0, res = 0; - while (isspace(s[i])) i++; - if (s[i] == '-') - neg = 1, i++; - else if (s[i] == '+') - i++; + public: + int myAtoi(string s) { + if (s == "-91283472332") return INT_MIN; + cout << INT_MAX << endl; + int i = 0, neg = 0, res = 0; + while (isspace(s[i])) + i++; + if (s[i] == '-') + neg = 1, i++; + else if (s[i] == '+') + i++; - while (isdigit(s[i])) { - int digit = s[i++] - '0'; - if (res > (INT_MAX / 10) || (res == (INT_MAX / 10) && digit > 7)) { - return neg ? INT_MIN : INT_MAX; - } - res *= 10, res += digit; - } + while (isdigit(s[i])) { + int digit = s[i++] - '0'; + if (res > (INT_MAX / 10) || (res == (INT_MAX / 10) && digit > 7)) { + return neg ? INT_MIN : INT_MAX; + } + res *= 10, res += digit; + } - return neg ? -res : res; - } + return neg ? -res : res; + } }; diff --git a/Problems/0009.cpp b/Problems/0009.cpp @@ -1,9 +1,11 @@ class Solution { -public: - bool isPalindrome(int x) { - if (x < 0 || (x != 0 && x % 10 == 0)) return false; - int sum = 0; - do { sum = sum * 10 + x % 10; } while ((x /= 10) > sum); - return (x == sum) || (x == sum / 10); - } + public: + bool isPalindrome(int x) { + if (x < 0 || (x != 0 && x % 10 == 0)) return false; + int sum = 0; + do { + sum = sum * 10 + x % 10; + } while ((x /= 10) > sum); + return (x == sum) || (x == sum / 10); + } }; diff --git a/Problems/0011.cpp b/Problems/0011.cpp @@ -1,16 +1,17 @@ class Solution { -public: - int trap(vector<int> &height) { - int ans = 0, n = height.size(), maxi, m1, m2; - vector<int> mleft(n), mright(n); + public: + int trap(vector<int> &height) { + int ans = 0, n = height.size(), maxi, m1, m2; + vector<int> mleft(n), mright(n); - m1 = m2 = INT_MIN; - for (int i = 0; i < n; i++) { - mleft[i] = m1 = max(m1, height[i]); - mright[n - i - 1] = m2 = max(m2, height[n - i - 1]); - } + m1 = m2 = INT_MIN; + for (int i = 0; i < n; i++) { + mleft[i] = m1 = max(m1, height[i]); + mright[n - i - 1] = m2 = max(m2, height[n - i - 1]); + } - for (int i = 1; i < n - 1; i++) ans += min(mleft[i], mright[i]) - height[i]; - return ans; - } + for (int i = 1; i < n - 1; i++) + ans += min(mleft[i], mright[i]) - height[i]; + return ans; + } }; diff --git a/Problems/0012.cpp b/Problems/0012.cpp @@ -1,17 +1,19 @@ class Solution { -public: - vector<vector<string>> vvs = { - {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, - {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, - {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, - {"", "M", "MM", "MMM", "*", "*", "*", "*", "*", "*"}, - }; + public: + vector<vector<string>> vvs = { + {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, + {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, + {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, + {"", "M", "MM", "MMM", "*", "*", "*", "*", "*", "*"}, + }; - string intToRoman(int num) { - int exp = 0; - string res = ""; - do { res = vvs[exp++][num % 10] + res; } while ((num /= 10) > 0); + string intToRoman(int num) { + int exp = 0; + string res = ""; + do { + res = vvs[exp++][num % 10] + res; + } while ((num /= 10) > 0); - return res; - } + return res; + } }; diff --git a/Problems/0013.cpp b/Problems/0013.cpp @@ -1,31 +1,31 @@ class Solution { -public: - int value(char c) { - switch (c) { - case 'I': return 1; - case 'V': return 5; - case 'X': return 10; - case 'L': return 50; - case 'C': return 100; - case 'D': return 500; - case 'M': return 1000; - default: return -10000; + public: + int value(char c) { + switch (c) { + case 'I': return 1; + case 'V': return 5; + case 'X': return 10; + case 'L': return 50; + case 'C': return 100; + case 'D': return 500; + case 'M': return 1000; + default: return -10000; + } } - } - int romanToInt(string s) { - int size = s.size(); - int res = 0; - for (int i = 0; i < size - 1; i++) { - int a = value(s[i]); - int b = value(s[i + 1]); - if (a >= b) - res += a; - else - res -= a; - } - res += value(s[size - 1]); + int romanToInt(string s) { + int size = s.size(); + int res = 0; + for (int i = 0; i < size - 1; i++) { + int a = value(s[i]); + int b = value(s[i + 1]); + if (a >= b) + res += a; + else + res -= a; + } + res += value(s[size - 1]); - return res; - } + return res; + } }; diff --git a/Problems/0014.cpp b/Problems/0014.cpp @@ -1,15 +1,16 @@ class Solution { -public: - string longestCommonPrefix(vector<string> &strs) { - int mlen = 200; - for (string &s : strs) mlen = min(mlen, (int)s.size()); + public: + string longestCommonPrefix(vector<string> &strs) { + int mlen = 200; + for (string &s : strs) + mlen = min(mlen, (int)s.size()); - string res = ""; - for (int i = 0; i < mlen; i++) { - for (int j = 1; j < strs.size(); j++) - if (strs[j][i] != strs[0][i]) return res; - res += strs[0][i]; + string res = ""; + for (int i = 0; i < mlen; i++) { + for (int j = 1; j < strs.size(); j++) + if (strs[j][i] != strs[0][i]) return res; + res += strs[0][i]; + } + return res; } - return res; - } }; diff --git a/Problems/0015.cpp b/Problems/0015.cpp @@ -1,28 +1,30 @@ class Solution { -public: - vector<vector<int>> threeSum(vector<int> &num) { - sort(num.begin(), num.end()); + public: + vector<vector<int>> threeSum(vector<int> &num) { + sort(num.begin(), num.end()); - vector<vector<int>> res; - for (int i = 0; i < num.size();) { - int target = -num[i], start = i + 1, end = num.size() - 1; + vector<vector<int>> res; + for (int i = 0; i < num.size();) { + int target = -num[i], start = i + 1, end = num.size() - 1; - while (start < end) { - int sum = num[start] + num[end]; - if (sum < target) - start++; - else if (sum > target) - end--; - else { - res.push_back({num[i], num[start], num[end]}); - while (start < end && num[start] == res.back()[1]) start++; - while (start < end && num[end] == res.back()[2]) end--; + while (start < end) { + int sum = num[start] + num[end]; + if (sum < target) + start++; + else if (sum > target) + end--; + else { + res.push_back({num[i], num[start], num[end]}); + while (start < end && num[start] == res.back()[1]) + start++; + while (start < end && num[end] == res.back()[2]) + end--; + } + } + for (i++; i < num.size() && num[i] == num[i - 1]; i++) + ; } - } - for (i++; i < num.size() && num[i] == num[i - 1]; i++) - ; - } - return res; - } + return res; + } }; diff --git a/Problems/0016.cpp b/Problems/0016.cpp @@ -1,20 +1,20 @@ class Solution { -public: - int threeSumClosest(vector<int> &nums, int target) { - int n = nums.size(), delta = INT_MAX / 2, res = 0; - sort(nums.begin(), nums.end()); - for (int i = 0; i < n; i++) { - int j = i + 1; - int k = n - 1; - while (j < k) { - int sum = nums[i] + nums[j] + nums[k]; - if (abs(target - sum) < delta) { - delta = abs(target - sum); - res = sum; + public: + int threeSumClosest(vector<int> &nums, int target) { + int n = nums.size(), delta = INT_MAX / 2, res = 0; + sort(nums.begin(), nums.end()); + for (int i = 0; i < n; i++) { + int j = i + 1; + int k = n - 1; + while (j < k) { + int sum = nums[i] + nums[j] + nums[k]; + if (abs(target - sum) < delta) { + delta = abs(target - sum); + res = sum; + } + (sum > target) ? k-- : j++; + } } - (sum > target) ? k-- : j++; - } + return res; } - return res; - } }; diff --git a/Problems/0017.cpp b/Problems/0017.cpp @@ -1,17 +1,16 @@ class Solution { -public: - vector<string> letterCombinations(string digits) { - vector<string> um = {"abc", "def", "ghi", "jkl", - "mno", "pqrs", "tuv", "wxyz"}, - res = {""}; + public: + vector<string> letterCombinations(string digits) { + vector<string> um = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}, res = {""}; - for (char d : digits) { - vector<string> tmp; - for (char l : um[d - '2']) - for (const string &s : res) tmp.push_back(s + l); - res = tmp; - } + for (char d : digits) { + vector<string> tmp; + for (char l : um[d - '2']) + for (const string &s : res) + tmp.push_back(s + l); + res = tmp; + } - return res.size() > 1 ? res : vector<string>(); - } + return res.size() > 1 ? res : vector<string>(); + } }; diff --git a/Problems/0018.cpp b/Problems/0018.cpp @@ -1,30 +1,33 @@ class Solution { -public: - vector<vector<int>> fourSum(vector<int> &nums, int target) { - vector<vector<int>> res; - int n = nums.size(); + public: + vector<vector<int>> fourSum(vector<int> &nums, int target) { + vector<vector<int>> res; + int n = nums.size(); - sort(nums.begin(), nums.end()); - for (int i = 0; i < n; i++) { - for (int j = i + 1; j < n; j++) { - long long goal = (long long)target - nums[i] - nums[j]; - int k = j + 1, l = n - 1; - while (k < l) { - long long crnt = nums[k] + nums[l]; - if (crnt > goal) - l--; - else if (crnt < goal) - k++; - else { - res.push_back({nums[i], nums[j], nums[k], nums[l]}); - k++, l--; - while (k < l && nums[l] == nums[l + 1]) l--; - } + sort(nums.begin(), nums.end()); + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + long long goal = (long long)target - nums[i] - nums[j]; + int k = j + 1, l = n - 1; + while (k < l) { + long long crnt = nums[k] + nums[l]; + if (crnt > goal) + l--; + else if (crnt < goal) + k++; + else { + res.push_back({nums[i], nums[j], nums[k], nums[l]}); + k++, l--; + while (k < l && nums[l] == nums[l + 1]) + l--; + } + } + while (j + 1 < n && nums[j] == nums[j + 1]) + ++j; + } + while (i + 1 < n && nums[i] == nums[i + 1]) + ++i; } - while (j + 1 < n && nums[j] == nums[j + 1]) ++j; - } - while (i + 1 < n && nums[i] == nums[i + 1]) ++i; + return res; } - return res; - } }; diff --git a/Problems/0019.cpp b/Problems/0019.cpp @@ -1,19 +1,19 @@ class Solution { -public: - ListNode *removeNthFromEnd(ListNode *head, int n) { - ListNode *b = head; + public: + ListNode *removeNthFromEnd(ListNode *head, int n) { + ListNode *b = head; - n++; - for (ListNode *a = head; a; a = a->next) { - if (!n) - b = b->next; - else - n--; + n++; + for (ListNode *a = head; a; a = a->next) { + if (!n) + b = b->next; + else + n--; + } + if (n) + head = head->next; + else + b->next = b->next->next; + return head; } - if (n) - head = head->next; - else - b->next = b->next->next; - return head; - } }; diff --git a/Problems/0020.cpp b/Problems/0020.cpp @@ -1,30 +1,30 @@ class Solution { - char is_open(char c) { return c == '(' || c == '[' || c == '{'; } - char get_open_pair(char c) { - switch (c) { - case ')': return '('; - case ']': return '['; - case '}': return '{'; - default: return 0; + char is_open(char c) { return c == '(' || c == '[' || c == '{'; } + char get_open_pair(char c) { + switch (c) { + case ')': return '('; + case ']': return '['; + case '}': return '{'; + default: return 0; + } } - } -public: - bool isValid(string s) { - stack<char> st; + public: + bool isValid(string s) { + stack<char> st; - char t; - for (auto c : s) - if (is_open(c)) - st.push(c); - else if ((t = get_open_pair(c))) - if (!st.empty() && st.top() == t) - st.pop(); - else - return false; - else - return false; + char t; + for (auto c : s) + if (is_open(c)) + st.push(c); + else if ((t = get_open_pair(c))) + if (!st.empty() && st.top() == t) + st.pop(); + else + return false; + else + return false; - return st.empty(); - } + return st.empty(); + } }; diff --git a/Problems/0021.cpp b/Problems/0021.cpp @@ -1,19 +1,19 @@ class Solution { -public: - ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) { - ListNode head, *t = &head; + public: + ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) { + ListNode head, *t = &head; - while (list1 && list2) { - if (list1->val < list2->val) { - t = t->next = list1; - list1 = list1->next; - } else { - t = t->next = list2; - list2 = list2->next; - } - } + while (list1 && list2) { + if (list1->val < list2->val) { + t = t->next = list1; + list1 = list1->next; + } else { + t = t->next = list2; + list2 = list2->next; + } + } - t->next = list1 ? list1 : list2; - return head.next; - } + t->next = list1 ? list1 : list2; + return head.next; + } }; diff --git a/Problems/0022.cpp b/Problems/0022.cpp @@ -1,31 +1,31 @@ class Solution { - vector<string> res; - stack<char> st; - string crnt = ""; + vector<string> res; + stack<char> st; + string crnt = ""; - void dfs(int n) { - static const char o = '(', c = ')'; + void dfs(int n) { + static const char o = '(', c = ')'; - if (!n) { - if (st.empty()) res.push_back(crnt); - return; - } + if (!n) { + if (st.empty()) res.push_back(crnt); + return; + } - st.push(o), crnt += o; - dfs(n - 1); - st.pop(), crnt.pop_back(); + st.push(o), crnt += o; + dfs(n - 1); + st.pop(), crnt.pop_back(); - if (st.empty()) return; + if (st.empty()) return; - crnt += c, st.pop(); - dfs(n - 1); - crnt.pop_back(); - st.push(c); - } + crnt += c, st.pop(); + dfs(n - 1); + crnt.pop_back(); + st.push(c); + } -public: - vector<string> generateParenthesis(int n) { - dfs(n * 2); - return res; - } + public: + vector<string> generateParenthesis(int n) { + dfs(n * 2); + return res; + } }; diff --git a/Problems/0023.cpp b/Problems/0023.cpp @@ -1,48 +1,48 @@ // Naive solution, barely passed class Solution { -public: - ListNode *mergeKLists(vector<ListNode *> &lists) { - ListNode *dummy, *tmp; - tmp = dummy = new ListNode; + public: + ListNode *mergeKLists(vector<ListNode *> &lists) { + ListNode *dummy, *tmp; + tmp = dummy = new ListNode; - while (true) { - int mini = INT_MAX, index = -1; - for (int i = 0; i < lists.size(); i++) { - if (lists[i] && lists[i]->val < mini) { - index = i; - mini = lists[i]->val; + while (true) { + int mini = INT_MAX, index = -1; + for (int i = 0; i < lists.size(); i++) { + if (lists[i] && lists[i]->val < mini) { + index = i; + mini = lists[i]->val; + } + } + if (index == -1) break; + ListNode *t = lists[index]; + lists[index] = lists[index]->next; + tmp = tmp->next = t; } - } - if (index == -1) break; - ListNode *t = lists[index]; - lists[index] = lists[index]->next; - tmp = tmp->next = t; + return dummy->next; } - return dummy->next; - } }; // Proper solution class Solution { - typedef pair<int, int> pii; + typedef pair<int, int> pii; -public: - ListNode *mergeKLists(vector<ListNode *> &lists) { - ListNode *dummy, *tmp; - tmp = dummy = new ListNode; + public: + ListNode *mergeKLists(vector<ListNode *> &lists) { + ListNode *dummy, *tmp; + tmp = dummy = new ListNode; - auto cmp = [](const pii &a, const pii &b) { return a.first > b.first; }; - priority_queue<pii, vector<pii>, decltype(cmp)> pq(cmp); - for (int i = 0; i < lists.size(); i++) - if (lists[i]) pq.push({lists[i]->val, i}); - while (!pq.empty()) { - int index = pq.top().second; - pq.pop(); - ListNode *t = lists[index]; - lists[index] = lists[index]->next; - if (lists[index]) pq.push({lists[index]->val, index}); - tmp = tmp->next = t; + auto cmp = [](const pii &a, const pii &b) { return a.first > b.first; }; + priority_queue<pii, vector<pii>, decltype(cmp)> pq(cmp); + for (int i = 0; i < lists.size(); i++) + if (lists[i]) pq.push({lists[i]->val, i}); + while (!pq.empty()) { + int index = pq.top().second; + pq.pop(); + ListNode *t = lists[index]; + lists[index] = lists[index]->next; + if (lists[index]) pq.push({lists[index]->val, index}); + tmp = tmp->next = t; + } + return dummy->next; } - return dummy->next; - } }; diff --git a/Problems/0024.cpp b/Problems/0024.cpp @@ -1,14 +1,14 @@ class Solution { -public: - ListNode *swapPairs(ListNode *head) { - ListNode *d = new ListNode(-1, head); - for (ListNode *p = d; p->next && p->next->next;) { - ListNode *t = p->next; - p->next = p->next->next; - t->next = p->next->next; - p->next->next = t; - p = t; + public: + ListNode *swapPairs(ListNode *head) { + ListNode *d = new ListNode(-1, head); + for (ListNode *p = d; p->next && p->next->next;) { + ListNode *t = p->next; + p->next = p->next->next; + t->next = p->next->next; + p->next->next = t; + p = t; + } + return d->next; } - return d->next; - } }; diff --git a/Problems/0025.cpp b/Problems/0025.cpp @@ -1,21 +1,21 @@ class Solution { -public: - ListNode *reverseKGroup(ListNode *head, int k) { - stack<ListNode *> st; - ListNode *tmp, *dummy, *next; + public: + ListNode *reverseKGroup(ListNode *head, int k) { + stack<ListNode *> st; + ListNode *tmp, *dummy, *next; - tmp = dummy = new ListNode(-1, nullptr); - for (ListNode *p = head; p; p = next) { - next = p->next; - st.push(p); - if (st.size() == k) { - while (!st.empty()) { - tmp = tmp->next = st.top(); - st.pop(); + tmp = dummy = new ListNode(-1, nullptr); + for (ListNode *p = head; p; p = next) { + next = p->next; + st.push(p); + if (st.size() == k) { + while (!st.empty()) { + tmp = tmp->next = st.top(); + st.pop(); + } + tmp->next = next; + } } - tmp->next = next; - } + return dummy->next; } - return dummy->next; - } }; diff --git a/Problems/0026.cpp b/Problems/0026.cpp @@ -1,10 +1,10 @@ class Solution { -public: - int removeDuplicates(vector<int> &nums) { - int j = 1; - for (int i = 1; i < nums.size(); i++) { - if (nums[i - 1] != nums[i]) nums[j++] = nums[i]; + public: + int removeDuplicates(vector<int> &nums) { + int j = 1; + for (int i = 1; i < nums.size(); i++) { + if (nums[i - 1] != nums[i]) nums[j++] = nums[i]; + } + return j; } - return j; - } }; diff --git a/Problems/0027.cpp b/Problems/0027.cpp @@ -1,10 +1,10 @@ class Solution { -public: - int removeElement(vector<int> &nums, int val) { - int j = 0; - for (int i = 0; i < nums.size(); i++) - if (nums[i] != val) nums[j++] = nums[i]; + public: + int removeElement(vector<int> &nums, int val) { + int j = 0; + for (int i = 0; i < nums.size(); i++) + if (nums[i] != val) nums[j++] = nums[i]; - return j; - } + return j; + } }; diff --git a/Problems/0028.cpp b/Problems/0028.cpp @@ -1,24 +1,24 @@ class Solution { -public: - int strStr(string haystack, string needle) { - vector<int> table(needle.size(), 0); + public: + int strStr(string haystack, string needle) { + vector<int> table(needle.size(), 0); - int m = haystack.size(), n = needle.size(); - for (int len = 0, j = 1; j < n;) { - if (needle[j] == needle[len]) - table[j++] = ++len; - else if (len) - len = table[len - 1]; - else - table[j++] = 0; - } + int m = haystack.size(), n = needle.size(); + for (int len = 0, j = 1; j < n;) { + if (needle[j] == needle[len]) + table[j++] = ++len; + else if (len) + len = table[len - 1]; + else + table[j++] = 0; + } - for (int i = 0, j = 0; i < m;) { - if (haystack[i] == needle[j]) i++, j++; - if (j == n) return i - j; - if (i < m && haystack[i] != needle[j]) j ? j = table[j - 1] : i++; - } + for (int i = 0, j = 0; i < m;) { + if (haystack[i] == needle[j]) i++, j++; + if (j == n) return i - j; + if (i < m && haystack[i] != needle[j]) j ? j = table[j - 1] : i++; + } - return -1; - } + return -1; + } }; diff --git a/Problems/0029.cpp b/Problems/0029.cpp @@ -1,35 +1,35 @@ class Solution { -public: - int divide(int dividend, int divisor) { - if (divisor == INT_MIN) return dividend == INT_MIN; - if (divisor == INT_MAX) { - if (dividend == INT_MIN) return -1; - if (dividend == INT_MAX) return 1; - return 0; - } + public: + int divide(int dividend, int divisor) { + if (divisor == INT_MIN) return dividend == INT_MIN; + if (divisor == INT_MAX) { + if (dividend == INT_MIN) return -1; + if (dividend == INT_MAX) return 1; + return 0; + } - if (divisor == 1) return dividend; - if (divisor == -1) { - if (dividend == INT_MIN) return INT_MAX; - return -dividend; - } + if (divisor == 1) return dividend; + if (divisor == -1) { + if (dividend == INT_MIN) return INT_MAX; + return -dividend; + } - int res = 0, sign = 1; - if (divisor < 0) divisor = -divisor, sign = -sign; - if (dividend < 0) { - if (dividend == INT_MIN) dividend += divisor, res++; - dividend = -dividend, sign = -sign; - } + int res = 0, sign = 1; + if (divisor < 0) divisor = -divisor, sign = -sign; + if (dividend < 0) { + if (dividend == INT_MIN) dividend += divisor, res++; + dividend = -dividend, sign = -sign; + } - while (dividend >= divisor) { - long temp = divisor, count = 1; - while (temp << 1 <= dividend) { - temp <<= 1; - count <<= 1; - } - dividend -= temp; - res += count; + while (dividend >= divisor) { + long temp = divisor, count = 1; + while (temp << 1 <= dividend) { + temp <<= 1; + count <<= 1; + } + dividend -= temp; + res += count; + } + return sign * res; } - return sign * res; - } }; diff --git a/Problems/0031.cpp b/Problems/0031.cpp @@ -1,17 +1,17 @@ class Solution { -public: - void nextPermutation(vector<int> &nums) { - int n = nums.size(), k, l; - for (k = n - 2; k >= 0 && nums[k] >= nums[k + 1]; k--) - ; + public: + void nextPermutation(vector<int> &nums) { + int n = nums.size(), k, l; + for (k = n - 2; k >= 0 && nums[k] >= nums[k + 1]; k--) + ; - if (k >= 0) { - for (l = n - 1; l > k && nums[l] <= nums[k]; l--) - ; - swap(nums[k], nums[l]); - reverse(nums.begin() + k + 1, nums.end()); - } else { - reverse(nums.begin(), nums.end()); + if (k >= 0) { + for (l = n - 1; l > k && nums[l] <= nums[k]; l--) + ; + swap(nums[k], nums[l]); + reverse(nums.begin() + k + 1, nums.end()); + } else { + reverse(nums.begin(), nums.end()); + } } - } }; diff --git a/Problems/0033.cpp b/Problems/0033.cpp @@ -1,24 +1,30 @@ class Solution { - int binary_search(const vector<int>& nums, int target, int low, int high) { - while(low<=high){ - int mid = low + (high-low)/2; - if(nums[mid]==target) return mid; - else if(nums[mid]>target) high = mid-1; - else low = mid + 1; + int binary_search(const vector<int> &nums, int target, int low, int high) { + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] == target) + return mid; + else if (nums[mid] > target) + high = mid - 1; + else + low = mid + 1; + } + return -1; } - return -1; - } -public: - int search(vector<int>& nums, int target) { - int pivot = -1; - for(int i=0; i<nums.size()-1; i++) { - if(nums[i] > nums[i+1]) { - pivot = i; - break; + + public: + int search(vector<int> &nums, int target) { + int pivot = -1; + for (int i = 0; i < nums.size() - 1; i++) { + if (nums[i] > nums[i + 1]) { + pivot = i; + break; + } } - } - if(pivot==-1) return binary_search(nums, target, 0, nums.size()-1); - if(nums[0]<=target) return binary_search(nums, target, 0, pivot); - else return binary_search(nums, target, pivot+1, nums.size()-1); + if (pivot == -1) return binary_search(nums, target, 0, nums.size() - 1); + if (nums[0] <= target) + return binary_search(nums, target, 0, pivot); + else + return binary_search(nums, target, pivot + 1, nums.size() - 1); } }; diff --git a/Problems/0034.cpp b/Problems/0034.cpp @@ -1,20 +1,26 @@ class Solution { - int binary_search(const vector<int>& nums, int target) { - int low = 0, high = nums.size()-1; - while(low<=high){ - int mid = low + (high-low)/2; - if(nums[mid]==target) return mid; - else if(nums[mid]>target) high = mid-1; - else low = mid + 1; + int binary_search(const vector<int> &nums, int target) { + int low = 0, high = nums.size() - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] == target) + return mid; + else if (nums[mid] > target) + high = mid - 1; + else + low = mid + 1; + } + return -1; } - return -1; - } -public: - vector<int> searchRange(vector<int>& nums, int target) { + + public: + vector<int> searchRange(vector<int> &nums, int target) { int low, high; low = high = binary_search(nums, target); - while(low-1>=0 && nums[low-1] == target) low--; - while(high+1<nums.size() && nums[high+1] == target) high++; + while (low - 1 >= 0 && nums[low - 1] == target) + low--; + while (high + 1 < nums.size() && nums[high + 1] == target) + high++; return {low, high}; } }; diff --git a/Problems/0035.cpp b/Problems/0035.cpp @@ -1,15 +1,15 @@ class Solution { -public: - int searchInsert(vector<int> &nums, int target) { - int low = 0, high = nums.size() - 1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (nums[mid] == target) return mid; - if (nums[mid] < target) - low = mid + 1; - else - high = mid - 1; + public: + int searchInsert(vector<int> &nums, int target) { + int low = 0, high = nums.size() - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] == target) return mid; + if (nums[mid] < target) + low = mid + 1; + else + high = mid - 1; + } + return high + 1; } - return high + 1; - } }; diff --git a/Problems/0036.cpp b/Problems/0036.cpp @@ -1,2 +1 @@ -Formating: Problems/0036.cpp -Formating: Problems/0074.cpp +Formating : Problems / 0036.cpp Formating : Problems / 0074.cpp diff --git a/Problems/0037.cpp b/Problems/0037.cpp @@ -1,31 +1,31 @@ class Solution { - bool check(vector<vector<char>> &board, int i, int j, char val) { - for (int x = 0; x < 9; x++) - if (board[x][j] == val) return false; - for (int y = 0; y < 9; y++) - if (board[i][y] == val) return false; + bool check(vector<vector<char>> &board, int i, int j, char val) { + for (int x = 0; x < 9; x++) + if (board[x][j] == val) return false; + for (int y = 0; y < 9; y++) + if (board[i][y] == val) return false; - i = (i / 3) * 3, j = (j / 3) * 3; - for (int x = i; x < i + 3; x++) - for (int y = j; y < j + 3; y++) - if (board[x][y] == val) return false; - return true; - } - bool solveSudoku(vector<vector<char>> &board, int i, int j) { - if (i == 9) return true; - if (j == 9) return solveSudoku(board, i + 1, 0); - if (board[i][j] != '.') return solveSudoku(board, i, j + 1); - - for (char c = '1'; c <= '9'; c++) { - if (!check(board, i, j, c)) continue; - board[i][j] = c; - if (solveSudoku(board, i, j + 1)) return true; - board[i][j] = '.'; + i = (i / 3) * 3, j = (j / 3) * 3; + for (int x = i; x < i + 3; x++) + for (int y = j; y < j + 3; y++) + if (board[x][y] == val) return false; + return true; } + bool solveSudoku(vector<vector<char>> &board, int i, int j) { + if (i == 9) return true; + if (j == 9) return solveSudoku(board, i + 1, 0); + if (board[i][j] != '.') return solveSudoku(board, i, j + 1); + + for (char c = '1'; c <= '9'; c++) { + if (!check(board, i, j, c)) continue; + board[i][j] = c; + if (solveSudoku(board, i, j + 1)) return true; + board[i][j] = '.'; + } - return false; - } + return false; + } -public: - void solveSudoku(vector<vector<char>> &board) { solveSudoku(board, 0, 0); } + public: + void solveSudoku(vector<vector<char>> &board) { solveSudoku(board, 0, 0); } }; diff --git a/Problems/0038.cpp b/Problems/0038.cpp @@ -1,21 +1,21 @@ class Solution { -public: - string countAndSay(int n) { - string crnt = "1"; - for (int i = 1; i < n; i++) { - string res = ""; - int c = crnt.front(), count = 1; - for (int i = 1; i < crnt.size(); i++) { - if (crnt[i] == c) - count++; - else { - res += to_string(count) + (char)c; - count = 1; - c = crnt[i]; + public: + string countAndSay(int n) { + string crnt = "1"; + for (int i = 1; i < n; i++) { + string res = ""; + int c = crnt.front(), count = 1; + for (int i = 1; i < crnt.size(); i++) { + if (crnt[i] == c) + count++; + else { + res += to_string(count) + (char)c; + count = 1; + c = crnt[i]; + } + } + crnt = res + to_string(count) + (char)c; } - } - crnt = res + to_string(count) + (char)c; + return crnt; } - return crnt; - } }; diff --git a/Problems/0039.cpp b/Problems/0039.cpp @@ -1,23 +1,23 @@ class Solution { - vector<vector<int>> res; - vector<int> crnt; + vector<vector<int>> res; + vector<int> crnt; - void rec(vector<int> &candidates, int target, int sum, int start = 0) { - if (sum == target) - res.push_back(crnt); - else if (sum < target) { - for (int i = start; i < candidates.size(); i++) { - crnt.push_back(candidates[i]); - rec(candidates, target, sum + candidates[i], i); - crnt.pop_back(); - } + void rec(vector<int> &candidates, int target, int sum, int start = 0) { + if (sum == target) + res.push_back(crnt); + else if (sum < target) { + for (int i = start; i < candidates.size(); i++) { + crnt.push_back(candidates[i]); + rec(candidates, target, sum + candidates[i], i); + crnt.pop_back(); + } + } } - } -public: - vector<vector<int>> combinationSum(vector<int> &candidates, int target) { - sort(candidates.begin(), candidates.end()); - rec(candidates, target, 0); - return res; - } + public: + vector<vector<int>> combinationSum(vector<int> &candidates, int target) { + sort(candidates.begin(), candidates.end()); + rec(candidates, target, 0); + return res; + } }; diff --git a/Problems/0040.cpp b/Problems/0040.cpp @@ -1,24 +1,24 @@ class Solution { - vector<vector<int>> res; - vector<int> crnt; + vector<vector<int>> res; + vector<int> crnt; - void rec(vector<int> &candidates, int target, int sum, int start = 0) { - if (sum == target) - res.push_back(crnt); - else if (sum < target) { - for (int i = start; i < candidates.size(); i++) { - if (i != start && candidates[i] == candidates[i - 1]) continue; - crnt.push_back(candidates[i]); - rec(candidates, target, sum + candidates[i], i + 1); - crnt.pop_back(); - } + void rec(vector<int> &candidates, int target, int sum, int start = 0) { + if (sum == target) + res.push_back(crnt); + else if (sum < target) { + for (int i = start; i < candidates.size(); i++) { + if (i != start && candidates[i] == candidates[i - 1]) continue; + crnt.push_back(candidates[i]); + rec(candidates, target, sum + candidates[i], i + 1); + crnt.pop_back(); + } + } } - } -public: - vector<vector<int>> combinationSum2(vector<int> &candidates, int target) { - sort(candidates.begin(), candidates.end()); - rec(candidates, target, 0); - return res; - } + public: + vector<vector<int>> combinationSum2(vector<int> &candidates, int target) { + sort(candidates.begin(), candidates.end()); + rec(candidates, target, 0); + return res; + } }; diff --git a/Problems/0043.cpp b/Problems/0043.cpp @@ -1,27 +1,27 @@ class Solution { -public: - string multiply(string num1, string num2) { - if (num1 == "0" || num2 == "0") return "0"; + public: + string multiply(string num1, string num2) { + if (num1 == "0" || num2 == "0") return "0"; - reverse(num1.begin(), num1.end()); - reverse(num2.begin(), num2.end()); - string answer(num1.size() + num2.size(), '0'); + reverse(num1.begin(), num1.end()); + reverse(num2.begin(), num2.end()); + string answer(num1.size() + num2.size(), '0'); - for (int p2 = 0; p2 < num2.size(); p2++) { - int d2 = num2[p2] - '0'; - for (int p1 = 0; p1 < num1.size(); p1++) { - int d1 = num1[p1] - '0'; + for (int p2 = 0; p2 < num2.size(); p2++) { + int d2 = num2[p2] - '0'; + for (int p1 = 0; p1 < num1.size(); p1++) { + int d1 = num1[p1] - '0'; - int numZero = p1 + p2; - int carry = answer[numZero] - '0'; - int mul = d1 * d2 + carry; - answer[numZero] = mul % 10 + '0'; - answer[numZero + 1] += mul / 10; - } - } - if (answer.back() == '0') answer.pop_back(); + int numZero = p1 + p2; + int carry = answer[numZero] - '0'; + int mul = d1 * d2 + carry; + answer[numZero] = mul % 10 + '0'; + answer[numZero + 1] += mul / 10; + } + } + if (answer.back() == '0') answer.pop_back(); - reverse(answer.begin(), answer.end()); - return answer; - } + reverse(answer.begin(), answer.end()); + return answer; + } }; diff --git a/Problems/0044.cpp b/Problems/0044.cpp @@ -1,21 +1,22 @@ class Solution { -public: - bool isMatch(string s, string p) { - int i = 0, j = 0, n = s.size(), m = p.size(); - int last = -1, star = -1; - while (i < n) { - if (j < m && (s[i] == p[j] || p[j] == '?')) - i++, j++; - else if (j < m && p[j] == '*') { - star = j++; - last = i; - } else if (star != -1) { - j = star + 1; - i = ++last; - } else - return false; + public: + bool isMatch(string s, string p) { + int i = 0, j = 0, n = s.size(), m = p.size(); + int last = -1, star = -1; + while (i < n) { + if (j < m && (s[i] == p[j] || p[j] == '?')) + i++, j++; + else if (j < m && p[j] == '*') { + star = j++; + last = i; + } else if (star != -1) { + j = star + 1; + i = ++last; + } else + return false; + } + while (p[j] == '*' && j < m) + j++; + return j == m; } - while (p[j] == '*' && j < m) j++; - return j == m; - } }; diff --git a/Problems/0045.cpp b/Problems/0045.cpp @@ -1,14 +1,14 @@ class Solution { -public: - int jump(vector<int> &nums) { - int n = nums.size(), limit = 0; - vector<int> num(n); - num[0] = 0; - for (int i = 0; i <= limit && i < n; i++) { - for (int j = limit + 1; j <= i + nums[i] && j < n; j++) - num[j] = num[i] + 1; - limit = max(limit, i + nums[i]); + public: + int jump(vector<int> &nums) { + int n = nums.size(), limit = 0; + vector<int> num(n); + num[0] = 0; + for (int i = 0; i <= limit && i < n; i++) { + for (int j = limit + 1; j <= i + nums[i] && j < n; j++) + num[j] = num[i] + 1; + limit = max(limit, i + nums[i]); + } + return num.back(); } - return num.back(); - } }; diff --git a/Problems/0046.cpp b/Problems/0046.cpp @@ -1,25 +1,25 @@ class Solution { - vector<vector<int>> res; - vector<int> crnt; - vector<bool> seen; + vector<vector<int>> res; + vector<int> crnt; + vector<bool> seen; - void rec(vector<int> &nums, int n) { - if (n == nums.size()) { - res.push_back(crnt); - return; + void rec(vector<int> &nums, int n) { + if (n == nums.size()) { + res.push_back(crnt); + return; + } + for (int i = 0; i < nums.size(); i++) { + if (seen[i]) continue; + seen[i] = true, crnt.push_back(nums[i]); + rec(nums, n + 1); + seen[i] = false, crnt.pop_back(); + } } - for (int i = 0; i < nums.size(); i++) { - if (seen[i]) continue; - seen[i] = true, crnt.push_back(nums[i]); - rec(nums, n + 1); - seen[i] = false, crnt.pop_back(); - } - } -public: - vector<vector<int>> permute(vector<int> &nums) { - seen.resize(nums.size()); - rec(nums, 0); - return res; - } + public: + vector<vector<int>> permute(vector<int> &nums) { + seen.resize(nums.size()); + rec(nums, 0); + return res; + } }; diff --git a/Problems/0047.cpp b/Problems/0047.cpp @@ -1,11 +1,11 @@ class Solution { -public: - vector<vector<int>> permuteUnique(vector<int> &nums) { - vector<vector<int>> res; - sort(nums.begin(), nums.end()); - do { - res.push_back(nums); - } while (next_permutation(nums.begin(), nums.end())); - return res; - } + public: + vector<vector<int>> permuteUnique(vector<int> &nums) { + vector<vector<int>> res; + sort(nums.begin(), nums.end()); + do { + res.push_back(nums); + } while (next_permutation(nums.begin(), nums.end())); + return res; + } }; diff --git a/Problems/0048.cpp b/Problems/0048.cpp @@ -1,17 +1,18 @@ class Solution { - typedef vector<vector<int>> Mat; - int n; + typedef vector<vector<int>> Mat; + int n; - void swap_group(Mat &matrix, int x, int y) { - swap(matrix[x][y], matrix[y][n - x - 1]); - swap(matrix[n - x - 1][n - y - 1], matrix[n - y - 1][x]); - swap(matrix[x][y], matrix[n - x - 1][n - y - 1]); - } + void swap_group(Mat &matrix, int x, int y) { + swap(matrix[x][y], matrix[y][n - x - 1]); + swap(matrix[n - x - 1][n - y - 1], matrix[n - y - 1][x]); + swap(matrix[x][y], matrix[n - x - 1][n - y - 1]); + } -public: - void rotate(Mat &matrix) { - n = matrix.size(); - for (int i = 0; i <= n / 2; i++) - for (int j = i; j < n - i - 1; j++) swap_group(matrix, i, j); - } + public: + void rotate(Mat &matrix) { + n = matrix.size(); + for (int i = 0; i <= n / 2; i++) + for (int j = i; j < n - i - 1; j++) + swap_group(matrix, i, j); + } }; diff --git a/Problems/0049.cpp b/Problems/0049.cpp @@ -1,20 +1,22 @@ class Solution { -public: - vector<vector<string>> groupAnagrams(vector<string> &strs) { - vector<vector<string>> res; - unordered_map<unsigned long long, int> um; - for (int i = 0; i < strs.size(); i++) { - unsigned long long hash = 0; - vector<int> m(26, 0); + public: + vector<vector<string>> groupAnagrams(vector<string> &strs) { + vector<vector<string>> res; + unordered_map<unsigned long long, int> um; + for (int i = 0; i < strs.size(); i++) { + unsigned long long hash = 0; + vector<int> m(26, 0); - for (char c : strs[i]) m[c - 'a']++; - for (int i = 0; i < 26; i++) hash = hash * 100 + m[i]; - if (um.find(hash) == um.end()) { - um[hash] = res.size(); - res.push_back({strs[i]}); - } else - res[um[hash]].push_back(strs[i]); + for (char c : strs[i]) + m[c - 'a']++; + for (int i = 0; i < 26; i++) + hash = hash * 100 + m[i]; + if (um.find(hash) == um.end()) { + um[hash] = res.size(); + res.push_back({strs[i]}); + } else + res[um[hash]].push_back(strs[i]); + } + return res; } - return res; - } }; diff --git a/Problems/0050.cpp b/Problems/0050.cpp @@ -1,8 +1,8 @@ class Solution { -public: - double myPow(double x, int n) { - if (n == 0) return 1; - if (n < 0) return 1 / x * myPow(1 / x, -(n + 1)); - return (n % 2 == 0) ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); - } + public: + double myPow(double x, int n) { + if (n == 0) return 1; + if (n < 0) return 1 / x * myPow(1 / x, -(n + 1)); + return (n % 2 == 0) ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); + } }; diff --git a/Problems/0051.cpp b/Problems/0051.cpp @@ -1,53 +1,46 @@ class Solution { - vector<vector<string>> res; - vector<string> board; - unordered_set<int> used; - int n; + vector<vector<string>> res; + vector<string> board; + unordered_set<int> used; + int n; - bool valid(int row, int col) { - return row >= 0 && row < n && col >= 0 && col < n; - } + bool valid(int row, int col) { return row >= 0 && row < n && col >= 0 && col < n; } - bool safe(int row, int col) { - static vector<pair<int, int>> ofsts = { - { 1, 1}, - { 1, -1}, - {-1, 1}, - {-1, -1} - }; + bool safe(int row, int col) { + static vector<pair<int, int>> ofsts = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; - if (used.count(col)) return false; - for (auto &ofst : ofsts) { - int a = row + ofst.first, b = col + ofst.second; - while (valid(a, b)) { - if (board[a][b] == 'Q') return false; - a += ofst.first, b += ofst.second; - } + if (used.count(col)) return false; + for (auto &ofst : ofsts) { + int a = row + ofst.first, b = col + ofst.second; + while (valid(a, b)) { + if (board[a][b] == 'Q') return false; + a += ofst.first, b += ofst.second; + } + } + return true; } - return true; - } - void rec(int row) { - if (row == n) { - res.push_back(board); - return; - } + void rec(int row) { + if (row == n) { + res.push_back(board); + return; + } - for (int i = 0; i < n; i++) { - if (!safe(row, i)) continue; - used.insert(i); - board[row][i] = 'Q'; - rec(row + 1); - used.erase(i); - board[row][i] = '.'; + for (int i = 0; i < n; i++) { + if (!safe(row, i)) continue; + used.insert(i); + board[row][i] = 'Q'; + rec(row + 1); + used.erase(i); + board[row][i] = '.'; + } } - } -public: - vector<vector<string>> solveNQueens(int n) { - this->n = n; - board = vector<string>(n, string(n, '.')); - rec(0); - return res; - } + public: + vector<vector<string>> solveNQueens(int n) { + this->n = n; + board = vector<string>(n, string(n, '.')); + rec(0); + return res; + } }; diff --git a/Problems/0052.cpp b/Problems/0052.cpp @@ -1,52 +1,45 @@ class Solution { - vector<string> board; - unordered_set<int> used; - int n, res; + vector<string> board; + unordered_set<int> used; + int n, res; - bool valid(int row, int col) { - return row >= 0 && row < n && col >= 0 && col < n; - } + bool valid(int row, int col) { return row >= 0 && row < n && col >= 0 && col < n; } - bool safe(int row, int col) { - static vector<pair<int, int>> ofsts = { - { 1, 1}, - { 1, -1}, - {-1, 1}, - {-1, -1} - }; + bool safe(int row, int col) { + static vector<pair<int, int>> ofsts = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; - if (used.count(col)) return false; - for (auto &ofst : ofsts) { - int a = row + ofst.first, b = col + ofst.second; - while (valid(a, b)) { - if (board[a][b] == 'Q') return false; - a += ofst.first, b += ofst.second; - } + if (used.count(col)) return false; + for (auto &ofst : ofsts) { + int a = row + ofst.first, b = col + ofst.second; + while (valid(a, b)) { + if (board[a][b] == 'Q') return false; + a += ofst.first, b += ofst.second; + } + } + return true; } - return true; - } - void rec(int row) { - if (row == n) { - res++; - return; - } + void rec(int row) { + if (row == n) { + res++; + return; + } - for (int i = 0; i < n; i++) { - if (!safe(row, i)) continue; - used.insert(i); - board[row][i] = 'Q'; - rec(row + 1); - used.erase(i); - board[row][i] = '.'; + for (int i = 0; i < n; i++) { + if (!safe(row, i)) continue; + used.insert(i); + board[row][i] = 'Q'; + rec(row + 1); + used.erase(i); + board[row][i] = '.'; + } } - } -public: - int totalNQueens(int n) { - this->n = n; - board = vector<string>(n, string(n, '.')); - rec(0); - return res; - } + public: + int totalNQueens(int n) { + this->n = n; + board = vector<string>(n, string(n, '.')); + rec(0); + return res; + } }; diff --git a/Problems/0053.cpp b/Problems/0053.cpp @@ -1,26 +1,27 @@ // memorization approach class Solution { -public: - int maxSubArray(vector<int> &nums) { - int n = nums.size(), maxi; - vector<int> dp(n); + public: + int maxSubArray(vector<int> &nums) { + int n = nums.size(), maxi; + vector<int> dp(n); - maxi = dp[0] = nums[0]; - for (int i = 1; i < n; i++) { - dp[i] = nums[i] + max(dp[i - 1], 0); - maxi = max(maxi, dp[i]); + maxi = dp[0] = nums[0]; + for (int i = 1; i < n; i++) { + dp[i] = nums[i] + max(dp[i - 1], 0); + maxi = max(maxi, dp[i]); + } + return maxi; } - return maxi; - } }; // optimized, memorize only the previous value class Solution { -public: - int maxSubArray(vector<int> &nums) { - int n = nums.size(), maxi, prev; - maxi = prev = nums[0]; - for (int i = 1; i < n; i++) maxi = max(maxi, prev = nums[i] + max(prev, 0)); - return maxi; - } + public: + int maxSubArray(vector<int> &nums) { + int n = nums.size(), maxi, prev; + maxi = prev = nums[0]; + for (int i = 1; i < n; i++) + maxi = max(maxi, prev = nums[i] + max(prev, 0)); + return maxi; + } }; diff --git a/Problems/0054.cpp b/Problems/0054.cpp @@ -1,44 +1,37 @@ class Solution { - pair<int, int> offset[4] = { - { 0, 1}, - { 1, 0}, - { 0, -1}, - {-1, 0} - }; - int limit_offset[4] = {1, -1, -1, 1}; - int limit[4] = {0, 0, 0, 0}; - - int &m = limit[2], &n = limit[1]; - - bool valid(int i, int j) { - return i >= limit[0] && i <= m && j >= limit[3] && j <= n; - } - -public: - vector<int> spiralOrder(vector<vector<int>> &matrix) { - vector<int> res; - int direction = 0; - int cnt = 0; - int size; - int i = 0, j = 0; - - m = matrix.size() - 1; - n = matrix[0].size() - 1; - size = (m + 1) * (n + 1); - - while (true) { - res.push_back(matrix[i][j]); - if (++cnt == size) break; - - if (!valid(i + offset[direction].first, j + offset[direction].second)) { - limit[direction] += limit_offset[direction]; - direction = (direction + 1) % 4; - } - - i += offset[direction].first; - j += offset[direction].second; - } + pair<int, int> offset[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int limit_offset[4] = {1, -1, -1, 1}; + int limit[4] = {0, 0, 0, 0}; + + int &m = limit[2], &n = limit[1]; + + bool valid(int i, int j) { return i >= limit[0] && i <= m && j >= limit[3] && j <= n; } + + public: + vector<int> spiralOrder(vector<vector<int>> &matrix) { + vector<int> res; + int direction = 0; + int cnt = 0; + int size; + int i = 0, j = 0; + + m = matrix.size() - 1; + n = matrix[0].size() - 1; + size = (m + 1) * (n + 1); - return res; - } + while (true) { + res.push_back(matrix[i][j]); + if (++cnt == size) break; + + if (!valid(i + offset[direction].first, j + offset[direction].second)) { + limit[direction] += limit_offset[direction]; + direction = (direction + 1) % 4; + } + + i += offset[direction].first; + j += offset[direction].second; + } + + return res; + } }; diff --git a/Problems/0055.cpp b/Problems/0055.cpp @@ -1,8 +1,9 @@ class Solution { -public: - bool canJump(vector<int> &nums) { - int n = nums.size(), limit = 0; - for (int i = 0; i <= limit && i < n; i++) limit = max(limit, i + nums[i]); - return limit >= n - 1; - } + public: + bool canJump(vector<int> &nums) { + int n = nums.size(), limit = 0; + for (int i = 0; i <= limit && i < n; i++) + limit = max(limit, i + nums[i]); + return limit >= n - 1; + } }; diff --git a/Problems/0056.cpp b/Problems/0056.cpp @@ -1,25 +1,23 @@ class Solution { - typedef vector<int> interval; + typedef vector<int> interval; -public: - vector<interval> merge(vector<interval> &intervals) { - auto cmp = [](const interval &i1, const interval &i2) { - return i1[0] < i2[0]; - }; - sort(intervals.begin(), intervals.end(), cmp); + public: + vector<interval> merge(vector<interval> &intervals) { + auto cmp = [](const interval &i1, const interval &i2) { return i1[0] < i2[0]; }; + sort(intervals.begin(), intervals.end(), cmp); - vector<interval> res; - int start = intervals[0][0], end = intervals[0][1]; - for (auto &i : intervals) { - if (i[0] > end) { - res.push_back({start, end}); - start = i[0]; - } - end = max(end, i[1]); - } + vector<interval> res; + int start = intervals[0][0], end = intervals[0][1]; + for (auto &i : intervals) { + if (i[0] > end) { + res.push_back({start, end}); + start = i[0]; + } + end = max(end, i[1]); + } - if (res.empty() || res.back()[1] != end) res.push_back({start, end}); + if (res.empty() || res.back()[1] != end) res.push_back({start, end}); - return res; - } + return res; + } }; diff --git a/Problems/0057.cpp b/Problems/0057.cpp @@ -1,25 +1,27 @@ class Solution { - typedef vector<int> Interval; + typedef vector<int> Interval; -public: - vector<Interval> insert(vector<Interval> &intervals, Interval &newInterval) { - if (intervals.empty()) return {newInterval}; + public: + vector<Interval> insert(vector<Interval> &intervals, Interval &newInterval) { + if (intervals.empty()) return {newInterval}; - vector<Interval> res; - int n = intervals.size(), i = 0; - for (; i < n && intervals[i][1] < newInterval[0]; i++) { - res.push_back(intervals[i]); - } + vector<Interval> res; + int n = intervals.size(), i = 0; + for (; i < n && intervals[i][1] < newInterval[0]; i++) { + res.push_back(intervals[i]); + } - for (; i < n && newInterval[1] >= intervals[i][0]; i++) { - newInterval[0] = min(newInterval[0], intervals[i][0]); - newInterval[1] = max(newInterval[1], intervals[i][1]); - } + for (; i < n && newInterval[1] >= intervals[i][0]; i++) { + newInterval[0] = min(newInterval[0], intervals[i][0]); + newInterval[1] = max(newInterval[1], intervals[i][1]); + } - res.push_back(newInterval); + res.push_back(newInterval); - for (; i < n; i++) { res.push_back(intervals[i]); } + for (; i < n; i++) { + res.push_back(intervals[i]); + } - return res; - } + return res; + } }; diff --git a/Problems/0058.cpp b/Problems/0058.cpp @@ -1,10 +1,11 @@ class Solution { -public: - int lengthOfLastWord(string s) { - int i = s.size(), res = 0; - while (--i >= 0 && isspace(s[i])) - ; - while (i >= 0 && !isspace(s[i--])) res++; - return res; - } + public: + int lengthOfLastWord(string s) { + int i = s.size(), res = 0; + while (--i >= 0 && isspace(s[i])) + ; + while (i >= 0 && !isspace(s[i--])) + res++; + return res; + } }; diff --git a/Problems/0059.cpp b/Problems/0059.cpp @@ -1,43 +1,36 @@ class Solution { - pair<int, int> offset[4] = { - { 0, 1}, - { 1, 0}, - { 0, -1}, - {-1, 0} - }; - int limit_offset[4] = {1, -1, -1, 1}; - int limit[4] = {0, 0, 0, 0}; - - int &m = limit[2], &n = limit[1]; - - bool valid(int i, int j) { - return i >= limit[0] && i <= m && j >= limit[3] && j <= n; - } - -public: - vector<vector<int>> generateMatrix(int dim) { - vector<vector<int>> res(dim, vector<int>(dim)); - int direction = 0; - int cnt = 0; - int size; - int i = 0, j = 0; - - m = n = dim - 1; - size = (m + 1) * (n + 1); - - while (true) { - res[i][j] = ++cnt; - if (cnt == size) break; - - if (!valid(i + offset[direction].first, j + offset[direction].second)) { - limit[direction] += limit_offset[direction]; - direction = (direction + 1) % 4; - } - - i += offset[direction].first; - j += offset[direction].second; - } + pair<int, int> offset[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int limit_offset[4] = {1, -1, -1, 1}; + int limit[4] = {0, 0, 0, 0}; + + int &m = limit[2], &n = limit[1]; + + bool valid(int i, int j) { return i >= limit[0] && i <= m && j >= limit[3] && j <= n; } + + public: + vector<vector<int>> generateMatrix(int dim) { + vector<vector<int>> res(dim, vector<int>(dim)); + int direction = 0; + int cnt = 0; + int size; + int i = 0, j = 0; + + m = n = dim - 1; + size = (m + 1) * (n + 1); - return res; - } + while (true) { + res[i][j] = ++cnt; + if (cnt == size) break; + + if (!valid(i + offset[direction].first, j + offset[direction].second)) { + limit[direction] += limit_offset[direction]; + direction = (direction + 1) % 4; + } + + i += offset[direction].first; + j += offset[direction].second; + } + + return res; + } }; diff --git a/Problems/0060.cpp b/Problems/0060.cpp @@ -1,15 +1,17 @@ class Solution { -public: - string getPermutation(int n, int k) { - vector<char> avail = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; - int factorial = 1, pos; - string res; - for (int i = 1; i <= n; i++) factorial *= i; - for (k--; n; n--) { - factorial /= n; - res += avail[pos = k / factorial], k -= pos * factorial; - for (int i = pos; i < avail.size() - 1; i++) avail[i] = avail[i + 1]; + public: + string getPermutation(int n, int k) { + vector<char> avail = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; + int factorial = 1, pos; + string res; + for (int i = 1; i <= n; i++) + factorial *= i; + for (k--; n; n--) { + factorial /= n; + res += avail[pos = k / factorial], k -= pos * factorial; + for (int i = pos; i < avail.size() - 1; i++) + avail[i] = avail[i + 1]; + } + return res; } - return res; - } }; diff --git a/Problems/0061.cpp b/Problems/0061.cpp @@ -1,29 +1,29 @@ class Solution { - int len(ListNode *head) { - int count = 0; - while (head) { - count++; - head = head->next; + int len(ListNode *head) { + int count = 0; + while (head) { + count++; + head = head->next; + } + return count; } - return count; - } -public: - ListNode *rotateRight(ListNode *head, int k) { - if (!head) return nullptr; + public: + ListNode *rotateRight(ListNode *head, int k) { + if (!head) return nullptr; - k %= len(head); - ListNode *p, *t; - t = p = head; - for (; p->next; p = p->next) { - if (k) - k--; - else - t = t->next; + k %= len(head); + ListNode *p, *t; + t = p = head; + for (; p->next; p = p->next) { + if (k) + k--; + else + t = t->next; + } + p->next = head; + head = t->next; + t->next = nullptr; + return head; } - p->next = head; - head = t->next; - t->next = nullptr; - return head; - } }; diff --git a/Problems/0062.cpp b/Problems/0062.cpp @@ -1,21 +1,21 @@ class Solution { -public: - int uniquePaths(int n, int m) { - vector<vector<int>> mat(n, vector<int>(m, 0)); - queue<pair<int, int>> q; - q.push({n - 1, m - 1}), mat[n - 1][m - 1] = 1; - while (!q.empty()) { - auto [x, y] = q.front(); - q.pop(); - if (x - 1 >= 0) { - mat[x - 1][y] += mat[x][y]; - if (mat[x - 1][y] == mat[x][y]) q.push({x - 1, y}); - } - if (y - 1 >= 0) { - mat[x][y - 1] += mat[x][y]; - if (mat[x][y - 1] == mat[x][y]) q.push({x, y - 1}); - } + public: + int uniquePaths(int n, int m) { + vector<vector<int>> mat(n, vector<int>(m, 0)); + queue<pair<int, int>> q; + q.push({n - 1, m - 1}), mat[n - 1][m - 1] = 1; + while (!q.empty()) { + auto [x, y] = q.front(); + q.pop(); + if (x - 1 >= 0) { + mat[x - 1][y] += mat[x][y]; + if (mat[x - 1][y] == mat[x][y]) q.push({x - 1, y}); + } + if (y - 1 >= 0) { + mat[x][y - 1] += mat[x][y]; + if (mat[x][y - 1] == mat[x][y]) q.push({x, y - 1}); + } + } + return mat[0][0]; } - return mat[0][0]; - } }; diff --git a/Problems/0063.cpp b/Problems/0063.cpp @@ -1,28 +1,28 @@ class Solution { -public: - int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) { - int dp[101][101] = {0}; - int n = obstacleGrid.size(), m = obstacleGrid[0].size(); + public: + int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) { + int dp[101][101] = {0}; + int n = obstacleGrid.size(), m = obstacleGrid[0].size(); - for (int i = 0, flag = 0; i < n; i++) { - if (flag || obstacleGrid[i][0]) - flag = true; - else - dp[i][0] = 1; - } + for (int i = 0, flag = 0; i < n; i++) { + if (flag || obstacleGrid[i][0]) + flag = true; + else + dp[i][0] = 1; + } - for (int i = 0, flag = 0; i < m; i++) { - if (flag || obstacleGrid[0][i]) - flag = true; - else - dp[0][i] = 1; - } + for (int i = 0, flag = 0; i < m; i++) { + if (flag || obstacleGrid[0][i]) + flag = true; + else + dp[0][i] = 1; + } - for (int i = 1; i < n; i++) { - for (int j = 1; j < m; j++) { - if (obstacleGrid[i][j] != 1) dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; - } + for (int i = 1; i < n; i++) { + for (int j = 1; j < m; j++) { + if (obstacleGrid[i][j] != 1) dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + return dp[n - 1][m - 1]; } - return dp[n - 1][m - 1]; - } }; diff --git a/Problems/0064.cpp b/Problems/0064.cpp @@ -1,17 +1,19 @@ class Solution { -public: - int minPathSum(vector<vector<int>> &grid) { - int n = grid.size(), m = grid[0].size(); + public: + int minPathSum(vector<vector<int>> &grid) { + int n = grid.size(), m = grid[0].size(); - for (int i = 1; i < n; i++) grid[i][0] += grid[i - 1][0]; - for (int j = 1; j < m; j++) grid[0][j] += grid[0][j - 1]; + for (int i = 1; i < n; i++) + grid[i][0] += grid[i - 1][0]; + for (int j = 1; j < m; j++) + grid[0][j] += grid[0][j - 1]; - for (int i = 1; i < n; i++) { - for (int j = 1; j < m; j++) { - grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]); - } - } + for (int i = 1; i < n; i++) { + for (int j = 1; j < m; j++) { + grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]); + } + } - return grid[n - 1][m - 1]; - } + return grid[n - 1][m - 1]; + } }; diff --git a/Problems/0066.cpp b/Problems/0066.cpp @@ -1,15 +1,15 @@ class Solution { -public: - vector<int> plusOne(vector<int> &digits) { - vector<int> res; + public: + vector<int> plusOne(vector<int> &digits) { + vector<int> res; - int add = 1; - for (int i = digits.size() - 1; i >= 0 || add; i--) { - if (i >= 0) add += digits[i]; - res.push_back(add % 10); - add /= 10; + int add = 1; + for (int i = digits.size() - 1; i >= 0 || add; i--) { + if (i >= 0) add += digits[i]; + res.push_back(add % 10); + add /= 10; + } + reverse(res.begin(), res.end()); + return res; } - reverse(res.begin(), res.end()); - return res; - } }; diff --git a/Problems/0067.cpp b/Problems/0067.cpp @@ -1,17 +1,17 @@ class Solution { -public: - string addBinary(string a, string b) { - string res; - int i = a.size() - 1; - int j = b.size() - 1; - int add = 0; - while (i >= 0 || j >= 0 || add) { - if (i >= 0) add += a[i--] - '0'; - if (j >= 0) add += b[j--] - '0'; - res += to_string(add % 2); - add /= 2; + public: + string addBinary(string a, string b) { + string res; + int i = a.size() - 1; + int j = b.size() - 1; + int add = 0; + while (i >= 0 || j >= 0 || add) { + if (i >= 0) add += a[i--] - '0'; + if (j >= 0) add += b[j--] - '0'; + res += to_string(add % 2); + add /= 2; + } + reverse(res.begin(), res.end()); + return res; } - reverse(res.begin(), res.end()); - return res; - } }; diff --git a/Problems/0068.cpp b/Problems/0068.cpp @@ -1,36 +1,34 @@ class Solution { -public: - vector<string> fullJustify(vector<string> &words, int maxWidth) { - vector<string> res; - int i = 0, j; - while (i < words.size()) { - int count = words[i].size(); // character count - for (j = i + 1; j < words.size() && count <= maxWidth; j++) - count += words[j].size() + 1; // word lenght + at least 1 space + public: + vector<string> fullJustify(vector<string> &words, int maxWidth) { + vector<string> res; + int i = 0, j; + while (i < words.size()) { + int count = words[i].size(); // character count + for (j = i + 1; j < words.size() && count <= maxWidth; j++) + count += words[j].size() + 1; // word lenght + at least 1 space - if (count > maxWidth) - count -= words[--j].size() + 1; // if we overshot, remove last word - int wordc = j - i; // number of words for the current row - count -= - wordc - 1; // remove minimum padding added from the character count; - int white = maxWidth - count; // how much whitespace - string row = words[i++]; - if (i != j) { - if (j != words.size()) { - while (i < j) { - int segment = ceil((double)white / (wordc-- - 1)); - row += string(min(segment, white), ' ') + words[i++]; - white -= segment; - } - } else { - // last row, adjust left - while (i < j) row += " " + words[i++]; + if (count > maxWidth) count -= words[--j].size() + 1; // if we overshot, remove last word + int wordc = j - i; // number of words for the current row + count -= wordc - 1; // remove minimum padding added from the character count; + int white = maxWidth - count; // how much whitespace + string row = words[i++]; + if (i != j) { + if (j != words.size()) { + while (i < j) { + int segment = ceil((double)white / (wordc-- - 1)); + row += string(min(segment, white), ' ') + words[i++]; + white -= segment; + } + } else { + // last row, adjust left + while (i < j) + row += " " + words[i++]; + } + } + row += string(maxWidth - row.size(), ' '); // padd the remainder of the row + res.push_back(row); // push the current row to the result } - } - row += - string(maxWidth - row.size(), ' '); // padd the remainder of the row - res.push_back(row); // push the current row to the result + return res; } - return res; - } }; diff --git a/Problems/0069.cpp b/Problems/0069.cpp @@ -1,16 +1,16 @@ class Solution { -public: - int mySqrt(int x) { - int low = 1, high = x; - while (low <= high) { - int mid = low + (high - low) / 2; - if (mid == x / mid) - return mid; - else if (mid > x / mid) - high = mid - 1; - else - low = mid + 1; + public: + int mySqrt(int x) { + int low = 1, high = x; + while (low <= high) { + int mid = low + (high - low) / 2; + if (mid == x / mid) + return mid; + else if (mid > x / mid) + high = mid - 1; + else + low = mid + 1; + } + return high; } - return high; - } }; diff --git a/Problems/0070.cpp b/Problems/0070.cpp @@ -1,27 +1,28 @@ // memorization approach class Solution { -public: - int climbStairs(int n) { - vector<int> vec(46); - vec[0] = 1; - vec[1] = 1; - for (int i = 2; i <= n; i++) vec[i] = vec[i - 1] + vec[i - 2]; + public: + int climbStairs(int n) { + vector<int> vec(46); + vec[0] = 1; + vec[1] = 1; + for (int i = 2; i <= n; i++) + vec[i] = vec[i - 1] + vec[i - 2]; - return vec[n]; - } + return vec[n]; + } } // optimized, memorize only the previous two values class Solution { -public: - int climbStairs(int n) { - int first = 1, second = 1; - for (int i = 2; i <= n; i++) { - int cnt = first + second; - first = second; - second = cnt; - } + public: + int climbStairs(int n) { + int first = 1, second = 1; + for (int i = 2; i <= n; i++) { + int cnt = first + second; + first = second; + second = cnt; + } - return second; - } + return second; + } }; diff --git a/Problems/0071.cpp b/Problems/0071.cpp @@ -1,26 +1,28 @@ class Solution { -public: + public: string simplifyPath(string path) { - deque<string> dq; - int start = 0; + deque<string> dq; + int start = 0; - path.push_back('/'); - for(int i=0; i<path.size(); i++) { - if(path[i] != '/') continue; - else { - string s = path.substr(start, i - start); - if(s=="..") { - if(!dq.empty()) dq.pop_back(); - }else if(!s.empty() && s!=".") dq.push_back(s); - start = i + 1; + path.push_back('/'); + for (int i = 0; i < path.size(); i++) { + if (path[i] != '/') + continue; + else { + string s = path.substr(start, i - start); + if (s == "..") { + if (!dq.empty()) dq.pop_back(); + } else if (!s.empty() && s != ".") + dq.push_back(s); + start = i + 1; + } } - } - string res = ""; - while(!dq.empty()) { - res+="/" + dq.front(); - dq.pop_front(); - } - return res.empty() ? "/" : res; + string res = ""; + while (!dq.empty()) { + res += "/" + dq.front(); + dq.pop_front(); + } + return res.empty() ? "/" : res; } -}; +}; diff --git a/Problems/0072.cpp b/Problems/0072.cpp @@ -1,41 +1,43 @@ class Solution { -public: - int minDistance(string word1, string word2) { - int n = word1.size(), m = word2.size(); - vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0)); - for (int i = 1; i <= n; i++) dp[i][0] = i; - for (int j = 1; j <= m; j++) dp[0][j] = j; + public: + int minDistance(string word1, string word2) { + int n = word1.size(), m = word2.size(); + vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0)); + for (int i = 1; i <= n; i++) + dp[i][0] = i; + for (int j = 1; j <= m; j++) + dp[0][j] = j; - for (int i = 1; i <= n; i++) { - for (int j = 1; j <= m; j++) { - if (word1[i - 1] == word2[j - 1]) - dp[i][j] = dp[i - 1][j - 1]; - else - dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1; - } + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + if (word1[i - 1] == word2[j - 1]) + dp[i][j] = dp[i - 1][j - 1]; + else + dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1; + } + } + return dp.back().back(); } - return dp.back().back(); - } }; // Improvement, use two DP arrays instead of a matrix class Solution { -public: - int minDistance(const string &word1, const string &word2) { - int n = word1.size(), m = word2.size(); - if (n == 0 || m == 0) return max(m, n); - vector<int> dp1(m + 1, 0), dp2(m + 1, 0); - iota(dp1.begin(), dp1.end(), 0); - for (int i = 1; i <= n; i++) { - dp2[0]++; - for (int j = 1; j <= m; j++) { - if (word1[i - 1] == word2[j - 1]) - dp2[j] = dp1[j - 1]; - else - dp2[j] = min({dp1[j - 1], dp2[j - 1], dp1[j]}) + 1; - } - dp1 = dp2; + public: + int minDistance(const string &word1, const string &word2) { + int n = word1.size(), m = word2.size(); + if (n == 0 || m == 0) return max(m, n); + vector<int> dp1(m + 1, 0), dp2(m + 1, 0); + iota(dp1.begin(), dp1.end(), 0); + for (int i = 1; i <= n; i++) { + dp2[0]++; + for (int j = 1; j <= m; j++) { + if (word1[i - 1] == word2[j - 1]) + dp2[j] = dp1[j - 1]; + else + dp2[j] = min({dp1[j - 1], dp2[j - 1], dp1[j]}) + 1; + } + dp1 = dp2; + } + return dp2[m]; } - return dp2[m]; - } }; diff --git a/Problems/0073.cpp b/Problems/0073.cpp @@ -1,25 +1,27 @@ class Solution { -public: - void setZeroes(vector<vector<int>> &matrix) { - int n = matrix.size(), m = matrix[0].size(); - unordered_set<int> rows, cols; + public: + void setZeroes(vector<vector<int>> &matrix) { + int n = matrix.size(), m = matrix[0].size(); + unordered_set<int> rows, cols; - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - if (matrix[i][j]) continue; - rows.insert(i); - cols.insert(j); - } - } + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (matrix[i][j]) continue; + rows.insert(i); + cols.insert(j); + } + } - for (int row : rows) { - for (int j = 0; j < m; j++) matrix[row][j] = 0; - } + for (int row : rows) { + for (int j = 0; j < m; j++) + matrix[row][j] = 0; + } - for (int col : cols) { - for (int i = 0; i < n; i++) matrix[i][col] = 0; - } + for (int col : cols) { + for (int i = 0; i < n; i++) + matrix[i][col] = 0; + } - return; - } + return; + } }; diff --git a/Problems/0074.cpp b/Problems/0074.cpp @@ -1,59 +1,60 @@ class Solution { -public: - bool searchMatrix(vector<vector<int>> &matrix, int target) { - int n = matrix.size(), m = matrix[0].size(), row = n - 1; - for (int i = 0; i < n - 1; i++) { - if (matrix[i + 1][0] > target) { - row = i; - break; - } - } + public: + bool searchMatrix(vector<vector<int>> &matrix, int target) { + int n = matrix.size(), m = matrix[0].size(), row = n - 1; + for (int i = 0; i < n - 1; i++) { + if (matrix[i + 1][0] > target) { + row = i; + break; + } + } - int low = 0, high = m - 1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (matrix[row][mid] == target) - return true; - else if (matrix[row][mid] < target) - low = mid + 1; - else - high = mid - 1; + int low = 0, high = m - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (matrix[row][mid] == target) + return true; + else if (matrix[row][mid] < target) + low = mid + 1; + else + high = mid - 1; + } + return false; } - return false; - } }; // Treat the matrix as a sorted list class Solution { -public: - bool searchMatrix(vector<vector<int>> &matrix, int target) { - int n = matrix.size(), m = matrix[0].size(); - int low = 0, high = m * n - 1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (matrix[mid / m][mid % m] == target) return true; - if (matrix[mid / m][mid % m] < target) - low = mid + 1; - else - high = mid - 1; + public: + bool searchMatrix(vector<vector<int>> &matrix, int target) { + int n = matrix.size(), m = matrix[0].size(); + int low = 0, high = m * n - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (matrix[mid / m][mid % m] == target) return true; + if (matrix[mid / m][mid % m] < target) + low = mid + 1; + else + high = mid - 1; + } + return false; } - return false; - } }; // Binary Search Tree class Solution { -public: - bool searchMatrix(vector<vector<int>> &matrix, int target) { - int n = matrix.size(), m = matrix[0].size(); - int row = 0, col = m - 1; - - while (row < n && col > -1) { - if (matrix[row][col] == target) return true; - if (target > matrix[row][col]) row++; - else col--; + public: + bool searchMatrix(vector<vector<int>> &matrix, int target) { + int n = matrix.size(), m = matrix[0].size(); + int row = 0, col = m - 1; + + while (row < n && col > -1) { + if (matrix[row][col] == target) return true; + if (target > matrix[row][col]) + row++; + else + col--; + } + return false; } - return false; - } }; - diff --git a/Problems/0075.cpp b/Problems/0075.cpp @@ -1,10 +1,12 @@ class Solution { -public: - void sortColors(vector<int> &nums) { - array<int, 3> arr; - for (int n : nums) arr[n]++; - int count = 0; - for (int i = 0; i < 3; i++) - while (arr[i]--) nums[count++] = i; - } + public: + void sortColors(vector<int> &nums) { + array<int, 3> arr; + for (int n : nums) + arr[n]++; + int count = 0; + for (int i = 0; i < 3; i++) + while (arr[i]--) + nums[count++] = i; + } }; diff --git a/Problems/0076.cpp b/Problems/0076.cpp @@ -1,23 +1,24 @@ class Solution { -public: - string minWindow(string s, string t) { - vector<int> remaining(128, 0); - for (char c : t) remaining[c]++; + public: + string minWindow(string s, string t) { + vector<int> remaining(128, 0); + for (char c : t) + remaining[c]++; - int required = t.size(); - int min = INT_MAX, start = 0, left = 0, i = 0; - while (i <= s.size() && start < s.size()) { - if (required) { - if (i == s.size()) break; - if (--remaining[s[i++]] >= 0) required--; - } else { - if (i - start < min) { - min = i - start; - left = start; + int required = t.size(); + int min = INT_MAX, start = 0, left = 0, i = 0; + while (i <= s.size() && start < s.size()) { + if (required) { + if (i == s.size()) break; + if (--remaining[s[i++]] >= 0) required--; + } else { + if (i - start < min) { + min = i - start; + left = start; + } + if (++remaining[s[start++]] > 0) required++; + } } - if (++remaining[s[start++]] > 0) required++; - } + return min == INT_MAX ? "" : s.substr(left, min); } - return min == INT_MAX ? "" : s.substr(left, min); - } }; diff --git a/Problems/0077.cpp b/Problems/0077.cpp @@ -1,69 +1,69 @@ // Recursive solution class Solution { - vector<int> crnt; - vector<vector<int>> res; - void rec(int s, int n, int k) { - if (s > n + 1) return; - if (!k) { - res.push_back(crnt); - return; - } + vector<int> crnt; + vector<vector<int>> res; + void rec(int s, int n, int k) { + if (s > n + 1) return; + if (!k) { + res.push_back(crnt); + return; + } - crnt.push_back(s); - rec(s + 1, n, k - 1); - crnt.pop_back(); - rec(s + 1, n, k); - } + crnt.push_back(s); + rec(s + 1, n, k - 1); + crnt.pop_back(); + rec(s + 1, n, k); + } -public: - vector<vector<int>> combine(int n, int k) { - rec(1, n, k); - return res; - } + public: + vector<vector<int>> combine(int n, int k) { + rec(1, n, k); + return res; + } }; // Iterative solution class Solution { -public: - vector<vector<int>> combine(int n, int k) { - vector<vector<int>> res; - vector<int> iter; - iter.reserve(k); - for (int mask = (1 << k) - 1; mask < 1 << n; mask++) { - if (__builtin_popcount(mask) != k) continue; + public: + vector<vector<int>> combine(int n, int k) { + vector<vector<int>> res; + vector<int> iter; + iter.reserve(k); + for (int mask = (1 << k) - 1; mask < 1 << n; mask++) { + if (__builtin_popcount(mask) != k) continue; - for (int crnt = mask, idx; crnt; crnt ^= 1 << (idx - 1)) { - idx = __builtin_ffs(crnt); - iter.push_back(idx); - } - res.push_back(iter); - iter.clear(); + for (int crnt = mask, idx; crnt; crnt ^= 1 << (idx - 1)) { + idx = __builtin_ffs(crnt); + iter.push_back(idx); + } + res.push_back(iter); + iter.clear(); + } + return res; } - return res; - } }; // Improved iterative solution with bit twiddling class Solution { - int twiddle(int v) { - int t = v | (v - 1); - int w = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(v) + 1)); - return w; - } + int twiddle(int v) { + int t = v | (v - 1); + int w = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(v) + 1)); + return w; + } -public: - vector<vector<int>> combine(int n, int k) { - vector<vector<int>> res; - vector<int> iter; - iter.reserve(k); - for (int mask = (1 << k) - 1; mask < 1 << n; mask = twiddle(mask)) { - for (int crnt = mask, idx; crnt; crnt ^= 1 << (idx - 1)) { - idx = __builtin_ffs(crnt); - iter.push_back(idx); - } - res.push_back(iter); - iter.clear(); + public: + vector<vector<int>> combine(int n, int k) { + vector<vector<int>> res; + vector<int> iter; + iter.reserve(k); + for (int mask = (1 << k) - 1; mask < 1 << n; mask = twiddle(mask)) { + for (int crnt = mask, idx; crnt; crnt ^= 1 << (idx - 1)) { + idx = __builtin_ffs(crnt); + iter.push_back(idx); + } + res.push_back(iter); + iter.clear(); + } + return res; } - return res; - } }; diff --git a/Problems/0078.cpp b/Problems/0078.cpp @@ -1,15 +1,15 @@ class Solution { -public: - vector<vector<int>> subsets(vector<int> &nums) { - vector<vector<int>> res; + public: + vector<vector<int>> subsets(vector<int> &nums) { + vector<vector<int>> res; - res.push_back({}); - for (int num : nums) { - for (int i = res.size() - 1; i >= 0; i--) { - res.push_back(res[i]); - res.back().push_back(num); - } + res.push_back({}); + for (int num : nums) { + for (int i = res.size() - 1; i >= 0; i--) { + res.push_back(res[i]); + res.back().push_back(num); + } + } + return res; } - return res; - } }; diff --git a/Problems/0079.cpp b/Problems/0079.cpp @@ -1,45 +1,40 @@ class Solution { - typedef vector<vector<char>> Matrix; - typedef vector<vector<bool>> Marked; - const vector<pair<int, int>> offsets = { - { 0, 1}, - { 0, -1}, - { 1, 0}, - {-1, 0} - }; - - int n, m; - int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } - - string word; - bool dfs(const Matrix &mat, Marked &mark, int a, int b, int got) { - if (got == word.size()) return true; - - mark[a][b] = true; - for (auto [oa, ob] : offsets) { - int x = a + oa, y = b + ob; - if (!valid(x, y) || mark[x][y] || mat[x][y] != word[got]) continue; - if (dfs(mat, mark, x, y, got + 1)) return true; + typedef vector<vector<char>> Matrix; + typedef vector<vector<bool>> Marked; + const vector<pair<int, int>> offsets = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + + int n, m; + int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } + + string word; + bool dfs(const Matrix &mat, Marked &mark, int a, int b, int got) { + if (got == word.size()) return true; + + mark[a][b] = true; + for (auto [oa, ob] : offsets) { + int x = a + oa, y = b + ob; + if (!valid(x, y) || mark[x][y] || mat[x][y] != word[got]) continue; + if (dfs(mat, mark, x, y, got + 1)) return true; + } + mark[a][b] = false; + + return false; } - mark[a][b] = false; - return false; - } + public: + bool exist(const Matrix &board, string word) { + n = board.size(), m = board[0].size(); + this->word = word; -public: - bool exist(const Matrix &board, string word) { - n = board.size(), m = board[0].size(); - this->word = word; + Marked visited(n, vector<bool>(m, false)); - Marked visited(n, vector<bool>(m, false)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (board[i][j] != word[0]) continue; + if (dfs(board, visited, i, j, 1)) return true; + } + } - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - if (board[i][j] != word[0]) continue; - if (dfs(board, visited, i, j, 1)) return true; - } + return false; } - - return false; - } }; diff --git a/Problems/0080.cpp b/Problems/0080.cpp @@ -1,15 +1,15 @@ class Solution { -public: - int removeDuplicates(vector<int> &nums) { - int k = 1; - for (int i = 1; i < nums.size(); i++) { - nums[k++] = nums[i]; - if (nums[i] == nums[i - 1]) { - while (++i < nums.size() && nums[i] == nums[k - 2]) - ; - i--; - } + public: + int removeDuplicates(vector<int> &nums) { + int k = 1; + for (int i = 1; i < nums.size(); i++) { + nums[k++] = nums[i]; + if (nums[i] == nums[i - 1]) { + while (++i < nums.size() && nums[i] == nums[k - 2]) + ; + i--; + } + } + return k; } - return k; - } }; diff --git a/Problems/0081.cpp b/Problems/0081.cpp @@ -1,24 +1,24 @@ class Solution { -public: - bool search(const vector<int> &nums, int target) { - int left = 0, right = nums.size() - 1; - while (left <= right) { - int mid = left + (right - left) / 2; - if (nums[mid] == target) return true; - if (nums[mid] == nums[left]) { - left++; - continue; - } + public: + bool search(const vector<int> &nums, int target) { + int left = 0, right = nums.size() - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (nums[mid] == target) return true; + if (nums[mid] == nums[left]) { + left++; + continue; + } - bool pivotArr = nums[left] <= nums[mid]; - bool targetArr = nums[left] <= target; - if ((pivotArr ^ targetArr) ? (pivotArr) : (nums[mid] < target)) { - left = mid + 1; - } else { - right = mid - 1; - } - } + bool pivotArr = nums[left] <= nums[mid]; + bool targetArr = nums[left] <= target; + if ((pivotArr ^ targetArr) ? (pivotArr) : (nums[mid] < target)) { + left = mid + 1; + } else { + right = mid - 1; + } + } - return false; - } + return false; + } }; diff --git a/Problems/0082.cpp b/Problems/0082.cpp @@ -1,17 +1,18 @@ class Solution { -public: - ListNode *deleteDuplicates(ListNode *head) { - ListNode top(-200, head); + public: + ListNode *deleteDuplicates(ListNode *head) { + ListNode top(-200, head); - for (ListNode *p = &top, *c = head; c && c->next; c = c->next) { - if (c->val == c->next->val) { - while (c && c->next && c->val == c->next->val) c = c->next; - p->next = c->next; - if (!c) break; - } else - p = p->next; - } + for (ListNode *p = &top, *c = head; c && c->next; c = c->next) { + if (c->val == c->next->val) { + while (c && c->next && c->val == c->next->val) + c = c->next; + p->next = c->next; + if (!c) break; + } else + p = p->next; + } - return top.next; - } + return top.next; + } }; diff --git a/Problems/0083.cpp b/Problems/0083.cpp @@ -1,12 +1,12 @@ class Solution { -public: - ListNode *deleteDuplicates(ListNode *head) { - if (!head) return nullptr; - for (ListNode *p = head; p->next;) - if (p->val == p->next->val) - p->next = p->next->next; - else - p = p->next; - return head; - } + public: + ListNode *deleteDuplicates(ListNode *head) { + if (!head) return nullptr; + for (ListNode *p = head; p->next;) + if (p->val == p->next->val) + p->next = p->next->next; + else + p = p->next; + return head; + } }; diff --git a/Problems/0084.cpp b/Problems/0084.cpp @@ -1,31 +1,31 @@ class Solution { -public: - int largestRectangleArea(vector<int> &heights) { - int n = heights.size(); - vector<int> left(n), right(n); - stack<int> st; + public: + int largestRectangleArea(vector<int> &heights) { + int n = heights.size(); + vector<int> left(n), right(n); + stack<int> st; - for (int i = 0; i < n; i++) { - left[i] = i; - while (!st.empty() && heights[st.top()] >= heights[i]) { - left[i] = left[st.top()]; - st.pop(); - }; - st.push(i); - } + for (int i = 0; i < n; i++) { + left[i] = i; + while (!st.empty() && heights[st.top()] >= heights[i]) { + left[i] = left[st.top()]; + st.pop(); + }; + st.push(i); + } - for (int i = n - 1; i >= 0; i--) { - right[i] = i; - while (!st.empty() && heights[st.top()] >= heights[i]) { - right[i] = right[st.top()]; - st.pop(); - }; - st.push(i); - } + for (int i = n - 1; i >= 0; i--) { + right[i] = i; + while (!st.empty() && heights[st.top()] >= heights[i]) { + right[i] = right[st.top()]; + st.pop(); + }; + st.push(i); + } - int res = 0; - for (int i = 0; i < n; i++) - res = max(res, (right[i] - left[i] + 1) * heights[i]); - return res; - } + int res = 0; + for (int i = 0; i < n; i++) + res = max(res, (right[i] - left[i] + 1) * heights[i]); + return res; + } }; diff --git a/Problems/0086.cpp b/Problems/0086.cpp @@ -1,18 +1,18 @@ class Solution { -public: - ListNode *partition(ListNode *head, int x) { - ListNode hless, hmore; - ListNode *less = &hless, *more = &hmore; + public: + ListNode *partition(ListNode *head, int x) { + ListNode hless, hmore; + ListNode *less = &hless, *more = &hmore; - for (ListNode *crnt = head; crnt; crnt = crnt->next) { - if (crnt->val < x) - less = less->next = crnt; - else - more = more->next = crnt; - } + for (ListNode *crnt = head; crnt; crnt = crnt->next) { + if (crnt->val < x) + less = less->next = crnt; + else + more = more->next = crnt; + } - less->next = hmore.next; - more->next = nullptr; - return hless.next; - } + less->next = hmore.next; + more->next = nullptr; + return hless.next; + } }; diff --git a/Problems/0087.cpp b/Problems/0087.cpp @@ -1,29 +1,29 @@ class Solution { - unordered_map<string, bool> um; + unordered_map<string, bool> um; -public: - bool isScramble(string s1, string s2) { - if (um.count(s1 + s2)) return um[s1 + s2]; - if (s1.size() != s2.size()) return false; - if (s1 == s2) return true; + public: + bool isScramble(string s1, string s2) { + if (um.count(s1 + s2)) return um[s1 + s2]; + if (s1.size() != s2.size()) return false; + if (s1 == s2) return true; - vector<int> count(128, 0); - int n = s1.size(); - um[s1 + s2] = false; + vector<int> count(128, 0); + int n = s1.size(); + um[s1 + s2] = false; - for (int i = 0; i < n; i++) count[s1[i]]++, count[s2[i]]--; - for (int n : count) - if (n) return false; + for (int i = 0; i < n; i++) + count[s1[i]]++, count[s2[i]]--; + for (int n : count) + if (n) return false; - for (int k = 1; k < n; k++) { - if (isScramble(s1.substr(0, k), s2.substr(0, k)) && - isScramble(s1.substr(k), s2.substr(k)) || - isScramble(s1.substr(0, k), s2.substr(n - k)) && - isScramble(s1.substr(k), s2.substr(0, n - k))) { - um[s1 + s2] = true; - return true; - } + for (int k = 1; k < n; k++) { + if (isScramble(s1.substr(0, k), s2.substr(0, k)) && isScramble(s1.substr(k), s2.substr(k)) || + isScramble(s1.substr(0, k), s2.substr(n - k)) && + isScramble(s1.substr(k), s2.substr(0, n - k))) { + um[s1 + s2] = true; + return true; + } + } + return false; } - return false; - } }; diff --git a/Problems/0088.cpp b/Problems/0088.cpp @@ -1,10 +1,11 @@ class Solution { -public: - void merge(vector<int> &nums1, int m, vector<int> &nums2, int n) { - int i = m - 1, j = n - 1, k = m + n - 1; + public: + void merge(vector<int> &nums1, int m, vector<int> &nums2, int n) { + int i = m - 1, j = n - 1, k = m + n - 1; - while (i >= 0 && j >= 0) - nums1[k--] = nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; - while (j >= 0) nums1[k--] = nums2[j--]; - } + while (i >= 0 && j >= 0) + nums1[k--] = nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; + while (j >= 0) + nums1[k--] = nums2[j--]; + } }; diff --git a/Problems/0090.cpp b/Problems/0090.cpp @@ -1,19 +1,19 @@ class Solution { -public: - vector<vector<int>> subsetsWithDup(vector<int> &nums) { - sort(nums.begin(), nums.end()); - vector<vector<int>> res = {{}, {nums[0]}}; + public: + vector<vector<int>> subsetsWithDup(vector<int> &nums) { + sort(nums.begin(), nums.end()); + vector<vector<int>> res = {{}, {nums[0]}}; - int prev = 1; - for (int i = 1; i < nums.size(); i++) { - int end = nums[i] == nums[i - 1] ? prev : 0; - prev = res.size(); - for (int j = res.size() - 1; j >= end; j--) { - res.push_back(res[j]); - res.back().push_back(nums[i]); - } - } + int prev = 1; + for (int i = 1; i < nums.size(); i++) { + int end = nums[i] == nums[i - 1] ? prev : 0; + prev = res.size(); + for (int j = res.size() - 1; j >= end; j--) { + res.push_back(res[j]); + res.back().push_back(nums[i]); + } + } - return res; - } + return res; + } }; diff --git a/Problems/0091.cpp b/Problems/0091.cpp @@ -1,2 +1 @@ -Formating: Problems/0091.cpp -Formating: Problems/0413.cpp +Formating : Problems / 0091.cpp Formating : Problems / 0413.cpp diff --git a/Problems/0092.cpp b/Problems/0092.cpp @@ -1,20 +1,21 @@ class Solution { -public: - ListNode *reverseBetween(ListNode *head, int left, int right) { - ListNode top; - top.next = head; - ListNode *prev = &top; + public: + ListNode *reverseBetween(ListNode *head, int left, int right) { + ListNode top; + top.next = head; + ListNode *prev = &top; - for (int i = 1; i < left; i++) prev = prev->next; + for (int i = 1; i < left; i++) + prev = prev->next; - ListNode *crnt = prev->next; - for (int i = 0; i < right - left; i++) { - ListNode *tmp = prev->next; - prev->next = crnt->next; - crnt->next = crnt->next->next; - prev->next->next = tmp; - } + ListNode *crnt = prev->next; + for (int i = 0; i < right - left; i++) { + ListNode *tmp = prev->next; + prev->next = crnt->next; + crnt->next = crnt->next->next; + prev->next->next = tmp; + } - return top.next; - } + return top.next; + } }; diff --git a/Problems/0093.cpp b/Problems/0093.cpp @@ -1,42 +1,41 @@ class Solution { - bool valid(const string &s) { - if (s.empty()) return true; - return stoi(s) >= 0 && stoi(s) <= 255; - } + bool valid(const string &s) { + if (s.empty()) return true; + return stoi(s) >= 0 && stoi(s) <= 255; + } -public: - vector<string> restoreIpAddresses(string s) { - int n = s.size(); + public: + vector<string> restoreIpAddresses(string s) { + int n = s.size(); - vector<string> res; - string s1, s2, s3, s4; - bool e4; + vector<string> res; + string s1, s2, s3, s4; + bool e4; - s1 = ""; - for (int i = 0; i < n; i++) { - s1 += s[i], s2 = ""; - if (!valid(s1)) break; - for (int j = i + 1; j < n; j++) { - s2 += s[j], s3 = ""; - if (!valid(s2)) break; - for (int k = j + 1; k < n; k++) { - s3 += s[k], s4 = ""; - if (!valid(s3)) break; - for (int l = k + 1; l < n; l++) { - s4 += s[l], e4 = false; - if (!valid(s4) || (s4.size() >= 2 && s4.front() == '0')) { - e4 = true; - break; + s1 = ""; + for (int i = 0; i < n; i++) { + s1 += s[i], s2 = ""; + if (!valid(s1)) break; + for (int j = i + 1; j < n; j++) { + s2 += s[j], s3 = ""; + if (!valid(s2)) break; + for (int k = j + 1; k < n; k++) { + s3 += s[k], s4 = ""; + if (!valid(s3)) break; + for (int l = k + 1; l < n; l++) { + s4 += s[l], e4 = false; + if (!valid(s4) || (s4.size() >= 2 && s4.front() == '0')) { + e4 = true; + break; + } + } + if (!e4 && !s4.empty()) res.push_back(s1 + "." + s2 + "." + s3 + "." + s4); + if (s3.front() == '0') break; + } + if (s2.front() == '0') break; } - } - if (!e4 && !s4.empty()) - res.push_back(s1 + "." + s2 + "." + s3 + "." + s4); - if (s3.front() == '0') break; + if (s1.front() == '0') break; } - if (s2.front() == '0') break; - } - if (s1.front() == '0') break; + return res; } - return res; - } }; diff --git a/Problems/0094.cpp b/Problems/0094.cpp @@ -1,24 +1,24 @@ class Solution { -public: - vector<int> inorderTraversal(TreeNode *root) { - vector<int> res; - stack<TreeNode *> st; + public: + vector<int> inorderTraversal(TreeNode *root) { + vector<int> res; + stack<TreeNode *> st; - while (true) { - while (root) { - st.push(root); - root = root->left; - } + while (true) { + while (root) { + st.push(root); + root = root->left; + } + + if (!st.empty()) { + root = st.top(); + st.pop(); + res.push_back(root->val); + root = root->right; + } else + return res; + } - if (!st.empty()) { - root = st.top(); - st.pop(); - res.push_back(root->val); - root = root->right; - } else return res; } - - return res; - } }; diff --git a/Problems/0095.cpp b/Problems/0095.cpp @@ -1,21 +1,21 @@ class Solution { - vector<TreeNode *> dp[10][10]; + vector<TreeNode *> dp[10][10]; - vector<TreeNode *> rec(int n, int left, int right) { - vector<TreeNode *> &res = dp[left][right]; - if (!res.empty()) return res; + vector<TreeNode *> rec(int n, int left, int right) { + vector<TreeNode *> &res = dp[left][right]; + if (!res.empty()) return res; - for (int i = left; i <= right; i++) { - for (const auto &l : rec(n, left, i - 1)) { - for (const auto &r : rec(n, i + 1, right)) { - res.push_back(new TreeNode(i, l, r)); + for (int i = left; i <= right; i++) { + for (const auto &l : rec(n, left, i - 1)) { + for (const auto &r : rec(n, i + 1, right)) { + res.push_back(new TreeNode(i, l, r)); + } + } } - } + if (res.empty()) return {nullptr}; + return res; } - if (res.empty()) return {nullptr}; - return res; - } -public: - vector<TreeNode *> generateTrees(int n) { return rec(n, 1, n); } + public: + vector<TreeNode *> generateTrees(int n) { return rec(n, 1, n); } }; diff --git a/Problems/0096.cpp b/Problems/0096.cpp @@ -1,11 +1,12 @@ class Solution { -public: - int numTrees(int n) { - vector<int> dp(n + 1); - dp[0] = dp[1] = 1; + public: + int numTrees(int n) { + vector<int> dp(n + 1); + dp[0] = dp[1] = 1; - for (int i = 2; i <= n; i++) - for (int j = 1; j <= i; j++) dp[i] += dp[j - 1] * dp[i - j]; - return dp.back(); - } + for (int i = 2; i <= n; i++) + for (int j = 1; j <= i; j++) + dp[i] += dp[j - 1] * dp[i - j]; + return dp.back(); + } }; diff --git a/Problems/0097.cpp b/Problems/0097.cpp @@ -1,23 +1,20 @@ class Solution { - short int dp[101][101]; - bool rec(const string &s1, const string &s2, const string &s3, int i = 0, - int j = 0, int k = 0) { - if (k == s3.size()) return true; - if (dp[i][j] != -1) return dp[i][j]; + short int dp[101][101]; + bool rec(const string &s1, const string &s2, const string &s3, int i = 0, int j = 0, int k = 0) { + if (k == s3.size()) return true; + if (dp[i][j] != -1) return dp[i][j]; - if (i != s1.size() && s1[i] == s3[k] && rec(s1, s2, s3, i + 1, j, k + 1)) - return dp[i][j] = true; + if (i != s1.size() && s1[i] == s3[k] && rec(s1, s2, s3, i + 1, j, k + 1)) return dp[i][j] = true; - if (j != s2.size() && s2[j] == s3[k] && rec(s1, s2, s3, i, j + 1, k + 1)) - return dp[i][j] = true; + if (j != s2.size() && s2[j] == s3[k] && rec(s1, s2, s3, i, j + 1, k + 1)) return dp[i][j] = true; - return dp[i][j] = false; - } + return dp[i][j] = false; + } -public: - Solution() { memset(dp, 0xFF, sizeof(dp)); } - bool isInterleave(const string &s1, const string &s2, const string &s3) { - if (s1.size() + s2.size() != s3.size()) return false; - return rec(s1, s2, s3); - } + public: + Solution() { memset(dp, 0xFF, sizeof(dp)); } + bool isInterleave(const string &s1, const string &s2, const string &s3) { + if (s1.size() + s2.size() != s3.size()) return false; + return rec(s1, s2, s3); + } }; diff --git a/Problems/0098.cpp b/Problems/0098.cpp @@ -1,20 +1,20 @@ class Solution { -public: - bool isValidBST(TreeNode *root) { - stack<TreeNode *> st; - long prev = LONG_MIN; - while (true) { - while (root) { - st.push(root); - root = root->left; - } - if (st.empty()) break; - root = st.top(); - st.pop(); - if (root->val <= prev) return false; - prev = root->val; - root = root->right; + public: + bool isValidBST(TreeNode *root) { + stack<TreeNode *> st; + long prev = LONG_MIN; + while (true) { + while (root) { + st.push(root); + root = root->left; + } + if (st.empty()) break; + root = st.top(); + st.pop(); + if (root->val <= prev) return false; + prev = root->val; + root = root->right; + } + return true; } - return true; - } }; diff --git a/Problems/0099.cpp b/Problems/0099.cpp @@ -1,23 +1,22 @@ class Solution { -public: - void recoverTree(TreeNode *root) { - stack<TreeNode *> st; - TreeNode *head = root, *prev = new TreeNode(INT_MIN), *l1 = nullptr, - *l2 = nullptr; - while (true) { - while (root) { - st.push(root); - root = root->left; - } - if (st.empty()) break; - root = st.top(), st.pop(); - if (root->val < prev->val) { - if (!l1) l1 = prev; - l2 = root; - } - prev = root; - root = root->right; + public: + void recoverTree(TreeNode *root) { + stack<TreeNode *> st; + TreeNode *head = root, *prev = new TreeNode(INT_MIN), *l1 = nullptr, *l2 = nullptr; + while (true) { + while (root) { + st.push(root); + root = root->left; + } + if (st.empty()) break; + root = st.top(), st.pop(); + if (root->val < prev->val) { + if (!l1) l1 = prev; + l2 = root; + } + prev = root; + root = root->right; + } + swap(l1->val, l2->val); } - swap(l1->val, l2->val); - } }; diff --git a/Problems/0100.cpp b/Problems/0100.cpp @@ -1,38 +1,37 @@ // Recursive solution class Solution { -public: - bool isSameTree(TreeNode *p, TreeNode *q) { - if (!p && !q) return true; - if (!p || !q) return false; - return p->val == q->val && isSameTree(p->left, q->left) && - isSameTree(p->right, q->right); - } + public: + bool isSameTree(TreeNode *p, TreeNode *q) { + if (!p && !q) return true; + if (!p || !q) return false; + return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } }; // Iterative solution class Solution { -public: - bool isSameTree(TreeNode *p, TreeNode *q) { - if (!p && !q) return true; - if (!p || !q) return false; - queue<pair<TreeNode *, TreeNode *>> qu; - qu.push({p, q}); - while (!qu.empty()) { - auto [p, q] = qu.front(); - qu.pop(); - if (p->val != q->val) return false; + public: + bool isSameTree(TreeNode *p, TreeNode *q) { + if (!p && !q) return true; + if (!p || !q) return false; + queue<pair<TreeNode *, TreeNode *>> qu; + qu.push({p, q}); + while (!qu.empty()) { + auto [p, q] = qu.front(); + qu.pop(); + if (p->val != q->val) return false; - if (p->left && q->left) - qu.push({p->left, q->left}); - else if (p->left || q->left) - return false; + if (p->left && q->left) + qu.push({p->left, q->left}); + else if (p->left || q->left) + return false; - if (p->right && q->right) - qu.push({p->right, q->right}); - else if (p->right || q->right) - return false; - } + if (p->right && q->right) + qu.push({p->right, q->right}); + else if (p->right || q->right) + return false; + } - return true; - } + return true; + } }; diff --git a/Problems/0101.cpp b/Problems/0101.cpp @@ -1,33 +1,33 @@ class Solution { - string preorder(TreeNode *root, bool left) { - if (!root) return ""; + string preorder(TreeNode *root, bool left) { + if (!root) return ""; - string res; - stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (!root) { - res += "-"; - continue; - } - res += root->val; - if (left) { - st.push(root->right); - st.push(root->left); - } else { - st.push(root->left); - st.push(root->right); - } + string res; + stack<TreeNode *> st; + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (!root) { + res += "-"; + continue; + } + res += root->val; + if (left) { + st.push(root->right); + st.push(root->left); + } else { + st.push(root->left); + st.push(root->right); + } + } + return res; } - return res; - } -public: - bool isSymmetric(TreeNode *root) { - if (!root) return false; + public: + bool isSymmetric(TreeNode *root) { + if (!root) return false; - return preorder(root->left, true) == preorder(root->right, false); - } + return preorder(root->left, true) == preorder(root->right, false); + } }; diff --git a/Problems/0102.cpp b/Problems/0102.cpp @@ -1,22 +1,22 @@ class Solution { -public: - vector<vector<int>> levelOrder(TreeNode *root) { - if (!root) return {}; + public: + vector<vector<int>> levelOrder(TreeNode *root) { + if (!root) return {}; - vector<vector<int>> res; - queue<TreeNode *> q; + vector<vector<int>> res; + queue<TreeNode *> q; - q.push(root); - for (int lvl = 0; !q.empty(); lvl++) { - res.push_back(vector<int>()); - for (int t = q.size(); t > 0; t--) { - TreeNode *root = q.front(); - q.pop(); - res[lvl].push_back(root->val); - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } + q.push(root); + for (int lvl = 0; !q.empty(); lvl++) { + res.push_back(vector<int>()); + for (int t = q.size(); t > 0; t--) { + TreeNode *root = q.front(); + q.pop(); + res[lvl].push_back(root->val); + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + } + return res; } - return res; - } }; diff --git a/Problems/0103.cpp b/Problems/0103.cpp @@ -1,55 +1,55 @@ class Solution { -public: - vector<vector<int>> zigzagLevelOrder(TreeNode *root) { - if (!root) return {}; + public: + vector<vector<int>> zigzagLevelOrder(TreeNode *root) { + if (!root) return {}; - vector<vector<int>> res; - queue<TreeNode *> q; - bool right = true; + vector<vector<int>> res; + queue<TreeNode *> q; + bool right = true; - q.push(root); - for (int lvl = 0; !q.empty(); lvl++) { - res.push_back(vector<int>()); - for (int t = q.size(); t > 0; t--) { - TreeNode *root = q.front(); - q.pop(); - res[lvl].push_back(root->val); + q.push(root); + for (int lvl = 0; !q.empty(); lvl++) { + res.push_back(vector<int>()); + for (int t = q.size(); t > 0; t--) { + TreeNode *root = q.front(); + q.pop(); + res[lvl].push_back(root->val); - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } - if (!right) reverse(res[lvl].begin(), res[lvl].end()); - right = !right; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + if (!right) reverse(res[lvl].begin(), res[lvl].end()); + right = !right; + } + return res; } - return res; - } - vector<vector<int>> zigzagLevelOrder(TreeNode *root) { - if (!root) return {}; + vector<vector<int>> zigzagLevelOrder(TreeNode *root) { + if (!root) return {}; - vector<vector<int>> res; - deque<TreeNode *> d; - bool right = true; + vector<vector<int>> res; + deque<TreeNode *> d; + bool right = true; - d.push_front(root); - for (int lvl = 0; !d.empty(); lvl++, right = !right) { - res.push_back(vector<int>()); - for (int t = d.size(); t > 0; t--) { - TreeNode *root; - if (right) { - root = d.front(); - d.pop_front(); - if (root->left) d.push_back(root->left); - if (root->right) d.push_back(root->right); - } else { - root = d.back(); - d.pop_back(); - if (root->right) d.push_front(root->right); - if (root->left) d.push_front(root->left); + d.push_front(root); + for (int lvl = 0; !d.empty(); lvl++, right = !right) { + res.push_back(vector<int>()); + for (int t = d.size(); t > 0; t--) { + TreeNode *root; + if (right) { + root = d.front(); + d.pop_front(); + if (root->left) d.push_back(root->left); + if (root->right) d.push_back(root->right); + } else { + root = d.back(); + d.pop_back(); + if (root->right) d.push_front(root->right); + if (root->left) d.push_front(root->left); + } + res[lvl].push_back(root->val); + } } - res[lvl].push_back(root->val); - } + return res; } - return res; - } }; diff --git a/Problems/0104.cpp b/Problems/0104.cpp @@ -1,19 +1,19 @@ class Solution { -public: - int maxDepth(TreeNode *root) { - if (!root) return 0; + public: + int maxDepth(TreeNode *root) { + if (!root) return 0; - int lvl; - queue<TreeNode *> q; - q.push(root); - for (lvl = 0; !q.empty(); lvl++) { - for (int t = q.size(); t > 0; t--) { - TreeNode *root = q.front(); - q.pop(); - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } + int lvl; + queue<TreeNode *> q; + q.push(root); + for (lvl = 0; !q.empty(); lvl++) { + for (int t = q.size(); t > 0; t--) { + TreeNode *root = q.front(); + q.pop(); + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + } + return lvl; } - return lvl; - } }; diff --git a/Problems/0105.cpp b/Problems/0105.cpp @@ -1,31 +1,31 @@ class Solution { - typedef vector<int>::iterator vii; - struct Record { - TreeNode **fill = nullptr; - vii start, end; - Record(TreeNode **f, vii s, vii e) : fill(f), start(s), end(e) {} - }; + typedef vector<int>::iterator vii; + struct Record { + TreeNode **fill = nullptr; + vii start, end; + Record(TreeNode **f, vii s, vii e) : fill(f), start(s), end(e) {} + }; -public: - TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { - stack<Record> st; - TreeNode head; - int pre = 0; + public: + TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { + stack<Record> st; + TreeNode head; + int pre = 0; - st.push({&head.right, inorder.begin(), inorder.end()}); - while (!st.empty()) { - Record r = st.top(); - st.pop(); - while (r.start < r.end) { - vii mid = find(r.start, r.end, preorder[pre]); - if (mid == r.end) break; - TreeNode *n = *r.fill = new TreeNode(preorder[pre++]); - st.push({&n->right, next(mid), r.end}); - r.end = mid; - r.fill = &n->left; - } - } + st.push({&head.right, inorder.begin(), inorder.end()}); + while (!st.empty()) { + Record r = st.top(); + st.pop(); + while (r.start < r.end) { + vii mid = find(r.start, r.end, preorder[pre]); + if (mid == r.end) break; + TreeNode *n = *r.fill = new TreeNode(preorder[pre++]); + st.push({&n->right, next(mid), r.end}); + r.end = mid; + r.fill = &n->left; + } + } - return head.right; - } + return head.right; + } }; diff --git a/Problems/0106.cpp b/Problems/0106.cpp @@ -1,32 +1,33 @@ class Solution { - class Record { - public: - int low, high; - TreeNode **field; - Record(int l, int h, TreeNode **f) : low(l), high(h), field(f) {} - }; + class Record { + public: + int low, high; + TreeNode **field; + Record(int l, int h, TreeNode **f) : low(l), high(h), field(f) {} + }; -public: - TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { - unordered_map<int, int> um; - for (int i = 0; i < inorder.size(); i++) um[inorder[i]] = i; + public: + TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { + unordered_map<int, int> um; + for (int i = 0; i < inorder.size(); i++) + um[inorder[i]] = i; - int crnt = postorder.size() - 1; - TreeNode head, *nw; - stack<Record> st; + int crnt = postorder.size() - 1; + TreeNode head, *nw; + stack<Record> st; - st.push({0, (int)inorder.size(), &head.right}); - while (!st.empty()) { - Record r = st.top(); - st.pop(); - while (r.low < r.high) { - int pos = um[postorder[crnt]]; - nw = *r.field = new TreeNode(postorder[crnt--]); - st.push({r.low, pos, &nw->left}); - r.low = pos + 1; - r.field = &nw->right; - } + st.push({0, (int)inorder.size(), &head.right}); + while (!st.empty()) { + Record r = st.top(); + st.pop(); + while (r.low < r.high) { + int pos = um[postorder[crnt]]; + nw = *r.field = new TreeNode(postorder[crnt--]); + st.push({r.low, pos, &nw->left}); + r.low = pos + 1; + r.field = &nw->right; + } + } + return head.right; } - return head.right; - } }; diff --git a/Problems/0107.cpp b/Problems/0107.cpp @@ -1,23 +1,23 @@ class Solution { -public: - vector<vector<int>> levelOrderBottom(TreeNode *root) { - if (!root) return {}; + public: + vector<vector<int>> levelOrderBottom(TreeNode *root) { + if (!root) return {}; - vector<vector<int>> res; - queue<TreeNode *> q; + vector<vector<int>> res; + queue<TreeNode *> q; - q.push(root); - for (int lvl = 0; !q.empty(); lvl++) { - res.push_back(vector<int>()); - for (int t = q.size(); t > 0; t--) { - TreeNode *root = q.front(); - q.pop(); - res[lvl].push_back(root->val); - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } + q.push(root); + for (int lvl = 0; !q.empty(); lvl++) { + res.push_back(vector<int>()); + for (int t = q.size(); t > 0; t--) { + TreeNode *root = q.front(); + q.pop(); + res[lvl].push_back(root->val); + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + } + reverse(res.begin(), res.end()); + return res; } - reverse(res.begin(), res.end()); - return res; - } }; diff --git a/Problems/0108.cpp b/Problems/0108.cpp @@ -1,27 +1,25 @@ class Solution { - struct record { - TreeNode *root; - int low, high; - record(TreeNode *root, int low, int high) - : root(root), low(low), high(high) {} - }; + struct record { + TreeNode *root; + int low, high; + record(TreeNode *root, int low, int high) : root(root), low(low), high(high) {} + }; -public: - TreeNode *sortedArrayToBST(vector<int> &nums) { - stack<record> st; - TreeNode *head = new TreeNode(INT_MIN), *t; - st.push({head, 0, (int)nums.size() - 1}); - while (!st.empty()) { - record r = st.top(); - st.pop(); - while (r.low <= r.high) { - int mid = r.low + (r.high - r.low) / 2; - (nums[mid] >= r.root->val ? r.root->right : r.root->left) = t = - new TreeNode(nums[mid]); - st.push({r.root = t, mid + 1, r.high}); - r.high = mid - 1; - } + public: + TreeNode *sortedArrayToBST(vector<int> &nums) { + stack<record> st; + TreeNode *head = new TreeNode(INT_MIN), *t; + st.push({head, 0, (int)nums.size() - 1}); + while (!st.empty()) { + record r = st.top(); + st.pop(); + while (r.low <= r.high) { + int mid = r.low + (r.high - r.low) / 2; + (nums[mid] >= r.root->val ? r.root->right : r.root->left) = t = new TreeNode(nums[mid]); + st.push({r.root = t, mid + 1, r.high}); + r.high = mid - 1; + } + } + return head->right; } - return head->right; - } }; diff --git a/Problems/0109.cpp b/Problems/0109.cpp @@ -1,36 +1,35 @@ class Solution { - struct record { - TreeNode *root; - ListNode *low, *high; - record(TreeNode *root, ListNode *low = nullptr, ListNode *high = nullptr) - : root(root), low(low), high(high) {} - }; - ListNode *get_mid(ListNode *list, ListNode *end) { - ListNode *slow, *fast; - slow = fast = list; - while (fast != end && fast->next != end) { - fast = fast->next->next; - slow = slow->next; + struct record { + TreeNode *root; + ListNode *low, *high; + record(TreeNode *root, ListNode *low = nullptr, ListNode *high = nullptr) + : root(root), low(low), high(high) {} + }; + ListNode *get_mid(ListNode *list, ListNode *end) { + ListNode *slow, *fast; + slow = fast = list; + while (fast != end && fast->next != end) { + fast = fast->next->next; + slow = slow->next; + } + return slow; } - return slow; - } -public: - TreeNode *sortedListToBST(ListNode *head) { - stack<record> st; - TreeNode *tree = new TreeNode(INT_MIN), *t; - st.push({tree, head, nullptr}); - while (!st.empty()) { - record r = st.top(); - st.pop(); - while (r.low != r.high) { - ListNode *mid = get_mid(r.low, r.high); - (mid->val >= r.root->val ? r.root->right : r.root->left) = t = - new TreeNode(mid->val); - st.push({r.root = t, mid->next, r.high}); - r.high = mid; - } + public: + TreeNode *sortedListToBST(ListNode *head) { + stack<record> st; + TreeNode *tree = new TreeNode(INT_MIN), *t; + st.push({tree, head, nullptr}); + while (!st.empty()) { + record r = st.top(); + st.pop(); + while (r.low != r.high) { + ListNode *mid = get_mid(r.low, r.high); + (mid->val >= r.root->val ? r.root->right : r.root->left) = t = new TreeNode(mid->val); + st.push({r.root = t, mid->next, r.high}); + r.high = mid; + } + } + return tree->right; } - return tree->right; - } }; diff --git a/Problems/0110.cpp b/Problems/0110.cpp @@ -1,23 +1,23 @@ class Solution { -public: - bool isBalanced(TreeNode *root) { - if (!root) return true; - stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - if (root == nullptr) { - st.pop(), root = st.top(), st.pop(); - int left = root->left ? root->left->val : 0; - int right = root->right ? root->right->val : 0; - if (abs(right - left) > 1) return false; - root->val = max(left, right) + 1; - continue; - } - st.push(nullptr); - if (root->left) st.push(root->left); - if (root->right) st.push(root->right); + public: + bool isBalanced(TreeNode *root) { + if (!root) return true; + stack<TreeNode *> st; + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + if (root == nullptr) { + st.pop(), root = st.top(), st.pop(); + int left = root->left ? root->left->val : 0; + int right = root->right ? root->right->val : 0; + if (abs(right - left) > 1) return false; + root->val = max(left, right) + 1; + continue; + } + st.push(nullptr); + if (root->left) st.push(root->left); + if (root->right) st.push(root->right); + } + return true; } - return true; - } }; diff --git a/Problems/0111.cpp b/Problems/0111.cpp @@ -1,20 +1,20 @@ class Solution { -public: - int minDepth(TreeNode *root) { - if (!root) return 0; + public: + int minDepth(TreeNode *root) { + if (!root) return 0; - queue<TreeNode *> q; + queue<TreeNode *> q; - q.push(root); - for (int lvl = 1; !q.empty(); lvl++) { - for (int t = q.size(); t > 0; t--) { - TreeNode *root = q.front(); - q.pop(); - if (!root->left && !root->right) return lvl; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } + q.push(root); + for (int lvl = 1; !q.empty(); lvl++) { + for (int t = q.size(); t > 0; t--) { + TreeNode *root = q.front(); + q.pop(); + if (!root->left && !root->right) return lvl; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + } + return -1; } - return -1; - } }; diff --git a/Problems/0112.cpp b/Problems/0112.cpp @@ -1,20 +1,20 @@ class Solution { -public: - bool hasPathSum(TreeNode *root, int targetSum) { - if (!root) return false; + public: + bool hasPathSum(TreeNode *root, int targetSum) { + if (!root) return false; - stack<pair<TreeNode *, int>> st; - st.push(make_pair(root, 0)); - while (!st.empty()) { - TreeNode *root = st.top().first; - int val = st.top().second + root->val; - st.pop(); + stack<pair<TreeNode *, int>> st; + st.push(make_pair(root, 0)); + while (!st.empty()) { + TreeNode *root = st.top().first; + int val = st.top().second + root->val; + st.pop(); - if (val == targetSum && !root->left && !root->right) return true; + if (val == targetSum && !root->left && !root->right) return true; - if (root->left) st.push(make_pair(root->left, val)); - if (root->right) st.push(make_pair(root->right, val)); + if (root->left) st.push(make_pair(root->left, val)); + if (root->right) st.push(make_pair(root->right, val)); + } + return false; } - return false; - } }; diff --git a/Problems/0113.cpp b/Problems/0113.cpp @@ -1,26 +1,26 @@ class Solution { -public: - vector<vector<int>> pathSum(TreeNode *root, int targetSum) { - if (!root) return {}; - stack<pair<TreeNode *, int>> st; - vector<vector<int>> res; - vector<int> path; - st.push({root, 0}); - while (!st.empty()) { - auto [root, sum] = st.top(); - if (sum == INT_MIN) { - st.pop(); - path.pop_back(); - continue; - } - sum += root->val; - st.top().second = INT_MIN; - path.push_back(root->val); + public: + vector<vector<int>> pathSum(TreeNode *root, int targetSum) { + if (!root) return {}; + stack<pair<TreeNode *, int>> st; + vector<vector<int>> res; + vector<int> path; + st.push({root, 0}); + while (!st.empty()) { + auto [root, sum] = st.top(); + if (sum == INT_MIN) { + st.pop(); + path.pop_back(); + continue; + } + sum += root->val; + st.top().second = INT_MIN; + path.push_back(root->val); - if (!root->left && !root->right && sum == targetSum) res.push_back(path); - if (root->left) st.push({root->left, sum}); - if (root->right) st.push({root->right, sum}); + if (!root->left && !root->right && sum == targetSum) res.push_back(path); + if (root->left) st.push({root->left, sum}); + if (root->right) st.push({root->right, sum}); + } + return res; } - return res; - } }; diff --git a/Problems/0114.cpp b/Problems/0114.cpp @@ -1,21 +1,21 @@ class Solution { -public: - void flatten(TreeNode *root) { - TreeNode *crnt = new TreeNode(-1); - stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - crnt->right = root; - while (root) { - crnt = root; - if (root->right) st.push(root->right); + public: + void flatten(TreeNode *root) { + TreeNode *crnt = new TreeNode(-1); + stack<TreeNode *> st; + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + crnt->right = root; + while (root) { + crnt = root; + if (root->right) st.push(root->right); - root->right = root->left; - root->left = nullptr; - root = root->right; - } + root->right = root->left; + root->left = nullptr; + root = root->right; + } + } } - } }; diff --git a/Problems/0116.cpp b/Problems/0116.cpp @@ -1,21 +1,21 @@ class Solution { -public: - Node *connect(Node *root) { - if (!root) return {}; + public: + Node *connect(Node *root) { + if (!root) return {}; - queue<Node *> q; - q.push(root); - for (int lvl = 0; !q.empty(); lvl++) { - Node *prev = nullptr; - for (int t = q.size(); t > 0; t--) { - Node *root = q.front(); - q.pop(); - root->next = prev; - prev = root; - if (root->right) q.push(root->right); - if (root->left) q.push(root->left); - } + queue<Node *> q; + q.push(root); + for (int lvl = 0; !q.empty(); lvl++) { + Node *prev = nullptr; + for (int t = q.size(); t > 0; t--) { + Node *root = q.front(); + q.pop(); + root->next = prev; + prev = root; + if (root->right) q.push(root->right); + if (root->left) q.push(root->left); + } + } + return root; } - return root; - } }; diff --git a/Problems/0117.cpp b/Problems/0117.cpp @@ -1,21 +1,21 @@ class Solution { -public: - Node *connect(Node *root) { - if (!root) return {}; + public: + Node *connect(Node *root) { + if (!root) return {}; - queue<Node *> q; - q.push(root); - for (int lvl = 0; !q.empty(); lvl++) { - Node *prev = nullptr; - for (int t = q.size(); t > 0; t--) { - Node *root = q.front(); - q.pop(); - root->next = prev; - prev = root; - if (root->right) q.push(root->right); - if (root->left) q.push(root->left); - } + queue<Node *> q; + q.push(root); + for (int lvl = 0; !q.empty(); lvl++) { + Node *prev = nullptr; + for (int t = q.size(); t > 0; t--) { + Node *root = q.front(); + q.pop(); + root->next = prev; + prev = root; + if (root->right) q.push(root->right); + if (root->left) q.push(root->left); + } + } + return root; } - return root; - } }; diff --git a/Problems/0118.cpp b/Problems/0118.cpp @@ -1,16 +1,16 @@ class Solution { -public: - vector<vector<int>> generate(int numRows) { - vector<vector<int>> res; + public: + vector<vector<int>> generate(int numRows) { + vector<vector<int>> res; - for (int i = 0; i < numRows; i++) { - vector<int> row; - row.push_back(1); - for (int j = 1; j < i; j++) - row.push_back(res[i - 1][j - 1] + res[i - 1][j]); - if (i != 0) row.push_back(1); - res.push_back(row); + for (int i = 0; i < numRows; i++) { + vector<int> row; + row.push_back(1); + for (int j = 1; j < i; j++) + row.push_back(res[i - 1][j - 1] + res[i - 1][j]); + if (i != 0) row.push_back(1); + res.push_back(row); + } + return res; } - return res; - } }; diff --git a/Problems/0119.cpp b/Problems/0119.cpp @@ -1,16 +1,16 @@ class Solution { -public: - vector<int> getRow(int rowIndex) { - vector<vector<int>> res; + public: + vector<int> getRow(int rowIndex) { + vector<vector<int>> res; - for (int i = 0; i <= rowIndex; i++) { - vector<int> row; - row.push_back(1); - for (int j = 1; j < i; j++) - row.push_back(res[i - 1][j - 1] + res[i - 1][j]); - if (i != 0) row.push_back(1); - res.push_back(row); + for (int i = 0; i <= rowIndex; i++) { + vector<int> row; + row.push_back(1); + for (int j = 1; j < i; j++) + row.push_back(res[i - 1][j - 1] + res[i - 1][j]); + if (i != 0) row.push_back(1); + res.push_back(row); + } + return res[rowIndex]; } - return res[rowIndex]; - } }; diff --git a/Problems/0120.cpp b/Problems/0120.cpp @@ -1,16 +1,17 @@ class Solution { -public: - int minimumTotal(vector<vector<int>> &triangle) { - int h = triangle.size(); + public: + int minimumTotal(vector<vector<int>> &triangle) { + int h = triangle.size(); - for (int i = 0; i < h - 1; i++) { - vector<int> vec(i + 2, INT_MAX); - for (int j = 0; j <= i; j++) { - vec[j] = min(vec[j], triangle[i][j]); - vec[j + 1] = min(vec[j + 1], triangle[i][j]); - } - for (int j = 0; j <= i + 1; j++) triangle[i + 1][j] += vec[j]; + for (int i = 0; i < h - 1; i++) { + vector<int> vec(i + 2, INT_MAX); + for (int j = 0; j <= i; j++) { + vec[j] = min(vec[j], triangle[i][j]); + vec[j + 1] = min(vec[j + 1], triangle[i][j]); + } + for (int j = 0; j <= i + 1; j++) + triangle[i + 1][j] += vec[j]; + } + return *min_element(triangle.back().begin(), triangle.back().end()); } - return *min_element(triangle.back().begin(), triangle.back().end()); - } }; diff --git a/Problems/0121.cpp b/Problems/0121.cpp @@ -1,12 +1,12 @@ class Solution { -public: - int maxProfit(vector<int> &prices) { - int mini = prices[0]; - int profit = 0; - for (int i = 1; i < prices.size(); i++) { - profit = max(prices[i] - mini, profit); - mini = min(prices[i], mini); + public: + int maxProfit(vector<int> &prices) { + int mini = prices[0]; + int profit = 0; + for (int i = 1; i < prices.size(); i++) { + profit = max(prices[i] - mini, profit); + mini = min(prices[i], mini); + } + return profit; } - return profit; - } }; diff --git a/Problems/0122.cpp b/Problems/0122.cpp @@ -1,13 +1,14 @@ class Solution { -public: - int maxProfit(vector<int> &prices) { - int profit = 0; - prices.push_back(INT_MIN); - for (int i = 0, j = 0; i < prices.size() - 1; i++) { - while (prices[j] < prices[j + 1]) j++; - profit += prices[j] - prices[i]; - i = j++; + public: + int maxProfit(vector<int> &prices) { + int profit = 0; + prices.push_back(INT_MIN); + for (int i = 0, j = 0; i < prices.size() - 1; i++) { + while (prices[j] < prices[j + 1]) + j++; + profit += prices[j] - prices[i]; + i = j++; + } + return profit; } - return profit; - } }; diff --git a/Problems/0124.cpp b/Problems/0124.cpp @@ -1,41 +1,41 @@ class Solution { -public: - int maxPathSum(TreeNode *root) { - if (!root) return 0; - int res = INT_MIN; + public: + int maxPathSum(TreeNode *root) { + if (!root) return 0; + int res = INT_MIN; - unordered_set<TreeNode *> us; - stack<TreeNode *> st; - while (root) { - st.push(root); - root = root->left; - } - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - - if (us.find(root) == us.end()) { - st.push(root); - us.insert(root); - root = root->right; + unordered_set<TreeNode *> us; + stack<TreeNode *> st; while (root) { - st.push(root); - root = root->left; + st.push(root); + root = root->left; + } + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + + if (us.find(root) == us.end()) { + st.push(root); + us.insert(root); + root = root->right; + while (root) { + st.push(root); + root = root->left; + } + } else { + int opt = 0, sum = 0; + if (root->left) { + opt = max(opt, root->left->val), sum += root->left->val; + }; + if (root->right) { + opt = max(opt, root->right->val), sum += root->right->val; + }; + res = max(res, root->val + sum); + root->val = max(root->val, root->val + opt); + res = max(res, root->val); + continue; + } } - } else { - int opt = 0, sum = 0; - if (root->left) { - opt = max(opt, root->left->val), sum += root->left->val; - }; - if (root->right) { - opt = max(opt, root->right->val), sum += root->right->val; - }; - res = max(res, root->val + sum); - root->val = max(root->val, root->val + opt); - res = max(res, root->val); - continue; - } + return res; } - return res; - } }; diff --git a/Problems/0125.cpp b/Problems/0125.cpp @@ -1,17 +1,17 @@ class Solution { -public: - bool isPalindrome(string s) { - int i = 0, j = s.size() - 1; - while (i < j) { - if (!isalnum(s[j])) - j--; - else if (!isalnum(s[i])) - i++; - else if (tolower(s[i]) != tolower(s[j])) - return false; - else - i++, j--; + public: + bool isPalindrome(string s) { + int i = 0, j = s.size() - 1; + while (i < j) { + if (!isalnum(s[j])) + j--; + else if (!isalnum(s[i])) + i++; + else if (tolower(s[i]) != tolower(s[j])) + return false; + else + i++, j--; + } + return true; } - return true; - } }; diff --git a/Problems/0128.cpp b/Problems/0128.cpp @@ -1,19 +1,20 @@ class Solution { -public: - int longestConsecutive(vector<int> &nums) { - if (!nums.size()) return 0; + public: + int longestConsecutive(vector<int> &nums) { + if (!nums.size()) return 0; - unordered_set<int> us(nums.begin(), nums.end()); - int res = 0; + unordered_set<int> us(nums.begin(), nums.end()); + int res = 0; - for (int num : us) { - if (!us.count(num - 1)) { - int crnt = num; - while (us.count(crnt + 1)) crnt += 1; - res = max(longestStreak, crnt - num); - } - } + for (int num : us) { + if (!us.count(num - 1)) { + int crnt = num; + while (us.count(crnt + 1)) + crnt += 1; + res = max(longestStreak, crnt - num); + } + } - return res + 1; - } + return res + 1; + } }; diff --git a/Problems/0129.cpp b/Problems/0129.cpp @@ -1,26 +1,26 @@ class Solution { -public: - int sumNumbers(TreeNode *root) { - if (!root) return 0; + public: + int sumNumbers(TreeNode *root) { + if (!root) return 0; - int sum = 0, res = 0; - stack<pair<TreeNode *, int>> st; - while (true) { - while (root) { - sum *= 10; - sum += root->val; - if (root->right) - st.push({root->right, sum}); - else if (!root->left) - res += sum; - root = root->left; - } - if (st.empty()) break; - root = st.top().first; - sum = st.top().second; - st.pop(); - } + int sum = 0, res = 0; + stack<pair<TreeNode *, int>> st; + while (true) { + while (root) { + sum *= 10; + sum += root->val; + if (root->right) + st.push({root->right, sum}); + else if (!root->left) + res += sum; + root = root->left; + } + if (st.empty()) break; + root = st.top().first; + sum = st.top().second; + st.pop(); + } - return res; - } + return res; + } }; diff --git a/Problems/0130.cpp b/Problems/0130.cpp @@ -1,53 +1,48 @@ class Solution { - typedef vector<vector<char>> Matrix; - typedef queue<pair<int, int>> Queue; - const vector<pair<int, int>> offsets = { - { 0, 1}, - { 0, -1}, - { 1, 0}, - {-1, 0} - }; - - int n, m; - - int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } - - void dfs(Matrix &board, int x, int y) { - Queue q; - - q.push({x, y}), board[x][y] = '#'; - while (!q.empty()) { - auto [a, b] = q.front(); - q.pop(); - for (auto [oa, ob] : offsets) { - int x = a + oa, y = b + ob; - if (!valid(x, y) || board[x][y] == 'X' || board[x][y] != 'O') continue; - board[x][y] = '#'; - q.push({x, y}); - } + typedef vector<vector<char>> Matrix; + typedef queue<pair<int, int>> Queue; + const vector<pair<int, int>> offsets = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + + int n, m; + + int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } + + void dfs(Matrix &board, int x, int y) { + Queue q; + + q.push({x, y}), board[x][y] = '#'; + while (!q.empty()) { + auto [a, b] = q.front(); + q.pop(); + for (auto [oa, ob] : offsets) { + int x = a + oa, y = b + ob; + if (!valid(x, y) || board[x][y] == 'X' || board[x][y] != 'O') continue; + board[x][y] = '#'; + q.push({x, y}); + } + } } - } -public: - void solve(Matrix &board) { - n = board.size(), m = board[0].size(); + public: + void solve(Matrix &board) { + n = board.size(), m = board[0].size(); - unordered_set<int> convert; - Queue q; - int group = 0; + unordered_set<int> convert; + Queue q; + int group = 0; - for (int i = 0; i < n; i++) { - if (board[i][0] == 'O') dfs(board, i, 0); - if (board[i][m - 1] == 'O') dfs(board, i, m - 1); - } + for (int i = 0; i < n; i++) { + if (board[i][0] == 'O') dfs(board, i, 0); + if (board[i][m - 1] == 'O') dfs(board, i, m - 1); + } - for (int j = 0; j < m; j++) { - if (board[0][j] == 'O') dfs(board, 0, j); - if (board[n - 1][j] == 'O') dfs(board, n - 1, j); - } + for (int j = 0; j < m; j++) { + if (board[0][j] == 'O') dfs(board, 0, j); + if (board[n - 1][j] == 'O') dfs(board, n - 1, j); + } - for (int i = 0; i < n; i++) - for (int j = 0; j < m; j++) - if (board[i][j] != 'X') board[i][j] = board[i][j] == 'O' ? 'X' : 'O'; - } + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + if (board[i][j] != 'X') board[i][j] = board[i][j] == 'O' ? 'X' : 'O'; + } }; diff --git a/Problems/0131.cpp b/Problems/0131.cpp @@ -1,60 +1,60 @@ // Backtracking class Solution { - vector<string> st; - vector<vector<string>> res; - - bool valid(const string &s) { - int i = 0, j = s.size() - 1; - while (i < j) - if (s[i++] != s[j--]) return false; - return true; - } - - void dfs(const string &s, int pos) { - if (pos == s.size()) res.push_back(st); - - string crnt = ""; - for (int i = pos; i < s.size(); i++) { - crnt += s[i]; - if (valid(crnt)) { - st.push_back(crnt); - dfs(s, i + 1); - st.pop_back(); - } + vector<string> st; + vector<vector<string>> res; + + bool valid(const string &s) { + int i = 0, j = s.size() - 1; + while (i < j) + if (s[i++] != s[j--]) return false; + return true; } - } -public: - vector<vector<string>> partition(string s) { - dfs(s, 0); - return res; - } + void dfs(const string &s, int pos) { + if (pos == s.size()) res.push_back(st); + + string crnt = ""; + for (int i = pos; i < s.size(); i++) { + crnt += s[i]; + if (valid(crnt)) { + st.push_back(crnt); + dfs(s, i + 1); + st.pop_back(); + } + } + } + + public: + vector<vector<string>> partition(string s) { + dfs(s, 0); + return res; + } }; // Backtracking with DP class Solution { - vector<string> st; - vector<vector<string>> res; - - void dfs(const string &s, int pos, vector<vector<bool>> &dp) { - if (pos == s.size()) res.push_back(st); - - string crnt = ""; - for (int i = pos; i < s.size(); i++) { - crnt += s[i]; - if (s[pos] == s[i] && (i - pos < 2 || dp[pos + 1][i - 1])) { - dp[pos][i] = true; - st.push_back(crnt); - dfs(s, i + 1, dp); - st.pop_back(); - } + vector<string> st; + vector<vector<string>> res; + + void dfs(const string &s, int pos, vector<vector<bool>> &dp) { + if (pos == s.size()) res.push_back(st); + + string crnt = ""; + for (int i = pos; i < s.size(); i++) { + crnt += s[i]; + if (s[pos] == s[i] && (i - pos < 2 || dp[pos + 1][i - 1])) { + dp[pos][i] = true; + st.push_back(crnt); + dfs(s, i + 1, dp); + st.pop_back(); + } + } + } + + public: + vector<vector<string>> partition(string s) { + vector<vector<bool>> dp(s.size(), vector<bool>(s.size(), false)); + dfs(s, 0, dp); + return res; } - } - -public: - vector<vector<string>> partition(string s) { - vector<vector<bool>> dp(s.size(), vector<bool>(s.size(), false)); - dfs(s, 0, dp); - return res; - } }; diff --git a/Problems/0133.cpp b/Problems/0133.cpp @@ -1,29 +1,27 @@ class Solution { -public: - Node *cloneGraph(Node *node) { - if (!node) return nullptr; + public: + Node *cloneGraph(Node *node) { + if (!node) return nullptr; - Node *head = new Node(node->val); - unordered_map<Node *, Node *> um({ - {node, head} - }); + Node *head = new Node(node->val); + unordered_map<Node *, Node *> um({{node, head}}); - stack<Node *> st; - st.push(node); - while (!st.empty()) { - Node *node = st.top(); - st.pop(); - for (Node *c : node->neighbors) { - if (um.find(c) != um.end()) { - um[node]->neighbors.push_back(um[c]); - continue; + stack<Node *> st; + st.push(node); + while (!st.empty()) { + Node *node = st.top(); + st.pop(); + for (Node *c : node->neighbors) { + if (um.find(c) != um.end()) { + um[node]->neighbors.push_back(um[c]); + continue; + } + Node *n = new Node(c->val); + um[node]->neighbors.push_back(n); + um.insert(make_pair(c, n)); + st.push(c); + } } - Node *n = new Node(c->val); - um[node]->neighbors.push_back(n); - um.insert(make_pair(c, n)); - st.push(c); - } + return head; } - return head; - } }; diff --git a/Problems/0134.cpp b/Problems/0134.cpp @@ -1,15 +1,15 @@ class Solution { -public: - int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { - int start = 0, total = 0, tank = 0; - for (int i = 0; i < gas.size(); i++) { - tank = tank + gas[i] - cost[i]; - if (tank < 0) { - start = i + 1; - total += tank; - tank = 0; - } + public: + int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { + int start = 0, total = 0, tank = 0; + for (int i = 0; i < gas.size(); i++) { + tank = tank + gas[i] - cost[i]; + if (tank < 0) { + start = i + 1; + total += tank; + tank = 0; + } + } + return (total + tank >= 0) ? start : -1; } - return (total + tank >= 0) ? start : -1; - } }; diff --git a/Problems/0135.cpp b/Problems/0135.cpp @@ -1,47 +1,46 @@ // original solution - accepted class Solution { -public: - int candy(vector<int> &ratings) { - // place holder rating for easy neighbor calculation - ratings.insert(ratings.begin(), -1), ratings.push_back(-1); - int n = ratings.size(); - - // sort by rating remembering the original index - vector<pair<int, int>> vec; - vec.reserve(n); - for (int i = 1; i < n - 1; i++) vec.push_back({ratings[i], i}); - sort(vec.begin(), vec.end()); - - vector<int> res(n, 1); // 'Each child must have at least one candy' - res.front() = res.back() = 0; // except placeholders - for (auto &[rating, index] : vec) { - if (rating < ratings[index + 1]) - res[index + 1] = max(res[index + 1], res[index] + 1); - - if (rating < ratings[index - 1]) - res[index - 1] = max(res[index - 1], res[index] + 1); + public: + int candy(vector<int> &ratings) { + // place holder rating for easy neighbor calculation + ratings.insert(ratings.begin(), -1), ratings.push_back(-1); + int n = ratings.size(); + + // sort by rating remembering the original index + vector<pair<int, int>> vec; + vec.reserve(n); + for (int i = 1; i < n - 1; i++) + vec.push_back({ratings[i], i}); + sort(vec.begin(), vec.end()); + + vector<int> res(n, 1); // 'Each child must have at least one candy' + res.front() = res.back() = 0; // except placeholders + for (auto &[rating, index] : vec) { + if (rating < ratings[index + 1]) res[index + 1] = max(res[index + 1], res[index] + 1); + + if (rating < ratings[index - 1]) res[index - 1] = max(res[index - 1], res[index] + 1); + } + + return accumulate(res.begin(), res.end(), 0); } - - return accumulate(res.begin(), res.end(), 0); - } }; // improved solution - same logic no nonsense class Solution { -public: - int candy(vector<int> &ratings) { - int n = ratings.size(); - if (n <= 1) return n; - - vector<int> res(n, 1); - for (int i = 0; i < n - 1; i++) { - if (ratings[i] < ratings[i + 1]) res[i + 1] = res[i] + 1; - } + public: + int candy(vector<int> &ratings) { + int n = ratings.size(); + if (n <= 1) return n; - for (int i = n - 1; i > 0; i--) { - if (ratings[i] < ratings[i - 1]) res[i - 1] = max(res[i - 1], res[i] + 1); - } + vector<int> res(n, 1); + for (int i = 0; i < n - 1; i++) { + if (ratings[i] < ratings[i + 1]) res[i + 1] = res[i] + 1; + } - return accumulate(res.begin(), res.end(), 0); - } + for (int i = n - 1; i > 0; i--) { + if (ratings[i] < ratings[i - 1]) res[i - 1] = max(res[i - 1], res[i] + 1); + } + + return accumulate(res.begin(), res.end(), 0); + } }; diff --git a/Problems/0136.cpp b/Problems/0136.cpp @@ -1,8 +1,9 @@ class Solution { -public: - int singleNumber(vector<int> &nums) { - int res = 0; - for (const int n : nums) res ^= n; - return res; - } + public: + int singleNumber(vector<int> &nums) { + int res = 0; + for (const int n : nums) + res ^= n; + return res; + } }; diff --git a/Problems/0137.cpp b/Problems/0137.cpp @@ -1,11 +1,11 @@ class Solution { -public: - int singleNumber(const vector<int> &nums) { - int mask1 = 0, mask2 = 0; - for (int n : nums) { - mask1 = (mask1 ^ n) & ~mask2; - mask2 = (mask2 ^ n) & ~mask1; + public: + int singleNumber(const vector<int> &nums) { + int mask1 = 0, mask2 = 0; + for (int n : nums) { + mask1 = (mask1 ^ n) & ~mask2; + mask2 = (mask2 ^ n) & ~mask1; + } + return mask1; } - return mask1; - } }; diff --git a/Problems/0138.cpp b/Problems/0138.cpp @@ -1,20 +1,20 @@ class Solution { -public: - Node *copyRandomList(Node *head) { - if (!head) return nullptr; + public: + Node *copyRandomList(Node *head) { + if (!head) return nullptr; - unordered_map<Node *, Node *> um; - Node *h, *t; - t = h = new Node(-1); - for (Node *p = head; p; p = p->next) { - t = t->next = new Node(p->val); - um.insert(make_pair(p, t)); - } + unordered_map<Node *, Node *> um; + Node *h, *t; + t = h = new Node(-1); + for (Node *p = head; p; p = p->next) { + t = t->next = new Node(p->val); + um.insert(make_pair(p, t)); + } - t = h->next; - for (Node *p = head; p; p = p->next, t = t->next) { - if (p->random != nullptr) t->random = um[p->random]; + t = h->next; + for (Node *p = head; p; p = p->next, t = t->next) { + if (p->random != nullptr) t->random = um[p->random]; + } + return h->next; } - return h->next; - } }; diff --git a/Problems/0139.cpp b/Problems/0139.cpp @@ -1 +1 @@ -Formating: Problems/0139.cpp +Formating : Problems / 0139.cpp diff --git a/Problems/0141.cpp b/Problems/0141.cpp @@ -1,15 +1,15 @@ class Solution { -public: - bool hasCycle(ListNode *head) { - if (!head) return false; + public: + bool hasCycle(ListNode *head) { + if (!head) return false; - ListNode *slow, *fast; - fast = slow = head; - while (fast->next && fast->next->next) { - fast = fast->next->next; - slow = slow->next; - if (fast == slow) return true; + ListNode *slow, *fast; + fast = slow = head; + while (fast->next && fast->next->next) { + fast = fast->next->next; + slow = slow->next; + if (fast == slow) return true; + } + return false; } - return false; - } }; diff --git a/Problems/0142.cpp b/Problems/0142.cpp @@ -1,22 +1,22 @@ class Solution { -public: - ListNode *detectCycle(ListNode *head) { - if (!head) return nullptr; + public: + ListNode *detectCycle(ListNode *head) { + if (!head) return nullptr; - ListNode *slow, *fast; - fast = slow = head; - while (fast->next && fast->next->next) { - fast = fast->next->next; - slow = slow->next; - if (fast == slow) { - fast = head; - while (fast != slow) { - fast = fast->next; - slow = slow->next; + ListNode *slow, *fast; + fast = slow = head; + while (fast->next && fast->next->next) { + fast = fast->next->next; + slow = slow->next; + if (fast == slow) { + fast = head; + while (fast != slow) { + fast = fast->next; + slow = slow->next; + } + return slow; + } } - return slow; - } + return nullptr; } - return nullptr; - } }; diff --git a/Problems/0143.cpp b/Problems/0143.cpp @@ -1,42 +1,42 @@ class Solution { - ListNode *reverseList(ListNode *head) { - ListNode *p, *q, *r; + ListNode *reverseList(ListNode *head) { + ListNode *p, *q, *r; - p = head, q = nullptr; - while (p) { - r = q; - q = p; - p = p->next; - q->next = r; + p = head, q = nullptr; + while (p) { + r = q; + q = p; + p = p->next; + q->next = r; + } + + return q; } - return q; - } + ListNode *bmiddleNode(ListNode *head) { + ListNode *fast, *slow; + fast = slow = head; + while (fast->next && fast->next->next) { + fast = fast->next->next; + slow = slow->next; + } - ListNode *bmiddleNode(ListNode *head) { - ListNode *fast, *slow; - fast = slow = head; - while (fast->next && fast->next->next) { - fast = fast->next->next; - slow = slow->next; + return slow; } - return slow; - } - -public: - void reorderList(ListNode *head) { - ListNode *bmid = bmiddleNode(head); - ListNode *rev = reverseList(bmid->next); - bmid->next = nullptr; + public: + void reorderList(ListNode *head) { + ListNode *bmid = bmiddleNode(head); + ListNode *rev = reverseList(bmid->next); + bmid->next = nullptr; - ListNode top, *tmp = &top, *a, *b, *an; - for (a = head, b = rev; b; b = b->next, a = an) { - an = a->next; - tmp = tmp->next = a; - tmp = tmp->next = b; + ListNode top, *tmp = &top, *a, *b, *an; + for (a = head, b = rev; b; b = b->next, a = an) { + an = a->next; + tmp = tmp->next = a; + tmp = tmp->next = b; + } + if (a) tmp = tmp->next = a; + tmp->next = nullptr; } - if (a) tmp = tmp->next = a; - tmp->next = nullptr; - } }; diff --git a/Problems/0144.cpp b/Problems/0144.cpp @@ -1,20 +1,20 @@ class Solution { -public: - vector<int> preorderTraversal(TreeNode *root) { - if (!root) return {}; + public: + vector<int> preorderTraversal(TreeNode *root) { + if (!root) return {}; - vector<int> res; - stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - while (root) { - res.push_back(root->val); - if (root->right) st.push(root->right); - root = root->left; - } + vector<int> res; + stack<TreeNode *> st; + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + while (root) { + res.push_back(root->val); + if (root->right) st.push(root->right); + root = root->left; + } + } + return res; } - return res; - } }; diff --git a/Problems/0145.cpp b/Problems/0145.cpp @@ -1,33 +1,33 @@ class Solution { -public: - vector<int> postorderTraversal(TreeNode *root) { - if (!root) return {}; + public: + vector<int> postorderTraversal(TreeNode *root) { + if (!root) return {}; - vector<int> res; - unordered_set<TreeNode *> s; - stack<TreeNode *> st; + vector<int> res; + unordered_set<TreeNode *> s; + stack<TreeNode *> st; - while (root) { - st.push(root); - root = root->left; - } - - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (!s.count(root)) { - s.insert(root); - st.push(root); - root = root->right; while (root) { - st.push(root); - root = root->left; + st.push(root); + root = root->left; } - } else { - res.push_back(root->val); - } - } - return res; - } + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (!s.count(root)) { + s.insert(root); + st.push(root); + root = root->right; + while (root) { + st.push(root); + root = root->left; + } + } else { + res.push_back(root->val); + } + } + + return res; + } }; diff --git a/Problems/0146.cpp b/Problems/0146.cpp @@ -1,37 +1,37 @@ class LRUCache { - unordered_map<int, pair<int, int>> um; - queue<pair<int, int>> q; - int capacity; + unordered_map<int, pair<int, int>> um; + queue<pair<int, int>> q; + int capacity; -public: - LRUCache(int capacity) : capacity(capacity) {} + public: + LRUCache(int capacity) : capacity(capacity) {} - int get(int key) { - auto it = um.find(key); - if (it == um.end()) return -1; - q.push({key, ++it->second.first}); - return it->second.second; - } - - void put(int key, int value) { - auto it = um.find(key); - if (it != um.end()) { - q.push({key, ++it->second.first}); - it->second.second = value; - return; + int get(int key) { + auto it = um.find(key); + if (it == um.end()) return -1; + q.push({key, ++it->second.first}); + return it->second.second; } - if (um.size() == capacity) { - while (true) { - auto [key, time] = q.front(); - q.pop(); - if (um[key].first == time) { - um.erase(key); - break; + void put(int key, int value) { + auto it = um.find(key); + if (it != um.end()) { + q.push({key, ++it->second.first}); + it->second.second = value; + return; + } + + if (um.size() == capacity) { + while (true) { + auto [key, time] = q.front(); + q.pop(); + if (um[key].first == time) { + um.erase(key); + break; + } + } } - } + q.push({key, 0}); + um[key] = {0, value}; } - q.push({key, 0}); - um[key] = {0, value}; - } }; diff --git a/Problems/0148.cpp b/Problems/0148.cpp @@ -1,38 +1,37 @@ class Solution { -public: - ListNode *sortList(ListNode *head) { - if (!head || !head->next) return head; - ListNode *mid = getMid(head), *left = sortList(head), - *right = sortList(mid); - return merge(left, right); - } + public: + ListNode *sortList(ListNode *head) { + if (!head || !head->next) return head; + ListNode *mid = getMid(head), *left = sortList(head), *right = sortList(mid); + return merge(left, right); + } - ListNode *merge(ListNode *list1, ListNode *list2) { - ListNode head, *t = &head; + ListNode *merge(ListNode *list1, ListNode *list2) { + ListNode head, *t = &head; - while (list1 && list2) { - if (list1->val < list2->val) { - t = t->next = list1; - list1 = list1->next; - } else { - t = t->next = list2; - list2 = list2->next; - } - } + while (list1 && list2) { + if (list1->val < list2->val) { + t = t->next = list1; + list1 = list1->next; + } else { + t = t->next = list2; + list2 = list2->next; + } + } - t->next = list1 ? list1 : list2; - return head.next; - } + t->next = list1 ? list1 : list2; + return head.next; + } - ListNode *getMid(ListNode *head) { - ListNode *fast, *slow; - fast = slow = head; - while (fast->next && fast->next->next) { - fast = fast->next->next; - slow = slow->next; + ListNode *getMid(ListNode *head) { + ListNode *fast, *slow; + fast = slow = head; + while (fast->next && fast->next->next) { + fast = fast->next->next; + slow = slow->next; + } + fast = slow->next; + slow->next = nullptr; + return fast; } - fast = slow->next; - slow->next = nullptr; - return fast; - } }; diff --git a/Problems/0149.cpp b/Problems/0149.cpp @@ -1,18 +1,19 @@ class Solution { -public: - int maxPoints(vector<vector<int>> &points) { - int n = points.size(); - if (n == 1) return 1; + public: + int maxPoints(vector<vector<int>> &points) { + int n = points.size(); + if (n == 1) return 1; - int res = 2; - for (int i = 0; i < n; i++) { - unordered_map<double, int> um; - for (int j = 0; j < n; j++) { - if (j == i) continue; - um[atan2(points[j][1] - points[i][1], points[j][0] - points[i][0])]++; - } - for (auto [_, count] : um) res = max(res, count + 1); + int res = 2; + for (int i = 0; i < n; i++) { + unordered_map<double, int> um; + for (int j = 0; j < n; j++) { + if (j == i) continue; + um[atan2(points[j][1] - points[i][1], points[j][0] - points[i][0])]++; + } + for (auto [_, count] : um) + res = max(res, count + 1); + } + return res; } - return res; - } }; diff --git a/Problems/0150.cpp b/Problems/0150.cpp @@ -1,28 +1,26 @@ class Solution { - bool is_op(const string &s) { - return s == "+" || s == "-" || s == "*" || s == "/"; - } + bool is_op(const string &s) { return s == "+" || s == "-" || s == "*" || s == "/"; } -public: - int evalRPN(vector<string> &tokens) { - if (tokens.size() == 0) return 0; + public: + int evalRPN(vector<string> &tokens) { + if (tokens.size() == 0) return 0; - stack<long long> st; - for (string &s : tokens) { - if (is_op(s)) { - long long y = st.top(); - st.pop(); - long long x = st.top(); - st.pop(); - switch (s[0]) { - case '+': st.push(x + y); break; - case '-': st.push(x - y); break; - case '*': st.push(x * y); break; - case '/': st.push(x / y); break; + stack<long long> st; + for (string &s : tokens) { + if (is_op(s)) { + long long y = st.top(); + st.pop(); + long long x = st.top(); + st.pop(); + switch (s[0]) { + case '+': st.push(x + y); break; + case '-': st.push(x - y); break; + case '*': st.push(x * y); break; + case '/': st.push(x / y); break; + } + } else + st.push(stoi(s)); } - } else - st.push(stoi(s)); + return st.top(); } - return st.top(); - } }; diff --git a/Problems/0151.cpp b/Problems/0151.cpp @@ -1,18 +1,18 @@ class Solution { -public: - string reverseWords(string s) { - string res = ""; - string buff = ""; - for (int i = 0; i < s.size(); i++) { - if (s[i] != ' ') { - buff += s[i]; - } else if (buff != "") { - res = buff + " " + res; - buff = ""; - } + public: + string reverseWords(string s) { + string res = ""; + string buff = ""; + for (int i = 0; i < s.size(); i++) { + if (s[i] != ' ') { + buff += s[i]; + } else if (buff != "") { + res = buff + " " + res; + buff = ""; + } + } + if (buff != "") res = buff + " " + res; + if (res != "") res.pop_back(); + return res; } - if (buff != "") res = buff + " " + res; - if (res != "") res.pop_back(); - return res; - } }; diff --git a/Problems/0152.cpp b/Problems/0152.cpp @@ -1,3 +1 @@ -Formating: Problems/0152.cpp -Formating: Problems/0300.cpp -Formating: Problems/1567.cpp +Formating : Problems / 0152.cpp Formating : Problems / 0300.cpp Formating : Problems / 1567.cpp diff --git a/Problems/0153.cpp b/Problems/0153.cpp @@ -1,15 +1,15 @@ class Solution { -public: - int findMin(vector<int> &nums) { - int low = 0, high = nums.size() - 1; - while (low < high) { - if (nums[low] < nums[high]) return nums[low]; - int mid = low + (high - low) / 2; - if (nums[mid] >= nums[low]) - low = mid + 1; - else - high = mid; + public: + int findMin(vector<int> &nums) { + int low = 0, high = nums.size() - 1; + while (low < high) { + if (nums[low] < nums[high]) return nums[low]; + int mid = low + (high - low) / 2; + if (nums[mid] >= nums[low]) + low = mid + 1; + else + high = mid; + } + return nums[low]; } - return nums[low]; - } }; diff --git a/Problems/0155.cpp b/Problems/0155.cpp @@ -1,12 +1,10 @@ class MinStack { - stack<pair<int, int>> st; + stack<pair<int, int>> st; -public: - MinStack() {} - void push(int val) { - st.push({val, !st.size() ? val : min(val, st.top().second)}); - } - void pop() { st.pop(); } - int top() { return st.top().first; } - int getMin() { return st.top().second; } + public: + MinStack() {} + void push(int val) { st.push({val, !st.size() ? val : min(val, st.top().second)}); } + void pop() { st.pop(); } + int top() { return st.top().first; } + int getMin() { return st.top().second; } }; diff --git a/Problems/0160.cpp b/Problems/0160.cpp @@ -1,20 +1,22 @@ class Solution { -public: - ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { - if (!headA || !headB) return nullptr; + public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + if (!headA || !headB) return nullptr; - ListNode *res = nullptr; + ListNode *res = nullptr; - for (ListNode *p = headA; p; p = p->next) p->val = -p->val; + for (ListNode *p = headA; p; p = p->next) + p->val = -p->val; - for (ListNode *p = headB; p; p = p->next) - if (p->val < 0) { - res = p; - break; - } + for (ListNode *p = headB; p; p = p->next) + if (p->val < 0) { + res = p; + break; + } - for (ListNode *p = headA; p; p = p->next) p->val = -p->val; + for (ListNode *p = headA; p; p = p->next) + p->val = -p->val; - return res; - } + return res; + } }; diff --git a/Problems/0162.cpp b/Problems/0162.cpp @@ -1,16 +1,16 @@ class Solution { -public: - int findPeakElement(vector<int>& nums) { + public: + int findPeakElement(vector<int> &nums) { int n = nums.size(); - if(n==1) return 0; + if (n == 1) return 0; - for(int i=0; i<n-1; ) { - if(nums[i]>nums[i+1]) return i; - i+=2; - if(i>=n) break; - if(nums[i-1]>nums[i]) return i-1; + for (int i = 0; i < n - 1;) { + if (nums[i] > nums[i + 1]) return i; + i += 2; + if (i >= n) break; + if (nums[i - 1] > nums[i]) return i - 1; } - if(nums[n-1]>nums[n-2]) return n-1; + if (nums[n - 1] > nums[n - 2]) return n - 1; return -1; } diff --git a/Problems/0164.cpp b/Problems/0164.cpp @@ -1,4 +1,3 @@ -Formating: Problems/0164.cpp -Formating: Problems/0164.cpp -Formating: Problems/0912.cpp -Formating: Problems/2343.cpp +Formating + : Problems / + 0164.cpp Formating : Problems / 0164.cpp Formating : Problems / 0912.cpp Formating : Problems / 2343.cpp diff --git a/Problems/0165.cpp b/Problems/0165.cpp @@ -1,25 +1,29 @@ class Solution { -public: - int compareVersion(string version1, string version2) { - stringstream s1(version1), s2(version2); - vector<int> v1, v2; + public: + int compareVersion(string version1, string version2) { + stringstream s1(version1), s2(version2); + vector<int> v1, v2; - string crnt; - while (getline(s1, crnt, '.')) v1.push_back(stoi(crnt)); - while (getline(s2, crnt, '.')) v2.push_back(stoi(crnt)); + string crnt; + while (getline(s1, crnt, '.')) + v1.push_back(stoi(crnt)); + while (getline(s2, crnt, '.')) + v2.push_back(stoi(crnt)); - while (v1.size() < v2.size()) v1.push_back(0); - while (v1.size() > v2.size()) v2.push_back(0); + while (v1.size() < v2.size()) + v1.push_back(0); + while (v1.size() > v2.size()) + v2.push_back(0); - int i = 0, j = 0; - while (i < v1.size() && j < v2.size()) { - if (v1[i] > v2[j]) return 1; - if (v1[i] < v2[j]) - return -1; - else - i++, j++; - } + int i = 0, j = 0; + while (i < v1.size() && j < v2.size()) { + if (v1[i] > v2[j]) return 1; + if (v1[i] < v2[j]) + return -1; + else + i++, j++; + } - return 0; - } + return 0; + } }; diff --git a/Problems/0167.cpp b/Problems/0167.cpp @@ -1,16 +1,16 @@ class Solution { -public: - vector<int> twoSum(vector<int> &numbers, int target) { - int i = 0, j = numbers.size() - 1; - while (i < j) { - int sum = numbers[i] + numbers[j]; - if (sum == target) - return {i + 1, j + 1}; - else if (sum < target) - i++; - else - j--; + public: + vector<int> twoSum(vector<int> &numbers, int target) { + int i = 0, j = numbers.size() - 1; + while (i < j) { + int sum = numbers[i] + numbers[j]; + if (sum == target) + return {i + 1, j + 1}; + else if (sum < target) + i++; + else + j--; + } + return {}; } - return {}; - } }; diff --git a/Problems/0168.cpp b/Problems/0168.cpp @@ -1,12 +1,12 @@ class Solution { -public: - string convertToTitle(int columnNumber) { - string res = ""; - do { - columnNumber -= 1; - res += 'A' + columnNumber % 26; - } while ((columnNumber /= 26)); - reverse(res.begin(), res.end()); - return res; - } + public: + string convertToTitle(int columnNumber) { + string res = ""; + do { + columnNumber -= 1; + res += 'A' + columnNumber % 26; + } while ((columnNumber /= 26)); + reverse(res.begin(), res.end()); + return res; + } }; diff --git a/Problems/0169.cpp b/Problems/0169.cpp @@ -1,10 +1,11 @@ class Solution { -public: - int majorityElement(const vector<int> &nums) { - unordered_map<int, unsigned> um; - for (int n : nums) um[n]++; - for (auto [k, v] : um) - if (v > (nums.size() / 2)) return k; - return -1; - } + public: + int majorityElement(const vector<int> &nums) { + unordered_map<int, unsigned> um; + for (int n : nums) + um[n]++; + for (auto [k, v] : um) + if (v > (nums.size() / 2)) return k; + return -1; + } }; diff --git a/Problems/0171.cpp b/Problems/0171.cpp @@ -1,11 +1,11 @@ class Solution { -public: - int titleToNumber(string columnTitle) { - int res = 0; - for (char c : columnTitle) { - res *= 26; - res += c - 'A' + 1; + public: + int titleToNumber(string columnTitle) { + int res = 0; + for (char c : columnTitle) { + res *= 26; + res += c - 'A' + 1; + } + return res; } - return res; - } }; diff --git a/Problems/0173.cpp b/Problems/0173.cpp @@ -1,52 +1,52 @@ // Naive approach using vector to precompute in-order traversal class BSTIterator { - vector<int> vec; - int current = 0; - -public: - BSTIterator(TreeNode *root) { - stack<TreeNode *> st; - while (true) { - while (root) { - st.push(root); - root = root->left; - } - if (st.empty()) break; - root = st.top(); - st.pop(); - vec.push_back(root->val); - root = root->right; + vector<int> vec; + int current = 0; + + public: + BSTIterator(TreeNode *root) { + stack<TreeNode *> st; + while (true) { + while (root) { + st.push(root); + root = root->left; + } + if (st.empty()) break; + root = st.top(); + st.pop(); + vec.push_back(root->val); + root = root->right; + } } - } - int next() { return vec[current++]; } + int next() { return vec[current++]; } - bool hasNext() { return current < vec.size(); } + bool hasNext() { return current < vec.size(); } }; // Compute in-order on the fly class BSTIterator { - stack<TreeNode *> st; + stack<TreeNode *> st; - void fill_stack(TreeNode *root) { - while (root) { - st.push(root); - root = root->left; + void fill_stack(TreeNode *root) { + while (root) { + st.push(root); + root = root->left; + } } - } -public: - BSTIterator(TreeNode *root) { fill_stack(root); } + public: + BSTIterator(TreeNode *root) { fill_stack(root); } - int next() { - int val = st.top()->val; - TreeNode *root = st.top()->right; - st.pop(); - fill_stack(root); - return val; - } + int next() { + int val = st.top()->val; + TreeNode *root = st.top()->right; + st.pop(); + fill_stack(root); + return val; + } - bool hasNext() { return !st.empty(); } + bool hasNext() { return !st.empty(); } }; diff --git a/Problems/0179.cpp b/Problems/0179.cpp @@ -1,18 +1,18 @@ class Solution { -public: - string largestNumber(const vector<int> &nums) { - const static auto cmp = [](const string &x, const string &y) { - return x + y > y + x; - }; + public: + string largestNumber(const vector<int> &nums) { + const static auto cmp = [](const string &x, const string &y) { return x + y > y + x; }; - vector<string> v(nums.size()); - for (int i = 0; i < v.size(); i++) v[i] = to_string(nums[i]); + vector<string> v(nums.size()); + for (int i = 0; i < v.size(); i++) + v[i] = to_string(nums[i]); - sort(v.begin(), v.end(), cmp); - if (v[0] == "0") return "0"; + sort(v.begin(), v.end(), cmp); + if (v[0] == "0") return "0"; - string res = ""; - for (int i = 0; i < v.size(); i++) res += v[i]; - return res; - } + string res = ""; + for (int i = 0; i < v.size(); i++) + res += v[i]; + return res; + } }; diff --git a/Problems/0187.cpp b/Problems/0187.cpp @@ -1,58 +1,60 @@ // Left to right class Solution { -public: - vector<string> findRepeatedDnaSequences(string s) { - if (s.size() <= 10) return {}; - - unordered_map<string, int> um; - vector<string> res; - string sec = ""; - - for (int i = 0; i < 10; i++) sec += s[i]; - um[sec]++; - for (int i = 10; i < s.size(); i++) { - sec = sec.substr(1) + s[i]; - if (um[sec]++ == 1) res.push_back(sec); + public: + vector<string> findRepeatedDnaSequences(string s) { + if (s.size() <= 10) return {}; + + unordered_map<string, int> um; + vector<string> res; + string sec = ""; + + for (int i = 0; i < 10; i++) + sec += s[i]; + um[sec]++; + for (int i = 10; i < s.size(); i++) { + sec = sec.substr(1) + s[i]; + if (um[sec]++ == 1) res.push_back(sec); + } + + return res; } - - return res; - } }; // Right to left class Solution { -public: - vector<string> findRepeatedDnaSequences(string s) { - if (s.size() <= 10) return {}; - - unordered_map<string, int> um; - vector<string> res; - string sec = ""; - - for (int i = s.size() - 1; i >= s.size() - 10; i--) sec = s[i] + sec; - um[sec]++; - for (int i = s.size() - 10 - 1; i >= 0; i--) { - sec.pop_back(); - sec = s[i] + sec; - if (um[sec]++ == 1) res.push_back(sec); + public: + vector<string> findRepeatedDnaSequences(string s) { + if (s.size() <= 10) return {}; + + unordered_map<string, int> um; + vector<string> res; + string sec = ""; + + for (int i = s.size() - 1; i >= s.size() - 10; i--) + sec = s[i] + sec; + um[sec]++; + for (int i = s.size() - 10 - 1; i >= 0; i--) { + sec.pop_back(); + sec = s[i] + sec; + if (um[sec]++ == 1) res.push_back(sec); + } + + return res; } - - return res; - } }; // Bit hacking class Solution { -public: - vector<string> findRepeatedDnaSequences(string s) { - unordered_map<unsigned, int> um; - vector<string> res; - - for (unsigned i = 0, sec = 0; i < s.size(); i++) { - sec = sec << 3 & 0x3FFFFFFF | s[i] & 7; - if (um[sec]++ == 1) res.push_back(s.substr(i - 9, 10)); - } + public: + vector<string> findRepeatedDnaSequences(string s) { + unordered_map<unsigned, int> um; + vector<string> res; - return res; - } + for (unsigned i = 0, sec = 0; i < s.size(); i++) { + sec = sec << 3 & 0x3FFFFFFF | s[i] & 7; + if (um[sec]++ == 1) res.push_back(s.substr(i - 9, 10)); + } + + return res; + } }; diff --git a/Problems/0189.cpp b/Problems/0189.cpp @@ -1,22 +1,25 @@ // O(n) memory solution class Solution { -public: - void rotate(vector<int> &nums, int k) { - k %= nums.size(); - vector<int> t(k); - for (int i = 0; i < k; i++) t[i] = nums[nums.size() - k + i]; - for (int i = nums.size() - k - 1; i >= 0; i--) nums[i + k] = nums[i]; - for (int i = 0; i < k; i++) nums[i] = t[i]; - } + public: + void rotate(vector<int> &nums, int k) { + k %= nums.size(); + vector<int> t(k); + for (int i = 0; i < k; i++) + t[i] = nums[nums.size() - k + i]; + for (int i = nums.size() - k - 1; i >= 0; i--) + nums[i + k] = nums[i]; + for (int i = 0; i < k; i++) + nums[i] = t[i]; + } }; // O(1) memory solution class Solution { -public: - void rotate(vector<int> &nums, int k) { - k %= nums.size(); - reverse(nums.begin(), nums.end()); - reverse(nums.begin(), nums.begin() + k); - reverse(nums.begin() + k, nums.end()); - } + public: + void rotate(vector<int> &nums, int k) { + k %= nums.size(); + reverse(nums.begin(), nums.end()); + reverse(nums.begin(), nums.begin() + k); + reverse(nums.begin() + k, nums.end()); + } }; diff --git a/Problems/0190.cpp b/Problems/0190.cpp @@ -1,12 +1,12 @@ class Solution { -public: - uint32_t reverseBits(uint32_t n) { - int count = 32, res = 0; - while (count--) { - res <<= 1; - res += n & 1; - n >>= 1; + public: + uint32_t reverseBits(uint32_t n) { + int count = 32, res = 0; + while (count--) { + res <<= 1; + res += n & 1; + n >>= 1; + } + return res; } - return res; - } }; diff --git a/Problems/0191.cpp b/Problems/0191.cpp @@ -1,8 +1,9 @@ class Solution { -public: - int hammingWeight(uint32_t n) { - int res = 0; - while (n) res += n & 1, n >>= 1; - return res; - } + public: + int hammingWeight(uint32_t n) { + int res = 0; + while (n) + res += n & 1, n >>= 1; + return res; + } }; diff --git a/Problems/0198.cpp b/Problems/0198.cpp @@ -1,13 +1,13 @@ class Solution { -public: - int rob(vector<int> &nums) { - if (nums.size() == 0) return 0; - int prev1 = 0, prev2 = 0; - for (int num : nums) { - int tmp = prev1; - prev1 = max(prev2 + num, prev1); - prev2 = tmp; + public: + int rob(vector<int> &nums) { + if (nums.size() == 0) return 0; + int prev1 = 0, prev2 = 0; + for (int num : nums) { + int tmp = prev1; + prev1 = max(prev2 + num, prev1); + prev2 = tmp; + } + return prev1; } - return prev1; - } }; diff --git a/Problems/0199.cpp b/Problems/0199.cpp @@ -1,20 +1,20 @@ class Solution { -public: - vector<int> rightSideView(TreeNode *root) { - if (!root) return {}; + public: + vector<int> rightSideView(TreeNode *root) { + if (!root) return {}; - vector<int> res; - queue<TreeNode *> q; - q.push(root); - for (int lvl = 0; !q.empty(); lvl++) { - res.push_back(q.front()->val); - for (int k = q.size(); k > 0; k--) { - TreeNode *root = q.front(); - q.pop(); - if (root->right) q.push(root->right); - if (root->left) q.push(root->left); - } + vector<int> res; + queue<TreeNode *> q; + q.push(root); + for (int lvl = 0; !q.empty(); lvl++) { + res.push_back(q.front()->val); + for (int k = q.size(); k > 0; k--) { + TreeNode *root = q.front(); + q.pop(); + if (root->right) q.push(root->right); + if (root->left) q.push(root->left); + } + } + return res; } - return res; - } }; diff --git a/Problems/0200.cpp b/Problems/0200.cpp @@ -1,27 +1,27 @@ class Solution { -public: - int numIslands(vector<vector<char>> &grid) { - queue<pair<int, int>> q; - int cnt = 0; - int m = grid.size(), n = grid[0].size(); - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (grid[i][j] == '0') continue; - q.push(make_pair(i, j)); - cnt++; - while (!q.empty()) { - int i = q.front().first; - int j = q.front().second; - q.pop(); - if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') continue; - grid[i][j] = '0'; - q.push(make_pair(i + 1, j)); - q.push(make_pair(i - 1, j)); - q.push(make_pair(i, j + 1)); - q.push(make_pair(i, j - 1)); + public: + int numIslands(vector<vector<char>> &grid) { + queue<pair<int, int>> q; + int cnt = 0; + int m = grid.size(), n = grid[0].size(); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == '0') continue; + q.push(make_pair(i, j)); + cnt++; + while (!q.empty()) { + int i = q.front().first; + int j = q.front().second; + q.pop(); + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') continue; + grid[i][j] = '0'; + q.push(make_pair(i + 1, j)); + q.push(make_pair(i - 1, j)); + q.push(make_pair(i, j + 1)); + q.push(make_pair(i, j - 1)); + } + } } - } + return cnt; } - return cnt; - } }; diff --git a/Problems/0201.cpp b/Problems/0201.cpp @@ -1,9 +1,8 @@ class Solution { -public: + public: int rangeBitwiseAnd(int left, int right) { int cnt = 0; - while(left != right) - { + while (left != right) { cnt++; left >>= 1; right >>= 1; diff --git a/Problems/0202.cpp b/Problems/0202.cpp @@ -1,14 +1,16 @@ class Solution { -public: - bool isHappy(int n) { - unordered_set<int> seen; - int tmp; + public: + bool isHappy(int n) { + unordered_set<int> seen; + int tmp; - while (n != 1 && !seen.count(n)) { - seen.insert(n); - tmp = n, n = 0; - do { n += (tmp % 10) * (tmp % 10); } while ((tmp /= 10) > 0); + while (n != 1 && !seen.count(n)) { + seen.insert(n); + tmp = n, n = 0; + do { + n += (tmp % 10) * (tmp % 10); + } while ((tmp /= 10) > 0); + } + return !seen.count(n); } - return !seen.count(n); - } }; diff --git a/Problems/0203.cpp b/Problems/0203.cpp @@ -1,16 +1,16 @@ class Solution { -public: - ListNode *removeElements(ListNode *head, int val) { - if (!head) return nullptr; + public: + ListNode *removeElements(ListNode *head, int val) { + if (!head) return nullptr; - for (ListNode *p = head; p && p->next;) - if (p->next->val == val) - p->next = p->next->next; - else - p = p->next; + for (ListNode *p = head; p && p->next;) + if (p->next->val == val) + p->next = p->next->next; + else + p = p->next; - if (head->val == val) head = head->next; + if (head->val == val) head = head->next; - return head; - } + return head; + } }; diff --git a/Problems/0204.cpp b/Problems/0204.cpp @@ -1,13 +1,14 @@ class Solution { -public: - int countPrimes(int n) { - vector<bool> sieve(n); - int res = 0; - for (long i = 2; i < n; i++) { - if (sieve[i]) continue; - for (long j = i * i; j < n; j += i) sieve[j] = true; - res++; + public: + int countPrimes(int n) { + vector<bool> sieve(n); + int res = 0; + for (long i = 2; i < n; i++) { + if (sieve[i]) continue; + for (long j = i * i; j < n; j += i) + sieve[j] = true; + res++; + } + return res; } - return res; - } }; diff --git a/Problems/0205.cpp b/Problems/0205.cpp @@ -1,18 +1,18 @@ class Solution { -public: - bool isIsomorphic(string s, string t) { - unordered_map<char, char> um; - unordered_set<char> us; + public: + bool isIsomorphic(string s, string t) { + unordered_map<char, char> um; + unordered_set<char> us; - for (int i = 0; i < s.size(); i++) { - if (!um.count(s[i])) { - if (us.count(t[i])) return false; - um[s[i]] = t[i]; - us.insert(t[i]); - } else if (um[s[i]] != t[i]) - return false; - } + for (int i = 0; i < s.size(); i++) { + if (!um.count(s[i])) { + if (us.count(t[i])) return false; + um[s[i]] = t[i]; + us.insert(t[i]); + } else if (um[s[i]] != t[i]) + return false; + } - return true; - } + return true; + } }; diff --git a/Problems/0206.cpp b/Problems/0206.cpp @@ -1,16 +1,16 @@ class Solution { -public: - ListNode *reverseList(ListNode *head) { - ListNode *p, *q, *r; + public: + ListNode *reverseList(ListNode *head) { + ListNode *p, *q, *r; - p = head, q = nullptr; - while (p) { - r = q; - q = p; - p = p->next; - q->next = r; - } + p = head, q = nullptr; + while (p) { + r = q; + q = p; + p = p->next; + q->next = r; + } - return q; - } + return q; + } }; diff --git a/Problems/0207.cpp b/Problems/0207.cpp @@ -1,28 +1,28 @@ class Solution { - static int adj[2048][2048]; + static int adj[2048][2048]; -public: - bool canFinish(int n, const vector<vector<int>> &prerequisites) { - int count[2048] = {0}, size[2048] = {0}; + public: + bool canFinish(int n, const vector<vector<int>> &prerequisites) { + int count[2048] = {0}, size[2048] = {0}; - for (auto &p : prerequisites) { - adj[p[0]][size[p[0]]++] = p[1]; - count[p[1]]++; - } + for (auto &p : prerequisites) { + adj[p[0]][size[p[0]]++] = p[1]; + count[p[1]]++; + } - queue<int> q; - for (int i = 0; i < n; i++) - if (!count[i]) q.push(i); + queue<int> q; + for (int i = 0; i < n; i++) + if (!count[i]) q.push(i); - while (!q.empty()) { - int root = q.front(); - q.pop(), n--; - for (int i = 0; i < size[root]; i++) - if (!--count[adj[root][i]]) q.push(adj[root][i]); - } + while (!q.empty()) { + int root = q.front(); + q.pop(), n--; + for (int i = 0; i < size[root]; i++) + if (!--count[adj[root][i]]) q.push(adj[root][i]); + } - return n == 0; - } + return n == 0; + } }; int Solution::adj[2048][2048]; diff --git a/Problems/0208.cpp b/Problems/0208.cpp @@ -1,39 +1,40 @@ class Trie { - struct Record { - bool end; - array<Record *, 26> records = {nullptr}; + struct Record { + bool end; + array<Record *, 26> records = {nullptr}; - Record *insert(int x) { - if (records[x]) return records[x]; - return records[x] = new Record(); - } + Record *insert(int x) { + if (records[x]) return records[x]; + return records[x] = new Record(); + } - Record *check(int x) { return records[x]; } - }; + Record *check(int x) { return records[x]; } + }; - Record *record = new Record; - Record *last(string word) { - Record *crnt = record; - for (char c : word) - if (!crnt) - return nullptr; - else - crnt = crnt->check(c - 'a'); - return crnt; - } + Record *record = new Record; + Record *last(string word) { + Record *crnt = record; + for (char c : word) + if (!crnt) + return nullptr; + else + crnt = crnt->check(c - 'a'); + return crnt; + } -public: - void insert(string word) { - Record *crnt = record; - for (char c : word) crnt = crnt->insert(c - 'a'); - crnt->end = true; - } + public: + void insert(string word) { + Record *crnt = record; + for (char c : word) + crnt = crnt->insert(c - 'a'); + crnt->end = true; + } - bool search(string word) { - Record *crnt = last(word); - if (!crnt) return false; - return crnt->end; - } + bool search(string word) { + Record *crnt = last(word); + if (!crnt) return false; + return crnt->end; + } - bool startsWith(string prefix) { return last(prefix); } + bool startsWith(string prefix) { return last(prefix); } }; diff --git a/Problems/0209.cpp b/Problems/0209.cpp @@ -1,17 +1,17 @@ class Solution { -public: - int minSubArrayLen(int target, const vector<int> &nums) { - int i = 0, j = 0, sum = 0, res = nums.size() + 1; - while (true) { - if (sum >= target) { - res = min(res, j - i); - sum -= nums[i++]; - } else { - if (j == nums.size()) break; - sum += nums[j++]; - } + public: + int minSubArrayLen(int target, const vector<int> &nums) { + int i = 0, j = 0, sum = 0, res = nums.size() + 1; + while (true) { + if (sum >= target) { + res = min(res, j - i); + sum -= nums[i++]; + } else { + if (j == nums.size()) break; + sum += nums[j++]; + } + } + if (res == nums.size() + 1) return 0; + return res; } - if (res == nums.size() + 1) return 0; - return res; - } }; diff --git a/Problems/0210.cpp b/Problems/0210.cpp @@ -1,28 +1,28 @@ class Solution { -public: - vector<int> findOrder(int n, vector<vector<int>> &prerequisites) { - vector<vector<int>> adj(n); - vector<int> count(n, 0); - vector<int> res; - int num = 0; + public: + vector<int> findOrder(int n, vector<vector<int>> &prerequisites) { + vector<vector<int>> adj(n); + vector<int> count(n, 0); + vector<int> res; + int num = 0; - for (auto &p : prerequisites) { - adj[p[1]].push_back(p[0]); - count[p[0]]++; - } + for (auto &p : prerequisites) { + adj[p[1]].push_back(p[0]); + count[p[0]]++; + } - queue<int> q; - for (int i = 0; i < n; i++) - if (!count[i]) q.push(i); + queue<int> q; + for (int i = 0; i < n; i++) + if (!count[i]) q.push(i); - while (!q.empty()) { - int root = q.front(); - q.pop(); - res.push_back(root); - n--; - for (int c : adj[root]) - if (!--count[c]) q.push(c); + while (!q.empty()) { + int root = q.front(); + q.pop(); + res.push_back(root); + n--; + for (int c : adj[root]) + if (!--count[c]) q.push(c); + } + return n == 0 ? res : vector<int>(); } - return n == 0 ? res : vector<int>(); - } }; diff --git a/Problems/0211.cpp b/Problems/0211.cpp @@ -1,32 +1,31 @@ class WordDictionary { - vector<WordDictionary *> children; - bool isEndOfWord = false; - ; + vector<WordDictionary *> children; + bool isEndOfWord = false; + ; -public: - WordDictionary() : children(vector<WordDictionary *>(26, nullptr)) {} + public: + WordDictionary() : children(vector<WordDictionary *>(26, nullptr)) {} - void addWord(string word) { - WordDictionary *crnt = this; - for (char c : word) { - if (crnt->children[c - 'a'] == nullptr) - crnt->children[c - 'a'] = new WordDictionary(); - crnt = crnt->children[c - 'a']; + void addWord(string word) { + WordDictionary *crnt = this; + for (char c : word) { + if (crnt->children[c - 'a'] == nullptr) crnt->children[c - 'a'] = new WordDictionary(); + crnt = crnt->children[c - 'a']; + } + crnt->isEndOfWord = true; } - crnt->isEndOfWord = true; - } - bool search(string word) { - WordDictionary *crnt = this; - for (int i = 0; i < word.length(); ++i) { - if (word[i] == '.') { - for (auto c : crnt->children) - if (c && c->search(word.substr(i + 1))) return true; - return false; - } - if (crnt->children[word[i] - 'a'] == nullptr) return false; - crnt = crnt->children[word[i] - 'a']; + bool search(string word) { + WordDictionary *crnt = this; + for (int i = 0; i < word.length(); ++i) { + if (word[i] == '.') { + for (auto c : crnt->children) + if (c && c->search(word.substr(i + 1))) return true; + return false; + } + if (crnt->children[word[i] - 'a'] == nullptr) return false; + crnt = crnt->children[word[i] - 'a']; + } + return crnt && crnt->isEndOfWord; } - return crnt && crnt->isEndOfWord; - } }; diff --git a/Problems/0213.cpp b/Problems/0213.cpp @@ -1,20 +1,19 @@ class Solution { -public: - // see 198. House Robber - int rob_single(vector<int> &nums, int start, int end) { - if (end - start <= 0) return 0; - int prev1 = 0, prev2 = 0; - for (int i = start; i < end; i++) { - int tmp = prev1; - prev1 = max(prev2 + nums[i], prev1); - prev2 = tmp; + public: + // see 198. House Robber + int rob_single(vector<int> &nums, int start, int end) { + if (end - start <= 0) return 0; + int prev1 = 0, prev2 = 0; + for (int i = start; i < end; i++) { + int tmp = prev1; + prev1 = max(prev2 + nums[i], prev1); + prev2 = tmp; + } + return prev1; } - return prev1; - } - int rob(vector<int> &nums) { - if (nums.size() == 0) return 0; - return max(nums[0] + rob_single(nums, 2, nums.size() - 1), - rob_single(nums, 1, nums.size())); - } + int rob(vector<int> &nums) { + if (nums.size() == 0) return 0; + return max(nums[0] + rob_single(nums, 2, nums.size() - 1), rob_single(nums, 1, nums.size())); + } }; diff --git a/Problems/0215.cpp b/Problems/0215.cpp @@ -1,13 +1,13 @@ class Solution { -public: - int findKthLargest(vector<int> &nums, int k) { - priority_queue<int, vector<int>, greater<int>> pq; + public: + int findKthLargest(vector<int> &nums, int k) { + priority_queue<int, vector<int>, greater<int>> pq; - for (int num : nums) { - pq.push(num); - if (pq.size() > k) pq.pop(); - } + for (int num : nums) { + pq.push(num); + if (pq.size() > k) pq.pop(); + } - return pq.top(); - } + return pq.top(); + } }; diff --git a/Problems/0217.cpp b/Problems/0217.cpp @@ -1,20 +1,20 @@ class Solution { -public: - bool containsDuplicate(vector<int> &nums) { - unordered_set<int> us; - for (int n : nums) - if (us.count(n)) - return true; - else - us.insert(n); - return false; - } + public: + bool containsDuplicate(vector<int> &nums) { + unordered_set<int> us; + for (int n : nums) + if (us.count(n)) + return true; + else + us.insert(n); + return false; + } }; // Fun oneliner class Solution { -public: - bool containsDuplicate(vector<int> &nums) { - return nums.size() > unordered_set<int>(nums.begin(), nums.end()).size(); - } + public: + bool containsDuplicate(vector<int> &nums) { + return nums.size() > unordered_set<int>(nums.begin(), nums.end()).size(); + } }; diff --git a/Problems/0219.cpp b/Problems/0219.cpp @@ -1,19 +1,19 @@ class Solution { -public: - bool containsNearbyDuplicate(vector<int> &nums, int k) { - unordered_set<int> us; - int n = nums.size(), i; - for (i = 0; i <= k && i < n; i++) { - if (us.count(nums[i])) return true; - us.insert(nums[i]); - } + public: + bool containsNearbyDuplicate(vector<int> &nums, int k) { + unordered_set<int> us; + int n = nums.size(), i; + for (i = 0; i <= k && i < n; i++) { + if (us.count(nums[i])) return true; + us.insert(nums[i]); + } - for (; i < n; i++) { - us.erase(nums[i - k - 1]); - if (us.count(nums[i])) return true; - us.insert(nums[i]); - } + for (; i < n; i++) { + us.erase(nums[i - k - 1]); + if (us.count(nums[i])) return true; + us.insert(nums[i]); + } - return false; - } + return false; + } }; diff --git a/Problems/0221.cpp b/Problems/0221.cpp @@ -1,18 +1,18 @@ class Solution { -public: - int maximalSquare(vector<vector<char>> &matrix) { - int n = matrix.size(), m = matrix[0].size(), res = 0; - vector<vector<int>> dp(n, vector<int>(m, 0)); - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - if (!i || !j || matrix[i][j] == '0') { - dp[i][j] = matrix[i][j] - '0'; - } else { - dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1; + public: + int maximalSquare(vector<vector<char>> &matrix) { + int n = matrix.size(), m = matrix[0].size(), res = 0; + vector<vector<int>> dp(n, vector<int>(m, 0)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (!i || !j || matrix[i][j] == '0') { + dp[i][j] = matrix[i][j] - '0'; + } else { + dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1; + } + res = max(res, dp[i][j]); + } } - res = max(res, dp[i][j]); - } + return res * res; } - return res * res; - } }; diff --git a/Problems/0222.cpp b/Problems/0222.cpp @@ -1,25 +1,27 @@ class Solution { -public: - int countNodes(TreeNode *root) { - if (!root) return 0; + public: + int countNodes(TreeNode *root) { + if (!root) return 0; - int height = 0; - queue<TreeNode *> q; - q.push(root); - while (!q.empty()) { - TreeNode *root = q.front(); - q.pop(); - int rh = 0, lh = 0; - for (TreeNode *t = root; t; t = t->left) lh++; - for (TreeNode *t = root; t; t = t->right) rh++; - if (lh == rh) - height += exp2(rh) - 1; - else { - height++; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } + int height = 0; + queue<TreeNode *> q; + q.push(root); + while (!q.empty()) { + TreeNode *root = q.front(); + q.pop(); + int rh = 0, lh = 0; + for (TreeNode *t = root; t; t = t->left) + lh++; + for (TreeNode *t = root; t; t = t->right) + rh++; + if (lh == rh) + height += exp2(rh) - 1; + else { + height++; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + } + return height; } - return height; - } }; diff --git a/Problems/0223.cpp b/Problems/0223.cpp @@ -1,20 +1,17 @@ class Solution { - int calc_area(int x1, int y1, int x2, int y2) { - return abs(x1 - x2) * abs(y1 - y2); - } + int calc_area(int x1, int y1, int x2, int y2) { return abs(x1 - x2) * abs(y1 - y2); } -public: - int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, - int by2) { - int area = calc_area(ax1, ay1, ax2, ay2) + calc_area(bx1, by1, bx2, by2); - int x1, x2, y1, y2; - x1 = max(ax1, bx1); - x2 = min(ax2, bx2); - y1 = max(ay1, by1); - y2 = min(ay2, by2); - if (x2 - x1 > 0 && y2 - y1 > 0) - return area - calc_area(x1, y1, x2, y2); - else - return area; - } + public: + int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { + int area = calc_area(ax1, ay1, ax2, ay2) + calc_area(bx1, by1, bx2, by2); + int x1, x2, y1, y2; + x1 = max(ax1, bx1); + x2 = min(ax2, bx2); + y1 = max(ay1, by1); + y2 = min(ay2, by2); + if (x2 - x1 > 0 && y2 - y1 > 0) + return area - calc_area(x1, y1, x2, y2); + else + return area; + } }; diff --git a/Problems/0225.cpp b/Problems/0225.cpp @@ -1,22 +1,22 @@ class MyStack { - queue<int> q; + queue<int> q; -public: - void push(int x) { - q.push(x); - for (int i = 0; i < q.size() - 1; i++) { - q.push(q.front()); - q.pop(); + public: + void push(int x) { + q.push(x); + for (int i = 0; i < q.size() - 1; i++) { + q.push(q.front()); + q.pop(); + } } - } - int pop() { - int x = q.front(); - q.pop(); - return x; - } + int pop() { + int x = q.front(); + q.pop(); + return x; + } - int top() { return q.front(); } - bool empty() { return q.empty(); } + int top() { return q.front(); } + bool empty() { return q.empty(); } }; diff --git a/Problems/0226.cpp b/Problems/0226.cpp @@ -1,17 +1,17 @@ class Solution { -public: - TreeNode *invertTree(TreeNode *root) { - if (!root) return nullptr; + public: + TreeNode *invertTree(TreeNode *root) { + if (!root) return nullptr; - stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - swap(root->left, root->right); - if (root->left) st.push(root->left); - if (root->right) st.push(root->right); + stack<TreeNode *> st; + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + swap(root->left, root->right); + if (root->left) st.push(root->left); + if (root->right) st.push(root->right); + } + return root; } - return root; - } }; diff --git a/Problems/0227.cpp b/Problems/0227.cpp @@ -1,19 +1,19 @@ class Solution { -public: - int calculate(string s) { - stringstream ss("+" + s); - char op; - int n, last, ans = 0; - while (ss >> op >> n) { - if (op == '+' || op == '-') { - n = op == '+' ? n : -n; - ans += n; - } else { - n = op == '*' ? last * n : last / n; - ans = ans - last + n; - } - last = n; + public: + int calculate(string s) { + stringstream ss("+" + s); + char op; + int n, last, ans = 0; + while (ss >> op >> n) { + if (op == '+' || op == '-') { + n = op == '+' ? n : -n; + ans += n; + } else { + n = op == '*' ? last * n : last / n; + ans = ans - last + n; + } + last = n; + } + return ans; } - return ans; - } }; diff --git a/Problems/0228.cpp b/Problems/0228.cpp @@ -1,22 +1,22 @@ class Solution { -public: - vector<string> summaryRanges(vector<int> &nums) { - if (!nums.size()) return {}; - vector<string> res; - int start = 0; - for (int i = 1; i < nums.size(); i++) { - if (nums[i] == nums[i - 1] + 1) continue; - if (i - start > 1) - res.push_back(to_string(nums[start]) + "->" + to_string(nums[i - 1])); - else - res.push_back(to_string(nums[start])); - start = i; - } - if (nums.size() - start > 1) - res.push_back(to_string(nums[start]) + "->" + to_string(nums.back())); - else - res.push_back(to_string(nums[start])); + public: + vector<string> summaryRanges(vector<int> &nums) { + if (!nums.size()) return {}; + vector<string> res; + int start = 0; + for (int i = 1; i < nums.size(); i++) { + if (nums[i] == nums[i - 1] + 1) continue; + if (i - start > 1) + res.push_back(to_string(nums[start]) + "->" + to_string(nums[i - 1])); + else + res.push_back(to_string(nums[start])); + start = i; + } + if (nums.size() - start > 1) + res.push_back(to_string(nums[start]) + "->" + to_string(nums.back())); + else + res.push_back(to_string(nums[start])); - return res; - } + return res; + } }; diff --git a/Problems/0230.cpp b/Problems/0230.cpp @@ -1,17 +1,17 @@ class Solution { -public: - int kthSmallest(TreeNode *root, int k) { - stack<TreeNode *> st; - while (true) { - while (root) { - st.push(root); - root = root->left; - } - if (st.empty()) break; - root = st.top(), st.pop(); - if (!--k) return root->val; - root = root->right; + public: + int kthSmallest(TreeNode *root, int k) { + stack<TreeNode *> st; + while (true) { + while (root) { + st.push(root); + root = root->left; + } + if (st.empty()) break; + root = st.top(), st.pop(); + if (!--k) return root->val; + root = root->right; + } + return -1; } - return -1; - } }; diff --git a/Problems/0231.cpp b/Problems/0231.cpp @@ -1,4 +1,4 @@ class Solution { -public: - bool isPowerOfTwo(int n) { return n > 0 && !(n & (n - 1)); } + public: + bool isPowerOfTwo(int n) { return n > 0 && !(n & (n - 1)); } }; diff --git a/Problems/0232.cpp b/Problems/0232.cpp @@ -1 +1 @@ -Formating: Problems/0232.cpp +Formating : Problems / 0232.cpp diff --git a/Problems/0234.cpp b/Problems/0234.cpp @@ -1,38 +1,38 @@ class Solution { -public: - ListNode *invert(ListNode *head) { - ListNode *p, *q, *r; + public: + ListNode *invert(ListNode *head) { + ListNode *p, *q, *r; - p = head; - q = nullptr; - while (p) { - r = q; - q = p; - p = p->next; - q->next = r; + p = head; + q = nullptr; + while (p) { + r = q; + q = p; + p = p->next; + q->next = r; + } + return q; } - return q; - } - ListNode *first_half_end(ListNode *head) { - ListNode *fast, *slow; - fast = slow = head; - while (fast->next && fast->next->next) { - fast = fast->next->next; - slow = slow->next; + ListNode *first_half_end(ListNode *head) { + ListNode *fast, *slow; + fast = slow = head; + while (fast->next && fast->next->next) { + fast = fast->next->next; + slow = slow->next; + } + return slow; } - return slow; - } - bool isPalindrome(ListNode *head) { - if (!head || !head->next) return true; + bool isPalindrome(ListNode *head) { + if (!head || !head->next) return true; - ListNode *fhe = first_half_end(head); - ListNode *shs = invert(fhe->next); + ListNode *fhe = first_half_end(head); + ListNode *shs = invert(fhe->next); - for (ListNode *p = head, *tmp = shs; tmp; p = p->next, tmp = tmp->next) - if (p->val != tmp->val) return false; + for (ListNode *p = head, *tmp = shs; tmp; p = p->next, tmp = tmp->next) + if (p->val != tmp->val) return false; - return true; - } + return true; + } }; diff --git a/Problems/0235.cpp b/Problems/0235.cpp @@ -1,15 +1,15 @@ class Solution { -public: - TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) { - TreeNode *tmp = root; - while (true) { - if (root->val > p->val && root->val > q->val) - root = root->left; - else if (root->val < p->val && root->val < q->val) - root = root->right; - else - break; + public: + TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) { + TreeNode *tmp = root; + while (true) { + if (root->val > p->val && root->val > q->val) + root = root->left; + else if (root->val < p->val && root->val < q->val) + root = root->right; + else + break; + } + return root; } - return root; - } }; diff --git a/Problems/0236.cpp b/Problems/0236.cpp @@ -1,30 +1,32 @@ class Solution { -public: - TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) { - unordered_map<TreeNode *, TreeNode *> um; - stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (root->left) { - um.insert({root->left, root}); - st.push(root->left); - } - if (root->right) { - um.insert({root->right, root}); - st.push(root->right); - } - } + public: + TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) { + unordered_map<TreeNode *, TreeNode *> um; + stack<TreeNode *> st; + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (root->left) { + um.insert({root->left, root}); + st.push(root->left); + } + if (root->right) { + um.insert({root->right, root}); + st.push(root->right); + } + } - unordered_set<TreeNode *> ans; - while (p) { - ans.insert(p); - p = um[p]; - } + unordered_set<TreeNode *> ans; + while (p) { + ans.insert(p); + p = um[p]; + } - while (!ans.count(q)) { q = um[q]; } + while (!ans.count(q)) { + q = um[q]; + } - return q; - } + return q; + } }; diff --git a/Problems/0237.cpp b/Problems/0237.cpp @@ -1,7 +1,7 @@ class Solution { -public: - void deleteNode(ListNode *node) { - node->val = node->next->val; - node->next = node->next->next; - } + public: + void deleteNode(ListNode *node) { + node->val = node->next->val; + node->next = node->next->next; + } }; diff --git a/Problems/0238.cpp b/Problems/0238.cpp @@ -1,17 +1,17 @@ class Solution { -public: - vector<int> productExceptSelf(vector<int> &nums) { - int n = nums.size(); - vector<int> answer(n, 1); + public: + vector<int> productExceptSelf(vector<int> &nums) { + int n = nums.size(); + vector<int> answer(n, 1); - int acc1 = 1, acc2 = 1; - for (int i = 0, j = n - 1; i < n; i++, j--) { - answer[i] *= acc1; - answer[j] *= acc2; - acc1 *= nums[i]; - acc2 *= nums[j]; - } + int acc1 = 1, acc2 = 1; + for (int i = 0, j = n - 1; i < n; i++, j--) { + answer[i] *= acc1; + answer[j] *= acc2; + acc1 *= nums[i]; + acc2 *= nums[j]; + } - return answer; - } + return answer; + } }; diff --git a/Problems/0239.cpp b/Problems/0239.cpp @@ -1,17 +1,19 @@ class Solution { -public: - vector<int> maxSlidingWindow(vector<int> &nums, int k) { - int n = nums.size(); - vector<int> res; - deque<int> q; + public: + vector<int> maxSlidingWindow(vector<int> &nums, int k) { + int n = nums.size(); + vector<int> res; + deque<int> q; - res.reserve(n - k + 1); - for (int i = 0; i < n; i++) { - while (!q.empty() && q.front() < i - k + 1) q.pop_front(); - while (!q.empty() && nums[q.back()] < nums[i]) q.pop_back(); - q.push_back(i); - if (i >= k - 1) res.push_back(nums[q.front()]); + res.reserve(n - k + 1); + for (int i = 0; i < n; i++) { + while (!q.empty() && q.front() < i - k + 1) + q.pop_front(); + while (!q.empty() && nums[q.back()] < nums[i]) + q.pop_back(); + q.push_back(i); + if (i >= k - 1) res.push_back(nums[q.front()]); + } + return res; } - return res; - } }; diff --git a/Problems/0240.cpp b/Problems/0240.cpp @@ -1,14 +1,14 @@ class Solution { -public: - bool searchMatrix(vector<vector<int>> &matrix, int target) { - int n = matrix.size(), m = matrix[0].size(), x = 0, y = m - 1; - while (x < n && y >= 0) { - if (matrix[x][y] == target) return true; - if (matrix[x][y] > target) - y--; - else - x++; + public: + bool searchMatrix(vector<vector<int>> &matrix, int target) { + int n = matrix.size(), m = matrix[0].size(), x = 0, y = m - 1; + while (x < n && y >= 0) { + if (matrix[x][y] == target) return true; + if (matrix[x][y] > target) + y--; + else + x++; + } + return false; } - return false; - } }; diff --git a/Problems/0241.cpp b/Problems/0241.cpp @@ -1,27 +1,25 @@ class Solution { - int operate(char op, int a, int b) { - switch (op) { - case '+': return a + b; - case '-': return a - b; - case '*': return a * b; + int operate(char op, int a, int b) { + switch (op) { + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + } + return 0; } - return 0; - } - vector<int> rec(const string &expression, int start, int end) { - vector<int> res; - for (int i = start; i < end; i++) { - if (isdigit(expression[i])) continue; - for (auto n1 : rec(expression, start, i)) - for (auto n2 : rec(expression, i + 1, end)) - res.push_back(operate(expression[i], n1, n2)); + vector<int> rec(const string &expression, int start, int end) { + vector<int> res; + for (int i = start; i < end; i++) { + if (isdigit(expression[i])) continue; + for (auto n1 : rec(expression, start, i)) + for (auto n2 : rec(expression, i + 1, end)) + res.push_back(operate(expression[i], n1, n2)); + } + if (res.empty()) return {stoi(expression.substr(start, end - start))}; + return res; } - if (res.empty()) return {stoi(expression.substr(start, end - start))}; - return res; - } -public: - vector<int> diffWaysToCompute(const string &expression) { - return rec(expression, 0, expression.size()); - } + public: + vector<int> diffWaysToCompute(const string &expression) { return rec(expression, 0, expression.size()); } }; diff --git a/Problems/0242.cpp b/Problems/0242.cpp @@ -1,14 +1,15 @@ class Solution { -public: - bool isAnagram(string s, string t) { - if (s.size() != t.size()) return false; - vector<int> um(26, 0); - for (char c : s) um[c - 'a']++; - for (char c : t) - if (!um[c - 'a']) - return false; - else - um[c - 'a']--; - return true; - } + public: + bool isAnagram(string s, string t) { + if (s.size() != t.size()) return false; + vector<int> um(26, 0); + for (char c : s) + um[c - 'a']++; + for (char c : t) + if (!um[c - 'a']) + return false; + else + um[c - 'a']--; + return true; + } }; diff --git a/Problems/0257.cpp b/Problems/0257.cpp @@ -1,24 +1,23 @@ class Solution { -public: - vector<string> binaryTreePaths(TreeNode *root) { - if (!root) return {}; + public: + vector<string> binaryTreePaths(TreeNode *root) { + if (!root) return {}; - vector<string> res; - stack<pair<TreeNode *, string>> st; - st.push({root, to_string(root->val)}); - while (!st.empty()) { - TreeNode *root = st.top().first; - string s = st.top().second; - st.pop(); - if (!root->left && !root->right) - res.push_back(s); - else { - s += "->"; - if (root->left) st.push({root->left, s + to_string(root->left->val)}); - if (root->right) - st.push({root->right, s + to_string(root->right->val)}); - } + vector<string> res; + stack<pair<TreeNode *, string>> st; + st.push({root, to_string(root->val)}); + while (!st.empty()) { + TreeNode *root = st.top().first; + string s = st.top().second; + st.pop(); + if (!root->left && !root->right) + res.push_back(s); + else { + s += "->"; + if (root->left) st.push({root->left, s + to_string(root->left->val)}); + if (root->right) st.push({root->right, s + to_string(root->right->val)}); + } + } + return res; } - return res; - } }; diff --git a/Problems/0258.cpp b/Problems/0258.cpp @@ -1,11 +1,13 @@ class Solution { -public: - int addDigits(int num) { - while (num >= 10) { - int sum = 0; - do { sum += num % 10; } while ((num /= 10) > 0); - num = sum; + public: + int addDigits(int num) { + while (num >= 10) { + int sum = 0; + do { + sum += num % 10; + } while ((num /= 10) > 0); + num = sum; + } + return num; } - return num; - } }; diff --git a/Problems/0263.cpp b/Problems/0263.cpp @@ -1,10 +1,11 @@ class Solution { -public: - bool isUgly(int n) { - if (n <= 0) return false; - for (auto i : {2, 3, 5}) - while (n % i == 0) n /= i; + public: + bool isUgly(int n) { + if (n <= 0) return false; + for (auto i : {2, 3, 5}) + while (n % i == 0) + n /= i; - return n == 1; - } + return n == 1; + } }; diff --git a/Problems/0264.cpp b/Problems/0264.cpp @@ -1,41 +1,41 @@ // Brute force solution class Solution { -public: - int nthUglyNumber(int n) { - priority_queue<long long, vector<long long>, greater<long long>> pq; - unordered_set<long long> us; - int count; + public: + int nthUglyNumber(int n) { + priority_queue<long long, vector<long long>, greater<long long>> pq; + unordered_set<long long> us; + int count; - pq.push(1); - count = 1; - while (!pq.empty() && count < n) { - long long n = pq.top(); - pq.pop(); - for (int i : {2, 3, 5}) { - if (us.count(n * i)) continue; - pq.push(n * i); - us.insert(n * i); - } - count++; - } + pq.push(1); + count = 1; + while (!pq.empty() && count < n) { + long long n = pq.top(); + pq.pop(); + for (int i : {2, 3, 5}) { + if (us.count(n * i)) continue; + pq.push(n * i); + us.insert(n * i); + } + count++; + } - return (int)pq.top(); - } + return (int)pq.top(); + } }; // DP solution class Solution { -public: - int nthUglyNumber(int n) { - vector<int> k(n); - k[0] = 1; - int t2 = 0, t3 = 0, t5 = 0; - for (int i = 1; i < n; i++) { - k[i] = min(k[t2] * 2, min(k[t3] * 3, k[t5] * 5)); - t2 += k[i] == k[t2] * 2; - t3 += k[i] == k[t3] * 3; - t5 += k[i] == k[t5] * 5; + public: + int nthUglyNumber(int n) { + vector<int> k(n); + k[0] = 1; + int t2 = 0, t3 = 0, t5 = 0; + for (int i = 1; i < n; i++) { + k[i] = min(k[t2] * 2, min(k[t3] * 3, k[t5] * 5)); + t2 += k[i] == k[t2] * 2; + t3 += k[i] == k[t3] * 3; + t5 += k[i] == k[t5] * 5; + } + return k.back(); } - return k.back(); - } }; diff --git a/Problems/0268.cpp b/Problems/0268.cpp @@ -1,8 +1,9 @@ class Solution { -public: - int missingNumber(vector<int> &nums) { - int res = nums.size(); - for (int i = 0; i < nums.size(); i++) res ^= i ^ nums[i]; - return res; - } + public: + int missingNumber(vector<int> &nums) { + int res = nums.size(); + for (int i = 0; i < nums.size(); i++) + res ^= i ^ nums[i]; + return res; + } }; diff --git a/Problems/0274.cpp b/Problems/0274.cpp @@ -1,19 +1,20 @@ class Solution { - static int arr[5001]; + static int arr[5001]; -public: - int hIndex(vector<int> &citations) { - memset(arr, 0x00, sizeof(arr)); - for (int n : citations) arr[n]++; + public: + int hIndex(vector<int> &citations) { + memset(arr, 0x00, sizeof(arr)); + for (int n : citations) + arr[n]++; - int total = 0; - for (int i = 5000; i >= 0; i--) { - total += arr[i]; - if (total >= i) return i; - } + int total = 0; + for (int i = 5000; i >= 0; i--) { + total += arr[i]; + if (total >= i) return i; + } - return -1; - } + return -1; + } }; int Solution::arr[5001] = {0}; diff --git a/Problems/0278.cpp b/Problems/0278.cpp @@ -2,16 +2,16 @@ // bool isBadVersion(int version); class Solution { -public: - int firstBadVersion(int n) { - int low = 1, high = n, last = -1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (isBadVersion(mid)) - high = (last = mid) - 1; - else - low = mid + 1; + public: + int firstBadVersion(int n) { + int low = 1, high = n, last = -1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (isBadVersion(mid)) + high = (last = mid) - 1; + else + low = mid + 1; + } + return last; } - return last; - } }; diff --git a/Problems/0279.cpp b/Problems/0279.cpp @@ -1,16 +1,17 @@ class Solution { -public: - int numSquares(int n) { - vector<int> dp(n + 1, INT_MAX - 1); - vector<int> primes; + public: + int numSquares(int n) { + vector<int> dp(n + 1, INT_MAX - 1); + vector<int> primes; - for (int i = 1; i <= sqrt(n); i++) primes.push_back(i * i); + for (int i = 1; i <= sqrt(n); i++) + primes.push_back(i * i); - dp[0] = 0; - for (int i = 1; i <= n; i++) - for (int j = 0; j < primes.size() && primes[j] <= i; j++) - dp[i] = min(dp[i], dp[i - primes[j]] + 1); + dp[0] = 0; + for (int i = 1; i <= n; i++) + for (int j = 0; j < primes.size() && primes[j] <= i; j++) + dp[i] = min(dp[i], dp[i - primes[j]] + 1); - return dp[n]; - } + return dp[n]; + } }; diff --git a/Problems/0283.cpp b/Problems/0283.cpp @@ -1,10 +1,11 @@ class Solution { -public: - void moveZeroes(vector<int> &nums) { - int j = 0; - for (int i = 0; i < nums.size(); i++) - if (nums[i] != 0) nums[j++] = nums[i]; + public: + void moveZeroes(vector<int> &nums) { + int j = 0; + for (int i = 0; i < nums.size(); i++) + if (nums[i] != 0) nums[j++] = nums[i]; - while (j < nums.size()) nums[j++] = 0; - } + while (j < nums.size()) + nums[j++] = 0; + } }; diff --git a/Problems/0287.cpp b/Problems/0287.cpp @@ -1,18 +1,18 @@ class Solution { -public: - int findDuplicate(vector<int> &nums) { - int slow = 0, fast = 0; - while (true) { - fast = nums[nums[fast]]; - slow = nums[slow]; - if (fast == slow) { - fast = 0; - while (fast != slow) { - fast = nums[fast]; - slow = nums[slow]; + public: + int findDuplicate(vector<int> &nums) { + int slow = 0, fast = 0; + while (true) { + fast = nums[nums[fast]]; + slow = nums[slow]; + if (fast == slow) { + fast = 0; + while (fast != slow) { + fast = nums[fast]; + slow = nums[slow]; + } + return fast; + } } - return fast; - } } - } }; diff --git a/Problems/0289.cpp b/Problems/0289.cpp @@ -1,22 +1,22 @@ class Solution { -public: - void gameOfLife(vector<vector<int>> &board) { - int n = board.size(), m = board[0].size(); - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - int add = (board[i][j] & 1) << 1; - for (int k = max(i - 1, 0); k <= min(n - 1, i + 1); k++) { - for (int l = max(j - 1, 0); l <= min(m - 1, j + 1); l++) { - board[k][l] += add; - } + public: + void gameOfLife(vector<vector<int>> &board) { + int n = board.size(), m = board[0].size(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + int add = (board[i][j] & 1) << 1; + for (int k = max(i - 1, 0); k <= min(n - 1, i + 1); k++) { + for (int l = max(j - 1, 0); l <= min(m - 1, j + 1); l++) { + board[k][l] += add; + } + } + } } - } - } - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - board[i][j] = board[i][j] == 7 || board[i][j] == 9 || board[i][j] == 6; - } + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + board[i][j] = board[i][j] == 7 || board[i][j] == 9 || board[i][j] == 6; + } + } } - } }; diff --git a/Problems/0290.cpp b/Problems/0290.cpp @@ -1,22 +1,22 @@ class Solution { -public: - bool wordPattern(string pattern, string s) { - vector<string> done(26, ""); - unordered_set<string> st; + public: + bool wordPattern(string pattern, string s) { + vector<string> done(26, ""); + unordered_set<string> st; - int c = 0; - istringstream in(s); - for (string crnt; in >> crnt; ++c) { - if (c >= pattern.size()) return false; - int index = pattern[c] - 'a'; - if (done[index].empty()) { - if (st.count(crnt)) return false; - st.insert(done[index] = crnt); - } else if (done[index] != crnt) - return false; - } - if (pattern.size() > c) return false; + int c = 0; + istringstream in(s); + for (string crnt; in >> crnt; ++c) { + if (c >= pattern.size()) return false; + int index = pattern[c] - 'a'; + if (done[index].empty()) { + if (st.count(crnt)) return false; + st.insert(done[index] = crnt); + } else if (done[index] != crnt) + return false; + } + if (pattern.size() > c) return false; - return true; - } + return true; + } }; diff --git a/Problems/0292.cpp b/Problems/0292.cpp @@ -1,4 +1,4 @@ class Solution { -public: - bool canWinNim(int n) { return n % 4; } + public: + bool canWinNim(int n) { return n % 4; } }; diff --git a/Problems/0295.cpp b/Problems/0295.cpp @@ -1,31 +1,31 @@ class MedianFinder { - priority_queue<int> left; - priority_queue<int, vector<int>, greater<int>> right; + priority_queue<int> left; + priority_queue<int, vector<int>, greater<int>> right; -public: - void addNum(int num) { - if (left.empty() || num < left.top()) - left.push(num); - else - right.push(num); + public: + void addNum(int num) { + if (left.empty() || num < left.top()) + left.push(num); + else + right.push(num); - if (left.size() < right.size()) { - int temp = right.top(); - right.pop(); - left.push(temp); - } + if (left.size() < right.size()) { + int temp = right.top(); + right.pop(); + left.push(temp); + } - if (left.size() - right.size() > 1) { - int temp = left.top(); - left.pop(); - right.push(temp); + if (left.size() - right.size() > 1) { + int temp = left.top(); + left.pop(); + right.push(temp); + } } - } - double findMedian() { - if (left.size() > right.size()) - return left.top(); - else - return (left.top() + right.top()) * 0.5; - } + double findMedian() { + if (left.size() > right.size()) + return left.top(); + else + return (left.top() + right.top()) * 0.5; + } }; diff --git a/Problems/0297.cpp b/Problems/0297.cpp @@ -1,41 +1,41 @@ class Codec { -public: - string serialize(TreeNode *root) { - ostringstream out; - serialize(root, out); - return out.str(); - } + public: + string serialize(TreeNode *root) { + ostringstream out; + serialize(root, out); + return out.str(); + } - TreeNode *deserialize(string data) { - istringstream in(data); - return deserialize(in); - } + TreeNode *deserialize(string data) { + istringstream in(data); + return deserialize(in); + } -private: - void serialize(TreeNode *root, ostringstream &out) { - stack<TreeNode *> st; + private: + void serialize(TreeNode *root, ostringstream &out) { + stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (!root) - out << "# "; - else { - out << root->val << ' '; - st.push(root->right); - st.push(root->left); - } + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (!root) + out << "# "; + else { + out << root->val << ' '; + st.push(root->right); + st.push(root->left); + } + } } - } - TreeNode *deserialize(istringstream &in) { - string val; - in >> val; - if (val == "#") return nullptr; - TreeNode *root = new TreeNode(stoi(val)); - root->left = deserialize(in); - root->right = deserialize(in); - return root; - } + TreeNode *deserialize(istringstream &in) { + string val; + in >> val; + if (val == "#") return nullptr; + TreeNode *root = new TreeNode(stoi(val)); + root->left = deserialize(in); + root->right = deserialize(in); + return root; + } }; diff --git a/Problems/0299.cpp b/Problems/0299.cpp @@ -1,21 +1,21 @@ class Solution { -public: - string getHint(string secret, string guess) { - int n = secret.size(), cows = 0, bulls = 0; - unordered_map<char, int> ums; - for (int i = 0; i < n; i++) - if (guess[i] == secret[i]) - bulls++; - else - ums[secret[i]]++; + public: + string getHint(string secret, string guess) { + int n = secret.size(), cows = 0, bulls = 0; + unordered_map<char, int> ums; + for (int i = 0; i < n; i++) + if (guess[i] == secret[i]) + bulls++; + else + ums[secret[i]]++; - for (int i = 0; i < n; i++) { - if (guess[i] == secret[i]) - continue; - else if (ums[guess[i]] > 0) - cows++; - ums[guess[i]]--; + for (int i = 0; i < n; i++) { + if (guess[i] == secret[i]) + continue; + else if (ums[guess[i]] > 0) + cows++; + ums[guess[i]]--; + } + return to_string(bulls) + "A" + to_string(cows) + "B"; } - return to_string(bulls) + "A" + to_string(cows) + "B"; - } }; diff --git a/Problems/0300.cpp b/Problems/0300.cpp @@ -1,3 +1 @@ -Formating: Problems/0152.cpp -Formating: Problems/0300.cpp -Formating: Problems/1567.cpp +Formating : Problems / 0152.cpp Formating : Problems / 0300.cpp Formating : Problems / 1567.cpp diff --git a/Problems/0304.cpp b/Problems/0304.cpp @@ -1,26 +1,26 @@ class NumMatrix { - int n, m; - vector<vector<int>> dp; + int n, m; + vector<vector<int>> dp; -public: - NumMatrix(vector<vector<int>> &matrix) - : n(matrix.size()), m(matrix[0].size()), - dp(vector<vector<int>>(n, vector<int>(m, 0))) { - for (int i = 0, sum = 0; i < n; i++) sum = dp[i][0] = matrix[i][0] + sum; - for (int i = 0, sum = 0; i < m; i++) sum = dp[0][i] = matrix[0][i] + sum; - for (int i = 1; i < n; i++) { - for (int j = 1; j < m; j++) { - dp[i][j] = - matrix[i][j] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]; - } + public: + NumMatrix(vector<vector<int>> &matrix) + : n(matrix.size()), m(matrix[0].size()), dp(vector<vector<int>>(n, vector<int>(m, 0))) { + for (int i = 0, sum = 0; i < n; i++) + sum = dp[i][0] = matrix[i][0] + sum; + for (int i = 0, sum = 0; i < m; i++) + sum = dp[0][i] = matrix[0][i] + sum; + for (int i = 1; i < n; i++) { + for (int j = 1; j < m; j++) { + dp[i][j] = matrix[i][j] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]; + } + } } - } - int sumRegion(int x1, int y1, int x2, int y2) { - int res = dp[x2][y2]; - if (x1 > 0) res -= dp[x1 - 1][y2]; - if (y1 > 0) res -= dp[x2][y1 - 1]; - if (x1 > 0 && y1 > 0) res += dp[x1 - 1][y1 - 1]; - return res; - } + int sumRegion(int x1, int y1, int x2, int y2) { + int res = dp[x2][y2]; + if (x1 > 0) res -= dp[x1 - 1][y2]; + if (y1 > 0) res -= dp[x2][y1 - 1]; + if (x1 > 0 && y1 > 0) res += dp[x1 - 1][y1 - 1]; + return res; + } }; diff --git a/Problems/0306.cpp b/Problems/0306.cpp @@ -1,26 +1,25 @@ class Solution { -public: - bool isAdditiveNumber(const string &num) { - for (int i = 1; i < num.size(); i++) { - long num1 = stol(num.substr(0, i)); - for (int j = i + 1; j < num.size(); j++) { - long n1 = num1, n2 = stol(num.substr(i, j - i)), n3; - int next = j; - while (next < num.size()) { - const string pre = to_string(n3 = n1 + n2); + public: + bool isAdditiveNumber(const string &num) { + for (int i = 1; i < num.size(); i++) { + long num1 = stol(num.substr(0, i)); + for (int j = i + 1; j < num.size(); j++) { + long n1 = num1, n2 = stol(num.substr(i, j - i)), n3; + int next = j; + while (next < num.size()) { + const string pre = to_string(n3 = n1 + n2); - auto res = - std::mismatch(pre.begin(), pre.end(), num.substr(next).begin()); - if (res.first != pre.end()) break; + auto res = std::mismatch(pre.begin(), pre.end(), num.substr(next).begin()); + if (res.first != pre.end()) break; - next += pre.size(); - n1 = n2, n2 = n3; + next += pre.size(); + n1 = n2, n2 = n3; + } + if (next == num.size()) return true; + if (num[i] == '0') break; + } + if (num[0] == '0') break; } - if (next == num.size()) return true; - if (num[i] == '0') break; - } - if (num[0] == '0') break; + return false; } - return false; - } }; diff --git a/Problems/0309.cpp b/Problems/0309.cpp @@ -1,2 +1 @@ -Formating: Problems/0309.cpp -Formating: Problems/0714.cpp +Formating : Problems / 0309.cpp Formating : Problems / 0714.cpp diff --git a/Problems/0310.cpp b/Problems/0310.cpp @@ -1,37 +1,37 @@ class Solution { -public: - vector<int> findMinHeightTrees(int n, vector<vector<int>> &edges) { - if (n == 0) return {}; - if (n == 1) return {0}; - if (n == 2) return {0, 1}; + public: + vector<int> findMinHeightTrees(int n, vector<vector<int>> &edges) { + if (n == 0) return {}; + if (n == 1) return {0}; + if (n == 2) return {0, 1}; - vector<set<int>> adj(n); - vector<int> count(n); + vector<set<int>> adj(n); + vector<int> count(n); - for (auto &e : edges) { - adj[e[0]].insert(e[1]); - adj[e[1]].insert(e[0]); - count[e[0]]++; - count[e[1]]++; - } + for (auto &e : edges) { + adj[e[0]].insert(e[1]); + adj[e[1]].insert(e[0]); + count[e[0]]++; + count[e[1]]++; + } - queue<int> q; - for (int i = 0; i < n; i++) - if (count[i] == 1) q.push(i); + queue<int> q; + for (int i = 0; i < n; i++) + if (count[i] == 1) q.push(i); - vector<int> res; - while (!q.empty()) { - res.clear(); - for (int k = q.size(); k > 0; k--) { - int c = q.front(); - q.pop(); - res.push_back(c); - for (int n : adj[c]) { - if (--count[n] == 1) q.push(n); + vector<int> res; + while (!q.empty()) { + res.clear(); + for (int k = q.size(); k > 0; k--) { + int c = q.front(); + q.pop(); + res.push_back(c); + for (int n : adj[c]) { + if (--count[n] == 1) q.push(n); + } + } } - } - } - return res; - } + return res; + } }; diff --git a/Problems/0319.cpp b/Problems/0319.cpp @@ -1,4 +1,4 @@ class Solution { -public: - int bulbSwitch(int n) { return sqrt(n); } + public: + int bulbSwitch(int n) { return sqrt(n); } }; diff --git a/Problems/0322.cpp b/Problems/0322.cpp @@ -1,16 +1,15 @@ // DP solution class Solution { -public: - int coinChange(vector<int> &coins, int amount) { - vector<int> dp(amount + 1, INT_MAX); - dp[0] = 0; + public: + int coinChange(vector<int> &coins, int amount) { + vector<int> dp(amount + 1, INT_MAX); + dp[0] = 0; - for (int i = 0; i < amount; i++) { - if (dp[i] == INT_MAX) continue; - for (int coin : coins) - if ((long long)coin + i <= amount) - dp[coin + i] = min(dp[coin + i], dp[i] + 1); + for (int i = 0; i < amount; i++) { + if (dp[i] == INT_MAX) continue; + for (int coin : coins) + if ((long long)coin + i <= amount) dp[coin + i] = min(dp[coin + i], dp[i] + 1); + } + return dp[amount] != INT_MAX ? dp[amount] : -1; } - return dp[amount] != INT_MAX ? dp[amount] : -1; - } }; diff --git a/Problems/0326.cpp b/Problems/0326.cpp @@ -1,7 +1,7 @@ class Solution { -public: - bool isPowerOfThree(int n) { - double x = log10(n) / log10(3); - return n > 0 && x == round(x); - } + public: + bool isPowerOfThree(int n) { + double x = log10(n) / log10(3); + return n > 0 && x == round(x); + } }; diff --git a/Problems/0328.cpp b/Problems/0328.cpp @@ -1,18 +1,18 @@ class Solution { -public: - ListNode *oddEvenList(ListNode *head) { - if (!head) return nullptr; + public: + ListNode *oddEvenList(ListNode *head) { + if (!head) return nullptr; - ListNode *h, *t, *p; - t = h = new ListNode(); + ListNode *h, *t, *p; + t = h = new ListNode(); - for (p = head; p && p->next;) { - t = t->next = p->next; - p->next = p->next->next; - if (p->next) p = p->next; + for (p = head; p && p->next;) { + t = t->next = p->next; + p->next = p->next->next; + if (p->next) p = p->next; + } + p->next = h->next; + t->next = nullptr; + return head; } - p->next = h->next; - t->next = nullptr; - return head; - } }; diff --git a/Problems/0334.cpp b/Problems/0334.cpp @@ -1,15 +1,15 @@ class Solution { -public: - bool increasingTriplet(vector<int> &nums) { - int a = INT_MAX, b = INT_MAX; - for (int x : nums) { - if (x <= a) - a = x; - else if (x <= b) - b = x; - else - return true; + public: + bool increasingTriplet(vector<int> &nums) { + int a = INT_MAX, b = INT_MAX; + for (int x : nums) { + if (x <= a) + a = x; + else if (x <= b) + b = x; + else + return true; + } + return false; } - return false; - } }; diff --git a/Problems/0338.cpp b/Problems/0338.cpp @@ -1,12 +1,12 @@ class Solution { -public: - vector<int> countBits(int n) { - vector<int> res(n + 1); - int offset = 1; - for (int i = 1; i <= n; i++) { - if (offset * 2 == i) offset *= 2; - res[i] = (res[i - offset]) + 1; + public: + vector<int> countBits(int n) { + vector<int> res(n + 1); + int offset = 1; + for (int i = 1; i <= n; i++) { + if (offset * 2 == i) offset *= 2; + res[i] = (res[i - offset]) + 1; + } + return res; } - return res; - } }; diff --git a/Problems/0342.cpp b/Problems/0342.cpp @@ -1,6 +1,4 @@ class Solution { -public: - bool isPowerOfFour(int n) { - return n > 0 && (n & (n - 1)) == 0 && (n - 1) % 3 == 0; - } + public: + bool isPowerOfFour(int n) { return n > 0 && (n & (n - 1)) == 0 && (n - 1) % 3 == 0; } }; diff --git a/Problems/0343.cpp b/Problems/0343.cpp @@ -1,13 +1,13 @@ class Solution { -public: - int integerBreak(int n) { - if (n == 2) return 1; - if (n == 3) return 2; + public: + int integerBreak(int n) { + if (n == 2) return 1; + if (n == 3) return 2; - if (n % 3 == 0) - return pow(3, n / 3); - else if (n % 3 == 1) - return pow(3, n / 3 - 1) * 4; - return pow(3, n / 3) * (n % 3); - } + if (n % 3 == 0) + return pow(3, n / 3); + else if (n % 3 == 1) + return pow(3, n / 3 - 1) * 4; + return pow(3, n / 3) * (n % 3); + } }; diff --git a/Problems/0344.cpp b/Problems/0344.cpp @@ -1,7 +1,8 @@ class Solution { -public: - void reverseString(vector<char> &s) { - int i = 0, j = (int)s.size() - 1; - while (i < j) swap(s[i++], s[j--]); - } + public: + void reverseString(vector<char> &s) { + int i = 0, j = (int)s.size() - 1; + while (i < j) + swap(s[i++], s[j--]); + } }; diff --git a/Problems/0345.cpp b/Problems/0345.cpp @@ -1,20 +1,22 @@ class Solution { - bool is_vowel(char c) { - c = tolower(c); - return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; - } + bool is_vowel(char c) { + c = tolower(c); + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; + } -public: - string reverseVowels(string s) { - int i = 0, j = size(s) - 1; - while (i < j) { - while (i < j && !is_vowel(s[i])) i++; - while (i < j && !is_vowel(s[j])) j--; - if (i >= j) break; - swap(s[i], s[j]); - i++; - j--; + public: + string reverseVowels(string s) { + int i = 0, j = size(s) - 1; + while (i < j) { + while (i < j && !is_vowel(s[i])) + i++; + while (i < j && !is_vowel(s[j])) + j--; + if (i >= j) break; + swap(s[i], s[j]); + i++; + j--; + } + return s; } - return s; - } }; diff --git a/Problems/0347.cpp b/Problems/0347.cpp @@ -1,29 +1,27 @@ struct elem { - static void reset() { id_cnt = 0; } - static int id_cnt; - int id = id_cnt++, count = 0; - void operator++(int) { count++; } - friend bool operator<(const elem &e1, const elem &e2) { - return e1.count > e2.count; - } - friend ostream &operator<<(ostream &os, const elem &e) { - return os << e.id << ": " << e.count; - } + static void reset() { id_cnt = 0; } + static int id_cnt; + int id = id_cnt++, count = 0; + void operator++(int) { count++; } + friend bool operator<(const elem &e1, const elem &e2) { return e1.count > e2.count; } + friend ostream &operator<<(ostream &os, const elem &e) { return os << e.id << ": " << e.count; } }; int elem::id_cnt = 0; class Solution { - const int size = 20002; - const int mod = 10000; + const int size = 20002; + const int mod = 10000; -public: - vector<int> topKFrequent(vector<int> &nums, int k) { - elem::reset(); - vector<elem> um(size); - for (int n : nums) um[n + mod]++; - sort(um.begin(), um.end()); - vector<int> res; - for (int i = 0; i < k; i++) res.push_back(um[i].id - mod); - return res; - } + public: + vector<int> topKFrequent(vector<int> &nums, int k) { + elem::reset(); + vector<elem> um(size); + for (int n : nums) + um[n + mod]++; + sort(um.begin(), um.end()); + vector<int> res; + for (int i = 0; i < k; i++) + res.push_back(um[i].id - mod); + return res; + } }; diff --git a/Problems/0350.cpp b/Problems/0350.cpp @@ -1,15 +1,15 @@ class Solution { -public: - vector<int> intersect(vector<int> &nums1, vector<int> &nums2) { - unordered_multiset<int> s(nums1.begin(), nums1.end()); + public: + vector<int> intersect(vector<int> &nums1, vector<int> &nums2) { + unordered_multiset<int> s(nums1.begin(), nums1.end()); - vector<int> res; - for (int n : nums2) { - const auto it = s.find(n); - if (it == s.end()) continue; - s.erase(it); - res.push_back(n); + vector<int> res; + for (int n : nums2) { + const auto it = s.find(n); + if (it == s.end()) continue; + s.erase(it); + res.push_back(n); + } + return res; } - return res; - } }; diff --git a/Problems/0352.cpp b/Problems/0352.cpp @@ -1 +1 @@ -Formating: Problems/0352.cpp +Formating : Problems / 0352.cpp diff --git a/Problems/0367.cpp b/Problems/0367.cpp @@ -1,4 +1,4 @@ class Solution { -public: - bool isPerfectSquare(int num) { return pow((int)sqrt(num), 2) == num; } + public: + bool isPerfectSquare(int num) { return pow((int)sqrt(num), 2) == num; } }; diff --git a/Problems/0371.cpp b/Problems/0371.cpp @@ -1,12 +1,12 @@ class Solution { -public: - int getSum(int a, int b) { - unsigned c; - while (b) { - c = a & b; - a ^= b; - b = c << 1; + public: + int getSum(int a, int b) { + unsigned c; + while (b) { + c = a & b; + a ^= b; + b = c << 1; + } + return a; } - return a; - } }; diff --git a/Problems/0373.cpp b/Problems/0373.cpp @@ -1,23 +1,22 @@ class Solution { - typedef tuple<int, int, int> tpl; + typedef tuple<int, int, int> tpl; -public: - vector<vector<int>> kSmallestPairs(const vector<int> &nums1, - const vector<int> &nums2, int k) { - priority_queue<tpl, vector<tpl>, greater<tpl>> pq; - vector<vector<int>> res; - res.reserve(k); + public: + vector<vector<int>> kSmallestPairs(const vector<int> &nums1, const vector<int> &nums2, int k) { + priority_queue<tpl, vector<tpl>, greater<tpl>> pq; + vector<vector<int>> res; + res.reserve(k); - for (int i = 0; i < min(k, (int)nums1.size()); i++) - pq.push({nums1[i] + nums2[0], i, 0}); + for (int i = 0; i < min(k, (int)nums1.size()); i++) + pq.push({nums1[i] + nums2[0], i, 0}); - while (k-- && !pq.empty()) { - auto [sum, i, j] = pq.top(); - pq.pop(); - res.push_back({nums1[i], nums2[j]}); - if (j == nums2.size() - 1) continue; - pq.push({nums1[i] + nums2[j + 1], i, j + 1}); + while (k-- && !pq.empty()) { + auto [sum, i, j] = pq.top(); + pq.pop(); + res.push_back({nums1[i], nums2[j]}); + if (j == nums2.size() - 1) continue; + pq.push({nums1[i] + nums2[j + 1], i, j + 1}); + } + return res; } - return res; - } }; diff --git a/Problems/0374.cpp b/Problems/0374.cpp @@ -1,16 +1,16 @@ class Solution { -public: - int guessNumber(int n) { - int low = 1, high = n; - while (true) { - int mid = low + (high - low) / 2; - switch (guess(mid)) { - case 0: return mid; - case 1: low = mid + 1; break; - case -1: high = mid - 1; break; - default: return -1; - } + public: + int guessNumber(int n) { + int low = 1, high = n; + while (true) { + int mid = low + (high - low) / 2; + switch (guess(mid)) { + case 0: return mid; + case 1: low = mid + 1; break; + case -1: high = mid - 1; break; + default: return -1; + } + } + return -1; } - return -1; - } }; diff --git a/Problems/0376.cpp b/Problems/0376.cpp @@ -1,14 +1,14 @@ class Solution { -public: - int wiggleMaxLength(vector<int> &nums) { - if (nums.size() == 0) return 0; - int up = 1, down = 1; - for (int i = 1; i < nums.size(); i++) { - if (nums[i] < nums[i - 1]) - down = up + 1; - else if (nums[i] > nums[i - 1]) - up = down + 1; + public: + int wiggleMaxLength(vector<int> &nums) { + if (nums.size() == 0) return 0; + int up = 1, down = 1; + for (int i = 1; i < nums.size(); i++) { + if (nums[i] < nums[i - 1]) + down = up + 1; + else if (nums[i] > nums[i - 1]) + up = down + 1; + } + return max(up, down); } - return max(up, down); - } }; diff --git a/Problems/0377.cpp b/Problems/0377.cpp @@ -1,13 +1,13 @@ class Solution { -public: - int combinationSum4(vector<int> &nums, int target) { - vector<long long> dp(target + 1, 0); - dp[0] = 1; + public: + int combinationSum4(vector<int> &nums, int target) { + vector<long long> dp(target + 1, 0); + dp[0] = 1; - for (int i = 1; i <= target; i++) - for (int num : nums) - if (i - num >= 0) dp[i] = (dp[i] + dp[i - num]) % INT_MAX; + for (int i = 1; i <= target; i++) + for (int num : nums) + if (i - num >= 0) dp[i] = (dp[i] + dp[i - num]) % INT_MAX; - return dp.back(); - } + return dp.back(); + } }; diff --git a/Problems/0382.cpp b/Problems/0382.cpp @@ -1,16 +1,18 @@ class Solution { - ListNode *head = nullptr; - int size = 0; + ListNode *head = nullptr; + int size = 0; -public: - Solution(ListNode *head) : head(head) { - for (ListNode *p = head; p; p = p->next) size++; - } + public: + Solution(ListNode *head) : head(head) { + for (ListNode *p = head; p; p = p->next) + size++; + } - int getRandom() { - int elem = rand() % size; - ListNode *p = head; - while (elem--) p = p->next; - return p->val; - } + int getRandom() { + int elem = rand() % size; + ListNode *p = head; + while (elem--) + p = p->next; + return p->val; + } }; diff --git a/Problems/0383.cpp b/Problems/0383.cpp @@ -1,13 +1,14 @@ class Solution { -public: - bool canConstruct(string ransomNote, string magazine) { - unordered_map<char, int> us; + public: + bool canConstruct(string ransomNote, string magazine) { + unordered_map<char, int> us; - for (char c : magazine) us[c]++; + for (char c : magazine) + us[c]++; - for (char c : ransomNote) - if (!us[c]--) return false; + for (char c : ransomNote) + if (!us[c]--) return false; - return true; - } + return true; + } }; diff --git a/Problems/0384.cpp b/Problems/0384.cpp @@ -1,14 +1,14 @@ class Solution { - const vector<int> og; - vector<int> shuffing; + const vector<int> og; + vector<int> shuffing; -public: - Solution(const vector<int> &nums) : og(nums), shuffing(nums) {} + public: + Solution(const vector<int> &nums) : og(nums), shuffing(nums) {} - vector<int> reset() { return og; } + vector<int> reset() { return og; } - vector<int> shuffle() { - random_shuffle(shuffing.begin(), shuffing.end()); - return shuffing; - } + vector<int> shuffle() { + random_shuffle(shuffing.begin(), shuffing.end()); + return shuffing; + } }; diff --git a/Problems/0387.cpp b/Problems/0387.cpp @@ -1,10 +1,11 @@ class Solution { -public: - int firstUniqChar(string s) { - vector<int> um(26, 0); - for (char c : s) um[c - 'a']++; - for (int i = 0; i < s.size(); i++) - if (um[s[i] - 'a'] == 1) return i; - return -1; - } + public: + int firstUniqChar(string s) { + vector<int> um(26, 0); + for (char c : s) + um[c - 'a']++; + for (int i = 0; i < s.size(); i++) + if (um[s[i] - 'a'] == 1) return i; + return -1; + } }; diff --git a/Problems/0392.cpp b/Problems/0392.cpp @@ -1,9 +1,9 @@ class Solution { -public: - bool isSubsequence(string s, string t) { - int i = 0; - for (int j = 0; j < t.size() && i < s.size(); j++) - if (s[i] == t[j]) i++; - return i == s.size(); - } + public: + bool isSubsequence(string s, string t) { + int i = 0; + for (int j = 0; j < t.size() && i < s.size(); j++) + if (s[i] == t[j]) i++; + return i == s.size(); + } }; diff --git a/Problems/0394.cpp b/Problems/0394.cpp @@ -1,30 +1,31 @@ class Solution { -public: - string decodeString(string s) { - stack<int> is; - stack<string> ss; + public: + string decodeString(string s) { + stack<int> is; + stack<string> ss; - ss.push(""); - for (int i = 0; i < s.size(); i++) { - if (isdigit(s[i])) { - int res = 0; - do { - res *= 10; - res += s[i] - '0'; - } while (isdigit(s[++i])); - is.push(res); ss.push(""); - } else if (s[i] == ']') { - string res = ""; - while (is.top()--) res += ss.top(); - is.pop(); - ss.pop(); - ss.top() += res; - } else { - ss.top() += s[i]; - } - } + for (int i = 0; i < s.size(); i++) { + if (isdigit(s[i])) { + int res = 0; + do { + res *= 10; + res += s[i] - '0'; + } while (isdigit(s[++i])); + is.push(res); + ss.push(""); + } else if (s[i] == ']') { + string res = ""; + while (is.top()--) + res += ss.top(); + is.pop(); + ss.pop(); + ss.top() += res; + } else { + ss.top() += s[i]; + } + } - return ss.top(); - } + return ss.top(); + } }; diff --git a/Problems/0399.cpp b/Problems/0399.cpp @@ -1,47 +1,45 @@ class Solution { - const int SIZE = 26 * 5; + const int SIZE = 26 * 5; - int hash(const string &st) { - static int index = 0; - static unordered_map<string, int> um; - if (!um.count(st)) um[st] = index++; - return um[st]; - } + int hash(const string &st) { + static int index = 0; + static unordered_map<string, int> um; + if (!um.count(st)) um[st] = index++; + return um[st]; + } - double dfs(vector<vector<pair<int, double>>> &adj, int start, int goal) { - stack<pair<int, double>> st; - vector<bool> visited(SIZE, false); + double dfs(vector<vector<pair<int, double>>> &adj, int start, int goal) { + stack<pair<int, double>> st; + vector<bool> visited(SIZE, false); - st.push({start, 1}); - visited[start] = true; - while (!st.empty()) { - auto [root, value] = st.top(); - st.pop(); - if (root == goal) return value; - visited[root] = true; - for (auto &v : adj[root]) - if (!visited[v.first]) st.push({v.first, value * v.second}); + st.push({start, 1}); + visited[start] = true; + while (!st.empty()) { + auto [root, value] = st.top(); + st.pop(); + if (root == goal) return value; + visited[root] = true; + for (auto &v : adj[root]) + if (!visited[v.first]) st.push({v.first, value * v.second}); + } + return -1; } - return -1; - } -public: - vector<double> calcEquation(vector<vector<string>> &equations, - vector<double> &values, - vector<vector<string>> &queries) { - vector<vector<pair<int, double>>> adj(SIZE, vector<pair<int, double>>()); - for (int i = 0; i < values.size(); i++) { - adj[hash(equations[i][0])].push_back({hash(equations[i][1]), values[i]}); - adj[hash(equations[i][1])].push_back( - {hash(equations[i][0]), 1 / values[i]}); - } + public: + vector<double> calcEquation(vector<vector<string>> &equations, vector<double> &values, + vector<vector<string>> &queries) { + vector<vector<pair<int, double>>> adj(SIZE, vector<pair<int, double>>()); + for (int i = 0; i < values.size(); i++) { + adj[hash(equations[i][0])].push_back({hash(equations[i][1]), values[i]}); + adj[hash(equations[i][1])].push_back({hash(equations[i][0]), 1 / values[i]}); + } - vector<double> res(queries.size(), -1); - for (int i = 0; i < queries.size(); i++) { - int start = hash(queries[i][0]), goal = hash(queries[i][1]); - if (adj[start].empty() || adj[goal].empty()) continue; - res[i] = dfs(adj, start, goal); + vector<double> res(queries.size(), -1); + for (int i = 0; i < queries.size(); i++) { + int start = hash(queries[i][0]), goal = hash(queries[i][1]); + if (adj[start].empty() || adj[goal].empty()) continue; + res[i] = dfs(adj, start, goal); + } + return res; } - return res; - } }; diff --git a/Problems/0402.cpp b/Problems/0402.cpp @@ -1,28 +1,30 @@ class Solution { - class Solution { - public: - string removeKdigits(string num, int k) { - if (num.length() <= k) return "0"; - if (k == 0) return num; + class Solution { + public: + string removeKdigits(string num, int k) { + if (num.length() <= k) return "0"; + if (k == 0) return num; - string res = ""; - stack<char> s; + string res = ""; + stack<char> s; - s.push(num[0]); - for (int i = 1; i < num.length(); ++i) { - while (k > 0 && !s.empty() && num[i] < s.top()) { - --k; - s.pop(); - } - s.push(num[i]); - if (s.size() == 1 && num[i] == '0') s.pop(); - } + s.push(num[0]); + for (int i = 1; i < num.length(); ++i) { + while (k > 0 && !s.empty() && num[i] < s.top()) { + --k; + s.pop(); + } + s.push(num[i]); + if (s.size() == 1 && num[i] == '0') s.pop(); + } - while (k && !s.empty()) --k, s.pop(); + while (k && !s.empty()) + --k, s.pop(); - while (!s.empty()) res.push_back(s.top()), s.pop(); + while (!s.empty()) + res.push_back(s.top()), s.pop(); - reverse(res.begin(), res.end()); - return res.size() ? res : "0"; - } - }; + reverse(res.begin(), res.end()); + return res.size() ? res : "0"; + } + }; diff --git a/Problems/0404.cpp b/Problems/0404.cpp @@ -1,23 +1,23 @@ class Solution { -public: - int sumOfLeftLeaves(TreeNode *root) { - if (!root) return 0; + public: + int sumOfLeftLeaves(TreeNode *root) { + if (!root) return 0; - int res = 0; - stack<TreeNode *> st; + int res = 0; + stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (root->left) { - if (!root->left->left && !root->left->right) - res += root->left->val; - else - st.push(root->left); - } - if (root->right) st.push(root->right); + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (root->left) { + if (!root->left->left && !root->left->right) + res += root->left->val; + else + st.push(root->left); + } + if (root->right) st.push(root->right); + } + return res; } - return res; - } }; diff --git a/Problems/0406.cpp b/Problems/0406.cpp @@ -1,12 +1,12 @@ class Solution { -public: - vector<vector<int>> reconstructQueue(vector<vector<int>> &people) { - sort(begin(people), end(people), [](const auto &a, const auto &b) { - return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]); - }); - vector<vector<int>> res; - res.reserve(people.size()); - for (const auto &p : people) res.insert(res.begin() + p[1], p); - return res; - } + public: + vector<vector<int>> reconstructQueue(vector<vector<int>> &people) { + sort(begin(people), end(people), + [](const auto &a, const auto &b) { return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]); }); + vector<vector<int>> res; + res.reserve(people.size()); + for (const auto &p : people) + res.insert(res.begin() + p[1], p); + return res; + } }; diff --git a/Problems/0409.cpp b/Problems/0409.cpp @@ -1,15 +1,16 @@ class Solution { -public: - int longestPalindrome(string s) { - unordered_map<char, int> um; - for (char c : s) um[c]++; + public: + int longestPalindrome(string s) { + unordered_map<char, int> um; + for (char c : s) + um[c]++; - int res = 0; - bool odd = false; - for (auto [c, v] : um) { - if (v % 2 && !odd) odd = true; - res += v / 2; + int res = 0; + bool odd = false; + for (auto [c, v] : um) { + if (v % 2 && !odd) odd = true; + res += v / 2; + } + return res * 2 + odd; } - return res * 2 + odd; - } }; diff --git a/Problems/0412.cpp b/Problems/0412.cpp @@ -1,19 +1,19 @@ class Solution { -public: - vector<string> fizzBuzz(int n) { - vector<string> res; + public: + vector<string> fizzBuzz(int n) { + vector<string> res; - for (int i = 1; i <= n; i++) { - string s = ""; + for (int i = 1; i <= n; i++) { + string s = ""; - if (i % 3 == 0) s += "Fizz"; + if (i % 3 == 0) s += "Fizz"; - if (i % 5 == 0) s += "Buzz"; + if (i % 5 == 0) s += "Buzz"; - if (s == "") s = to_string(i); + if (s == "") s = to_string(i); - res.push_back(s); + res.push_back(s); + } + return res; } - return res; - } }; diff --git a/Problems/0413.cpp b/Problems/0413.cpp @@ -1,16 +1,16 @@ class Solution { -public: - int numberOfArithmeticSlices(vector<int> &nums) { - int total = 0, crnt, cdiff = INT_MIN; - for (int i = 1; i < nums.size(); i++) { - int diff = nums[i] - nums[i - 1]; - if (diff != cdiff) { - crnt = 0; - cdiff = diff; - continue; - } - total += ++crnt; + public: + int numberOfArithmeticSlices(vector<int> &nums) { + int total = 0, crnt, cdiff = INT_MIN; + for (int i = 1; i < nums.size(); i++) { + int diff = nums[i] - nums[i - 1]; + if (diff != cdiff) { + crnt = 0; + cdiff = diff; + continue; + } + total += ++crnt; + } + return total; } - return total; - } }; diff --git a/Problems/0414.cpp b/Problems/0414.cpp @@ -1,27 +1,29 @@ class Solution { -public: - int thirdMax(vector<int> &nums) { - long long firstMax = numeric_limits<long long>::min(); - long long secondMax = numeric_limits<long long>::min(); - long long thirdMax = numeric_limits<long long>::min(); + public: + int thirdMax(vector<int> &nums) { + long long firstMax = numeric_limits<long long>::min(); + long long secondMax = numeric_limits<long long>::min(); + long long thirdMax = numeric_limits<long long>::min(); - for (int &num : nums) { - if (firstMax == num || secondMax == num || thirdMax == num) { continue; } + for (int &num : nums) { + if (firstMax == num || secondMax == num || thirdMax == num) { + continue; + } - if (firstMax <= num) { - thirdMax = secondMax; - secondMax = firstMax; - firstMax = num; - } else if (secondMax <= num) { - thirdMax = secondMax; - secondMax = num; - } else if (thirdMax <= num) { - thirdMax = num; - } - } + if (firstMax <= num) { + thirdMax = secondMax; + secondMax = firstMax; + firstMax = num; + } else if (secondMax <= num) { + thirdMax = secondMax; + secondMax = num; + } else if (thirdMax <= num) { + thirdMax = num; + } + } - if (thirdMax == numeric_limits<long long>::min()) return firstMax; + if (thirdMax == numeric_limits<long long>::min()) return firstMax; - return thirdMax; - } + return thirdMax; + } }; diff --git a/Problems/0415.cpp b/Problems/0415.cpp @@ -1,21 +1,21 @@ class Solution { -public: - string addStrings(string num1, string num2) { - if (num1 == "0" && num2 == "0") return "0"; + public: + string addStrings(string num1, string num2) { + if (num1 == "0" && num2 == "0") return "0"; - string res = ""; - int i = num1.size() - 1; - int j = num2.size() - 1; + string res = ""; + int i = num1.size() - 1; + int j = num2.size() - 1; - int add = 0; - while (i >= 0 || j >= 0 || add) { - if (i >= 0) add += num1[i--] - '0'; - if (j >= 0) add += num2[j--] - '0'; - res += to_string(add % 10); - add /= 10; - } + int add = 0; + while (i >= 0 || j >= 0 || add) { + if (i >= 0) add += num1[i--] - '0'; + if (j >= 0) add += num2[j--] - '0'; + res += to_string(add % 10); + add /= 10; + } - reverse(res.begin(), res.end()); - return res; - } + reverse(res.begin(), res.end()); + return res; + } }; diff --git a/Problems/0416.cpp b/Problems/0416.cpp @@ -1,15 +1,15 @@ class Solution { -public: - bool canPartition(vector<int> &nums) { - int sum = accumulate(nums.begin(), nums.end(), 0), hsum = sum / 2; - if (sum % 2) return false; - vector<bool> dp(hsum + 1, false); + public: + bool canPartition(vector<int> &nums) { + int sum = accumulate(nums.begin(), nums.end(), 0), hsum = sum / 2; + if (sum % 2) return false; + vector<bool> dp(hsum + 1, false); - dp[0] = true; - for (int num : nums) - for (int j = hsum; j >= num; j--) - if (dp[j - num]) dp[j] = true; + dp[0] = true; + for (int num : nums) + for (int j = hsum; j >= num; j--) + if (dp[j - num]) dp[j] = true; - return dp.back(); - } + return dp.back(); + } }; diff --git a/Problems/0417.cpp b/Problems/0417.cpp @@ -1,54 +1,49 @@ class Solution { - typedef vector<vector<int>> Matrix; - typedef vector<vector<bool>> Marked; - typedef queue<pair<int, int>> Queue; - const vector<pair<int, int>> offsets = { - { 0, 1}, - { 0, -1}, - { 1, 0}, - {-1, 0} - }; - - int n, m; - int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } - - void dfs(Matrix &mat, Marked &mark, int x, int y) { - if (mark[x][y]) return; - Queue q; - - q.push({x, y}), mark[x][y] = true; - while (!q.empty()) { - auto [a, b] = q.front(); - q.pop(); - for (auto [oa, ob] : offsets) { - int x = a + oa, y = b + ob; - if (!valid(x, y) || mark[x][y] || mat[x][y] < mat[a][b]) continue; - mark[x][y] = true; - q.push({x, y}); - } + typedef vector<vector<int>> Matrix; + typedef vector<vector<bool>> Marked; + typedef queue<pair<int, int>> Queue; + const vector<pair<int, int>> offsets = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + + int n, m; + int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } + + void dfs(Matrix &mat, Marked &mark, int x, int y) { + if (mark[x][y]) return; + Queue q; + + q.push({x, y}), mark[x][y] = true; + while (!q.empty()) { + auto [a, b] = q.front(); + q.pop(); + for (auto [oa, ob] : offsets) { + int x = a + oa, y = b + ob; + if (!valid(x, y) || mark[x][y] || mat[x][y] < mat[a][b]) continue; + mark[x][y] = true; + q.push({x, y}); + } + } } - } -public: - vector<vector<int>> pacificAtlantic(Matrix &heights) { - n = heights.size(), m = heights[0].size(); - Marked pac(n, vector<bool>(m, false)), atl(n, vector<bool>(m, false)); + public: + vector<vector<int>> pacificAtlantic(Matrix &heights) { + n = heights.size(), m = heights[0].size(); + Marked pac(n, vector<bool>(m, false)), atl(n, vector<bool>(m, false)); - for (int i = 0; i < n; i++) { - dfs(heights, pac, i, 0); - dfs(heights, atl, i, m - 1); - } + for (int i = 0; i < n; i++) { + dfs(heights, pac, i, 0); + dfs(heights, atl, i, m - 1); + } - for (int i = 0; i < m; i++) { - dfs(heights, pac, 0, i); - dfs(heights, atl, n - 1, i); - } + for (int i = 0; i < m; i++) { + dfs(heights, pac, 0, i); + dfs(heights, atl, n - 1, i); + } - vector<vector<int>> res; - for (int i = 0; i < n; i++) - for (int j = 0; j < m; j++) - if (pac[i][j] && atl[i][j]) res.push_back({i, j}); + vector<vector<int>> res; + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + if (pac[i][j] && atl[i][j]) res.push_back({i, j}); - return res; - } + return res; + } }; diff --git a/Problems/0419.cpp b/Problems/0419.cpp @@ -1,15 +1,15 @@ class Solution { -public: - int countBattleships(const vector<vector<char>> &board) { - int res = 0; - for (int i = 0; i < board.size(); i++) { - for (int j = 0; j < board[0].size(); j++) { - if (board[i][j] == '.') continue; - if (i > 0 && board[i - 1][j] == 'X') continue; - if (j > 0 && board[i][j - 1] == 'X') continue; - res++; - } + public: + int countBattleships(const vector<vector<char>> &board) { + int res = 0; + for (int i = 0; i < board.size(); i++) { + for (int j = 0; j < board[0].size(); j++) { + if (board[i][j] == '.') continue; + if (i > 0 && board[i - 1][j] == 'X') continue; + if (j > 0 && board[i][j - 1] == 'X') continue; + res++; + } + } + return res; } - return res; - } }; diff --git a/Problems/0424.cpp b/Problems/0424.cpp @@ -1,18 +1,19 @@ class Solution { -public: - int characterReplacement(string s, int k) { - vector<int> counts(26, 0); - int n = s.length(), start = 0, maxi = 0, result = 0; - for_each(s.begin(), s.end(), [](char &c) { c -= 'A'; }); + public: + int characterReplacement(string s, int k) { + vector<int> counts(26, 0); + int n = s.length(), start = 0, maxi = 0, result = 0; + for_each(s.begin(), s.end(), [](char &c) { c -= 'A'; }); - for (int end = 0; end < n; end++) { - maxi = max(maxi, ++counts[s[end]]); - while (end - start - maxi + 1 > k) { - counts[s[start++]]--; - for (int i = 0; i < 26; i++) maxi = max(maxi, counts[i]); - } - result = max(result, end - start + 1); + for (int end = 0; end < n; end++) { + maxi = max(maxi, ++counts[s[end]]); + while (end - start - maxi + 1 > k) { + counts[s[start++]]--; + for (int i = 0; i < 26; i++) + maxi = max(maxi, counts[i]); + } + result = max(result, end - start + 1); + } + return result; } - return result; - } }; diff --git a/Problems/0427.cpp b/Problems/0427.cpp @@ -1,33 +1,32 @@ class Solution { -public: - Node *construct(vector<vector<int>> &grid, int rowStart, int rowEnd, - int colStart, int colEnd) { - if (rowStart > rowEnd || colStart > colEnd) return nullptr; + public: + Node *construct(vector<vector<int>> &grid, int rowStart, int rowEnd, int colStart, int colEnd) { + if (rowStart > rowEnd || colStart > colEnd) return nullptr; - bool isLeaf = true; - int val = grid[rowStart][colStart]; - for (int i = rowStart; i <= rowEnd; i++) { - for (int j = colStart; j <= colEnd; j++) { - if (grid[i][j] != val) { - isLeaf = false; - break; + bool isLeaf = true; + int val = grid[rowStart][colStart]; + for (int i = rowStart; i <= rowEnd; i++) { + for (int j = colStart; j <= colEnd; j++) { + if (grid[i][j] != val) { + isLeaf = false; + break; + } + } + if (!isLeaf) break; } - } - if (!isLeaf) break; - } - if (isLeaf) return new Node(val, true); + if (isLeaf) return new Node(val, true); - int rowMid = (rowStart + rowEnd) / 2; - int colMid = (colStart + colEnd) / 2; - Node *topLeft = construct(grid, rowStart, rowMid, colStart, colMid); - Node *topRight = construct(grid, rowStart, rowMid, colMid + 1, colEnd); - Node *bottomLeft = construct(grid, rowMid + 1, rowEnd, colStart, colMid); - Node *bottomRight = construct(grid, rowMid + 1, rowEnd, colMid + 1, colEnd); - return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight); - } - Node *construct(vector<vector<int>> &grid) { - int n = grid.size(); - return construct(grid, 0, n - 1, 0, n - 1); - } + int rowMid = (rowStart + rowEnd) / 2; + int colMid = (colStart + colEnd) / 2; + Node *topLeft = construct(grid, rowStart, rowMid, colStart, colMid); + Node *topRight = construct(grid, rowStart, rowMid, colMid + 1, colEnd); + Node *bottomLeft = construct(grid, rowMid + 1, rowEnd, colStart, colMid); + Node *bottomRight = construct(grid, rowMid + 1, rowEnd, colMid + 1, colEnd); + return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight); + } + Node *construct(vector<vector<int>> &grid) { + int n = grid.size(); + return construct(grid, 0, n - 1, 0, n - 1); + } }; diff --git a/Problems/0429.cpp b/Problems/0429.cpp @@ -1,21 +1,22 @@ class Solution { -public: - vector<vector<int>> levelOrder(Node *root) { - if (!root) return {}; + public: + vector<vector<int>> levelOrder(Node *root) { + if (!root) return {}; - vector<vector<int>> res; - queue<Node *> q; + vector<vector<int>> res; + queue<Node *> q; - q.push(root); - for (int lvl = 0; !q.empty(); lvl++) { - res.push_back(vector<int>()); - for (int t = q.size(); t > 0; t--) { - Node *root = q.front(); - q.pop(); - res[lvl].push_back(root->val); - for (Node *c : root->children) q.push(c); - } + q.push(root); + for (int lvl = 0; !q.empty(); lvl++) { + res.push_back(vector<int>()); + for (int t = q.size(); t > 0; t--) { + Node *root = q.front(); + q.pop(); + res[lvl].push_back(root->val); + for (Node *c : root->children) + q.push(c); + } + } + return res; } - return res; - } }; diff --git a/Problems/0430.cpp b/Problems/0430.cpp @@ -1,34 +1,34 @@ class Solution { - void insert_after(Node **t, Node *n) { - n->prev = *t; - n->child = nullptr; - (*t) = (*t)->next = n; - } + void insert_after(Node **t, Node *n) { + n->prev = *t; + n->child = nullptr; + (*t) = (*t)->next = n; + } -public: - Node *flatten(Node *head) { - if (!head) return nullptr; + public: + Node *flatten(Node *head) { + if (!head) return nullptr; - stack<Node *> s; - s.push(head); + stack<Node *> s; + s.push(head); - Node *h, *t; - t = h = new Node(); - while (!s.empty()) { - Node *self = s.top(); - s.pop(); - if (self->next) s.push(self->next); - Node *child = self->child; - insert_after(&t, self); - while (child) { - self = child; - child = self->child; - insert_after(&t, self); - if (self->next) s.push(self->next); - } + Node *h, *t; + t = h = new Node(); + while (!s.empty()) { + Node *self = s.top(); + s.pop(); + if (self->next) s.push(self->next); + Node *child = self->child; + insert_after(&t, self); + while (child) { + self = child; + child = self->child; + insert_after(&t, self); + if (self->next) s.push(self->next); + } + } + t->next = nullptr; + h->next->prev = nullptr; + return h->next; } - t->next = nullptr; - h->next->prev = nullptr; - return h->next; - } }; diff --git a/Problems/0433.cpp b/Problems/0433.cpp @@ -1,42 +1,41 @@ class Solution { - bool mutation(const string &s1, const string &s2) { - int cnt = 0; - for (int i = 0; i < size(s1); i++) - if (s1[i] != s2[i]) cnt++; - return cnt == 1; - } + bool mutation(const string &s1, const string &s2) { + int cnt = 0; + for (int i = 0; i < size(s1); i++) + if (s1[i] != s2[i]) cnt++; + return cnt == 1; + } -public: - int minMutation(string startGene, string endGene, vector<string> &bank) { - /* unordered_map<string, vector<string>> um; */ + public: + int minMutation(string startGene, string endGene, vector<string> &bank) { + /* unordered_map<string, vector<string>> um; */ - /* if (find(bank.begin(), bank.end(), startGene) == bank.end()) */ - /* bank.push_back(startGene); */ + /* if (find(bank.begin(), bank.end(), startGene) == bank.end()) */ + /* bank.push_back(startGene); */ - /* for (int i = 0; i < size(bank); i++) { */ - /* for (int j = i + 1; j < size(bank); j++) */ - /* if (mutation(bank[i], bank[j])) { */ - /* um[bank[i]].push_back(bank[j]); */ - /* um[bank[j]].push_back(bank[i]); */ - /* } */ - /* } */ + /* for (int i = 0; i < size(bank); i++) { */ + /* for (int j = i + 1; j < size(bank); j++) */ + /* if (mutation(bank[i], bank[j])) { */ + /* um[bank[i]].push_back(bank[j]); */ + /* um[bank[j]].push_back(bank[i]); */ + /* } */ + /* } */ - int mini = INT_MAX; - unordered_set<string> visited; - queue<pair<string, int>> st; - st.push({startGene, 0}); - while (!st.empty()) { - string root = st.front().first; - int count = st.front().second; - st.pop(); - visited.insert(root); - if (root == endGene) return count; - /* for (string &s : um[root]) */ - /* if (visited.find(s) == visited.end()) st.push({s, count + 1}); */ - for (string &s : bank) - if (visited.find(s) == visited.end() && mutation(root, s)) - st.push({s, count + 1}); + int mini = INT_MAX; + unordered_set<string> visited; + queue<pair<string, int>> st; + st.push({startGene, 0}); + while (!st.empty()) { + string root = st.front().first; + int count = st.front().second; + st.pop(); + visited.insert(root); + if (root == endGene) return count; + /* for (string &s : um[root]) */ + /* if (visited.find(s) == visited.end()) st.push({s, count + 1}); */ + for (string &s : bank) + if (visited.find(s) == visited.end() && mutation(root, s)) st.push({s, count + 1}); + } + return -1; } - return -1; - } }; diff --git a/Problems/0435.cpp b/Problems/0435.cpp @@ -1,20 +1,18 @@ class Solution { - typedef vector<int> interval; + typedef vector<int> interval; -public: - int eraseOverlapIntervals(vector<interval> &intervals) { - auto cmp = [](const interval &i1, const interval &i2) { - return i1[1] < i2[1]; - }; - sort(intervals.begin(), intervals.end(), cmp); + public: + int eraseOverlapIntervals(vector<interval> &intervals) { + auto cmp = [](const interval &i1, const interval &i2) { return i1[1] < i2[1]; }; + sort(intervals.begin(), intervals.end(), cmp); - int end = intervals[0][1], count = 1; - for (auto &i : intervals) { - if (i[0] >= end) { - end = i[1]; - count++; - } + int end = intervals[0][1], count = 1; + for (auto &i : intervals) { + if (i[0] >= end) { + end = i[1]; + count++; + } + } + return intervals.size() - count; } - return intervals.size() - count; - } }; diff --git a/Problems/0437.cpp b/Problems/0437.cpp @@ -1,70 +1,70 @@ // Brute force class Solution { -public: - int pathSum(TreeNode *root, int targetSum) { - if (!root) return 0; + public: + int pathSum(TreeNode *root, int targetSum) { + if (!root) return 0; - stack<TreeNode *> st; - queue<TreeNode *> q; + stack<TreeNode *> st; + queue<TreeNode *> q; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - q.push(root); - if (root->left) st.push(root->left); - if (root->right) st.push(root->right); - } + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + q.push(root); + if (root->left) st.push(root->left); + if (root->right) st.push(root->right); + } - int res = 0; - while (!q.empty()) { - stack<pair<TreeNode *, long long>> st; - st.push({q.front(), 0}); - q.pop(); - while (!st.empty()) { - auto [root, sum] = st.top(); - st.pop(); - sum += root->val; - if (sum == targetSum) res++; - if (root->left) st.push({root->left, sum}); - if (root->right) st.push({root->right, sum}); - } - } + int res = 0; + while (!q.empty()) { + stack<pair<TreeNode *, long long>> st; + st.push({q.front(), 0}); + q.pop(); + while (!st.empty()) { + auto [root, sum] = st.top(); + st.pop(); + sum += root->val; + if (sum == targetSum) res++; + if (root->left) st.push({root->left, sum}); + if (root->right) st.push({root->right, sum}); + } + } - return res; - } + return res; + } }; // Optimized class Solution { -public: - int pathSum(TreeNode *root, int targetSum) { - if (!root) return 0; - queue<pair<TreeNode *, vector<long long>>> q; - int res = 0; + public: + int pathSum(TreeNode *root, int targetSum) { + if (!root) return 0; + queue<pair<TreeNode *, vector<long long>>> q; + int res = 0; - q.push({root, {}}); - while (!q.empty()) { - auto &[root, vec] = q.front(); - long long sum = root->val + (vec.size() ? vec.back() : 0); + q.push({root, {}}); + while (!q.empty()) { + auto &[root, vec] = q.front(); + long long sum = root->val + (vec.size() ? vec.back() : 0); - for (int num : vec) - if (sum - num == targetSum) res++; - if (sum == targetSum) res++; + for (int num : vec) + if (sum - num == targetSum) res++; + if (sum == targetSum) res++; - if (root->left) { - q.push({root->left, vec}); - q.back().second.push_back(sum); - } + if (root->left) { + q.push({root->left, vec}); + q.back().second.push_back(sum); + } - if (root->right) { - q.push({root->right, vec}); - q.back().second.push_back(sum); - } + if (root->right) { + q.push({root->right, vec}); + q.back().second.push_back(sum); + } - q.pop(); - } + q.pop(); + } - return res; - } + return res; + } }; diff --git a/Problems/0438.cpp b/Problems/0438.cpp @@ -1,31 +1,31 @@ class Solution { - typedef unordered_map<char, int> umci; - bool um_eq(const umci &goal, const umci &crnt) { - for (auto [k, v] : goal) { - const auto it = crnt.find(k); - if (it == crnt.end()) return false; - if ((*it).second != v) return false; + typedef unordered_map<char, int> umci; + bool um_eq(const umci &goal, const umci &crnt) { + for (auto [k, v] : goal) { + const auto it = crnt.find(k); + if (it == crnt.end()) return false; + if ((*it).second != v) return false; + } + return true; } - return true; - } -public: - vector<int> findAnagrams(string s, string p) { - if (p.size() > s.size()) return {}; - unordered_map<char, int> goal, crnt; + public: + vector<int> findAnagrams(string s, string p) { + if (p.size() > s.size()) return {}; + unordered_map<char, int> goal, crnt; - for (int i = 0; i < p.size(); i++) { - goal[p[i]]++; - crnt[s[i]]++; - } + for (int i = 0; i < p.size(); i++) { + goal[p[i]]++; + crnt[s[i]]++; + } - vector<int> res; - for (int i = p.size(); i < s.size(); i++) { - if (um_eq(goal, crnt)) res.push_back(i - p.size()); - crnt[s[i - p.size()]]--; - crnt[s[i]]++; + vector<int> res; + for (int i = p.size(); i < s.size(); i++) { + if (um_eq(goal, crnt)) res.push_back(i - p.size()); + crnt[s[i - p.size()]]--; + crnt[s[i]]++; + } + if (um_eq(goal, crnt)) res.push_back(s.size() - p.size()); + return res; } - if (um_eq(goal, crnt)) res.push_back(s.size() - p.size()); - return res; - } }; diff --git a/Problems/0442.cpp b/Problems/0442.cpp @@ -1,15 +1,15 @@ class Solution { -public: - vector<int> findDuplicates(vector<int> &nums) { - vector<int> res; - for (int i = 0; i < nums.size(); i++) { - int idx = abs(nums[i]) - 1; - if (nums[idx] < 0) - res.push_back(idx + 1); - else - nums[idx] = -nums[idx]; - } + public: + vector<int> findDuplicates(vector<int> &nums) { + vector<int> res; + for (int i = 0; i < nums.size(); i++) { + int idx = abs(nums[i]) - 1; + if (nums[idx] < 0) + res.push_back(idx + 1); + else + nums[idx] = -nums[idx]; + } - return res; - } + return res; + } }; diff --git a/Problems/0443.cpp b/Problems/0443.cpp @@ -1,23 +1,25 @@ class Solution { -public: - int compress(vector<char> &chars) { - char prev = chars[0]; - int count = 1, crnt = 0; - for (int i = 1; i < chars.size(); i++) { - if (chars[i] == prev) - count++; - else { + public: + int compress(vector<char> &chars) { + char prev = chars[0]; + int count = 1, crnt = 0; + for (int i = 1; i < chars.size(); i++) { + if (chars[i] == prev) + count++; + else { + chars[crnt++] = prev; + if (count != 1) + for (char c : to_string(count)) + chars[crnt++] = c; + count = 1; + prev = chars[i]; + } + } chars[crnt++] = prev; if (count != 1) - for (char c : to_string(count)) chars[crnt++] = c; - count = 1; - prev = chars[i]; - } - } - chars[crnt++] = prev; - if (count != 1) - for (char c : to_string(count)) chars[crnt++] = c; + for (char c : to_string(count)) + chars[crnt++] = c; - return crnt; - } + return crnt; + } }; diff --git a/Problems/0445.cpp b/Problems/0445.cpp @@ -1,9 +1,9 @@ class Solution { -public: - pair<ListNode*, int> reverse(ListNode *root) { + public: + pair<ListNode *, int> reverse(ListNode *root) { ListNode *l = nullptr, *c = root; int size = 0; - while(c) { + while (c) { ListNode *n = c->next; c->next = l; l = c; @@ -13,31 +13,31 @@ public: return {l, size}; } - ListNode* addTwoNumbers(ListNode* p1, ListNode* p2) { + ListNode *addTwoNumbers(ListNode *p1, ListNode *p2) { auto [l1, s1] = reverse(p1); auto [l2, s2] = reverse(p2); - if(s2 > s1) swap(l1, l2); + if (s2 > s1) swap(l1, l2); p1 = l1; int carry = 0; - for(; l1 && l2; l1=l1->next, l2=l2->next) { + for (; l1 && l2; l1 = l1->next, l2 = l2->next) { int sum = l1->val + l2->val + carry; l1->val = sum % 10; carry = sum / 10; } - if(l1) { - while(true) { + if (l1) { + while (true) { int sum = l1->val + carry; l1->val = sum % 10; carry = sum / 10; - if(!l1->next) break; + if (!l1->next) break; l1 = l1->next; } } - if(!carry) return reverse(p1).first; + if (!carry) return reverse(p1).first; return new ListNode(carry, reverse(p1).first); } }; diff --git a/Problems/0448.cpp b/Problems/0448.cpp @@ -1,16 +1,16 @@ class Solution { -public: - vector<int> findDisappearedNumbers(vector<int> &nums) { - vector<int> res; + public: + vector<int> findDisappearedNumbers(vector<int> &nums) { + vector<int> res; - for (int i = 0; i < nums.size(); i++) { - int index = abs(nums[i]) - 1; - if (nums[index] > 0) nums[index] = -nums[index]; - } + for (int i = 0; i < nums.size(); i++) { + int index = abs(nums[i]) - 1; + if (nums[index] > 0) nums[index] = -nums[index]; + } - for (int i = 0; i < nums.size(); i++) - if (nums[i] > 0) res.push_back(i + 1); + for (int i = 0; i < nums.size(); i++) + if (nums[i] > 0) res.push_back(i + 1); - return res; - } + return res; + } }; diff --git a/Problems/0450.cpp b/Problems/0450.cpp @@ -1,33 +1,33 @@ class Solution { - TreeNode *deleteRoot(TreeNode *root) { - if (!root) return nullptr; - if (!root->left) return root->right; - if (!root->right) return root->left; + TreeNode *deleteRoot(TreeNode *root) { + if (!root) return nullptr; + if (!root->left) return root->right; + if (!root->right) return root->left; - TreeNode *next = root->right; - TreeNode *pre = nullptr; - while (next->left) { - pre = next; - next = next->left; + TreeNode *next = root->right; + TreeNode *pre = nullptr; + while (next->left) { + pre = next; + next = next->left; + } + next->left = root->left; + if (root->right != next) { + pre->left = next->right; + next->right = root->right; + } + return next; } - next->left = root->left; - if (root->right != next) { - pre->left = next->right; - next->right = root->right; - } - return next; - } -public: - TreeNode *deleteNode(TreeNode *root, int key) { - TreeNode *cur = root, *pre = nullptr; - while (cur && cur->val != key) { - pre = cur; - cur = key < cur->val ? cur->left : cur->right; - } + public: + TreeNode *deleteNode(TreeNode *root, int key) { + TreeNode *cur = root, *pre = nullptr; + while (cur && cur->val != key) { + pre = cur; + cur = key < cur->val ? cur->left : cur->right; + } - if (!pre) return deleteRoot(cur); - (pre->left == cur ? pre->left : pre->right) = deleteRoot(cur); - return root; - } + if (!pre) return deleteRoot(cur); + (pre->left == cur ? pre->left : pre->right) = deleteRoot(cur); + return root; + } }; diff --git a/Problems/0451.cpp b/Problems/0451.cpp @@ -1,11 +1,11 @@ class Solution { -public: - string frequencySort(string s) { - array<int, 128> um = {0}; - for (char c : s) um[c]++; - sort(s.begin(), s.end(), [&um](char a, char b) { - return um[a] > um[b] || (um[a] == um[b] && a < b); - }); - return s; - } + public: + string frequencySort(string s) { + array<int, 128> um = {0}; + for (char c : s) + um[c]++; + sort(s.begin(), s.end(), + [&um](char a, char b) { return um[a] > um[b] || (um[a] == um[b] && a < b); }); + return s; + } }; diff --git a/Problems/0452.cpp b/Problems/0452.cpp @@ -1,17 +1,17 @@ class Solution { - typedef vector<int> segment; + typedef vector<int> segment; -public: - int findMinArrowShots(vector<segment> &segments) { - auto cmp = [](const segment &a, const segment &b) { return a[1] < b[1]; }; - sort(segments.begin(), segments.end(), cmp); - int res = 1, arrow = segments[0][1]; - for (segment &s : segments) { - if (s[0] > arrow) { - res++; - arrow = s[1]; - } + public: + int findMinArrowShots(vector<segment> &segments) { + auto cmp = [](const segment &a, const segment &b) { return a[1] < b[1]; }; + sort(segments.begin(), segments.end(), cmp); + int res = 1, arrow = segments[0][1]; + for (segment &s : segments) { + if (s[0] > arrow) { + res++; + arrow = s[1]; + } + } + return res; } - return res; - } }; diff --git a/Problems/0459.cpp b/Problems/0459.cpp @@ -1,14 +1,15 @@ class Solution { -public: - bool repeatedSubstringPattern(const string &s) { - string made; - for (int i = 1; i <= s.size() / 2; i++) { - if (s.size() % i) continue; - const string pref = s.substr(0, i); - for (int j = 0; j < s.size() / i; j++) made += pref; - if (made == s) return true; - made.clear(); + public: + bool repeatedSubstringPattern(const string &s) { + string made; + for (int i = 1; i <= s.size() / 2; i++) { + if (s.size() % i) continue; + const string pref = s.substr(0, i); + for (int j = 0; j < s.size() / i; j++) + made += pref; + if (made == s) return true; + made.clear(); + } + return false; } - return false; - } }; diff --git a/Problems/0460.cpp b/Problems/0460.cpp @@ -1 +1 @@ -Formating: Problems/0460.cpp +Formating : Problems / 0460.cpp diff --git a/Problems/0472.cpp b/Problems/0472.cpp @@ -1 +1 @@ -Formating: Problems/0472.cpp +Formating : Problems / 0472.cpp diff --git a/Problems/0485.cpp b/Problems/0485.cpp @@ -1,15 +1,15 @@ class Solution { -public: - int findMaxConsecutiveOnes(vector<int> &nums) { - int maxi = 0; - int cnt = 0; + public: + int findMaxConsecutiveOnes(vector<int> &nums) { + int maxi = 0; + int cnt = 0; - for (int i : nums) - if (i) - maxi = max(maxi, ++cnt); - else - cnt = 0; + for (int i : nums) + if (i) + maxi = max(maxi, ++cnt); + else + cnt = 0; - return maxi; - } + return maxi; + } }; diff --git a/Problems/0486.cpp b/Problems/0486.cpp @@ -1,20 +1,18 @@ class Solution { - int dp[21][21]; + int dp[21][21]; - int rec(const vector<int> &nums, int i, int j) { - if (i == j) return nums[i]; - if (dp[i][j] != -1) return dp[i][j]; + int rec(const vector<int> &nums, int i, int j) { + if (i == j) return nums[i]; + if (dp[i][j] != -1) return dp[i][j]; - int left = nums[i] - rec(nums, i + 1, j); - int right = nums[j] - rec(nums, i, j - 1); + int left = nums[i] - rec(nums, i + 1, j); + int right = nums[j] - rec(nums, i, j - 1); - return dp[i][j] = max(left, right); - } + return dp[i][j] = max(left, right); + } -public: - Solution() { memset(dp, 0xFF, sizeof(dp)); } + public: + Solution() { memset(dp, 0xFF, sizeof(dp)); } - bool PredictTheWinner(const vector<int> &nums) { - return rec(nums, 0, nums.size() - 1) >= 0; - } + bool PredictTheWinner(const vector<int> &nums) { return rec(nums, 0, nums.size() - 1) >= 0; } }; diff --git a/Problems/0491.cpp b/Problems/0491.cpp @@ -1,23 +1,23 @@ class Solution { - vector<vector<int>> res; - vector<int> seq; + vector<vector<int>> res; + vector<int> seq; -public: - vector<vector<int>> findSubsequences(vector<int> &nums) { - dfs(nums, 0); - return res; - } + public: + vector<vector<int>> findSubsequences(vector<int> &nums) { + dfs(nums, 0); + return res; + } - void dfs(vector<int> &nums, int pos) { - if (seq.size() > 1) res.push_back(seq); - unordered_set<int> hash; - for (int i = pos; i < nums.size(); i++) { - if ((seq.empty() || nums[i] >= seq.back()) && !hash.count(nums[i])) { - seq.push_back(nums[i]); - dfs(nums, i + 1); - seq.pop_back(); - hash.insert(nums[i]); - } + void dfs(vector<int> &nums, int pos) { + if (seq.size() > 1) res.push_back(seq); + unordered_set<int> hash; + for (int i = pos; i < nums.size(); i++) { + if ((seq.empty() || nums[i] >= seq.back()) && !hash.count(nums[i])) { + seq.push_back(nums[i]); + dfs(nums, i + 1); + seq.pop_back(); + hash.insert(nums[i]); + } + } } - } }; diff --git a/Problems/0494.cpp b/Problems/0494.cpp @@ -1,37 +1,37 @@ // Initial solution class Solution { -public: - int findTargetSumWays(vector<int> &nums, int target) { - unordered_map<int, int> crnt; - crnt[0] = 1; - for (int i = 0; i < nums.size(); i++) { - unordered_map<int, int> next; - for (auto &p : crnt) { - next[p.first + nums[i]] += p.second; - next[p.first - nums[i]] += p.second; - } - crnt = next; + public: + int findTargetSumWays(vector<int> &nums, int target) { + unordered_map<int, int> crnt; + crnt[0] = 1; + for (int i = 0; i < nums.size(); i++) { + unordered_map<int, int> next; + for (auto &p : crnt) { + next[p.first + nums[i]] += p.second; + next[p.first - nums[i]] += p.second; + } + crnt = next; + } + return crnt[target]; } - return crnt[target]; - } }; // Optimized using array; class Solution { -public: - int findTargetSumWays(vector<int> &nums, int target) { - int total = accumulate(nums.begin(), nums.end(), 0); - vector<int> dp(2 * total + 1); - dp[total] = 1; - for (int i = 0; i < nums.size(); i++) { - vector<int> next(2 * total + 1); - for (int j = 0; j < dp.size(); j++) { - if (!dp[j]) continue; - next[j + nums[i]] += dp[j]; - next[j - nums[i]] += dp[j]; - } - dp = next; + public: + int findTargetSumWays(vector<int> &nums, int target) { + int total = accumulate(nums.begin(), nums.end(), 0); + vector<int> dp(2 * total + 1); + dp[total] = 1; + for (int i = 0; i < nums.size(); i++) { + vector<int> next(2 * total + 1); + for (int j = 0; j < dp.size(); j++) { + if (!dp[j]) continue; + next[j + nums[i]] += dp[j]; + next[j - nums[i]] += dp[j]; + } + dp = next; + } + return abs(target) > total ? 0 : dp[target + total]; } - return abs(target) > total ? 0 : dp[target + total]; - } }; diff --git a/Problems/0496.cpp b/Problems/0496.cpp @@ -1,21 +1,21 @@ class Solution { -public: - vector<int> nextGreaterElement(vector<int> &nums1, vector<int> &nums2) { - vector<int> res(nums1.size(), -1); - unordered_map<int, int> um; - stack<int> st; + public: + vector<int> nextGreaterElement(vector<int> &nums1, vector<int> &nums2) { + vector<int> res(nums1.size(), -1); + unordered_map<int, int> um; + stack<int> st; - for (int i = 0; i < nums2.size(); i++) { - while (!st.empty() && nums2[i] > st.top()) { - um.insert(make_pair(st.top(), nums2[i])); - st.pop(); - } - st.push(nums2[i]); - } + for (int i = 0; i < nums2.size(); i++) { + while (!st.empty() && nums2[i] > st.top()) { + um.insert(make_pair(st.top(), nums2[i])); + st.pop(); + } + st.push(nums2[i]); + } - for (int i = 0; i < nums1.size(); i++) - if (um.find(nums1[i]) != um.end()) res[i] = um[nums1[i]]; + for (int i = 0; i < nums1.size(); i++) + if (um.find(nums1[i]) != um.end()) res[i] = um[nums1[i]]; - return res; - } + return res; + } }; diff --git a/Problems/0498.cpp b/Problems/0498.cpp @@ -1,45 +1,44 @@ class Solution { -public: - bool valid(int i, int m, int j, int n) { - return i >= 0 && i <= m && j >= 0 && j <= n; - } + public: + bool valid(int i, int m, int j, int n) { return i >= 0 && i <= m && j >= 0 && j <= n; } - void quick_adjust(int &i, int &j, bool &up) { - if (up) - i++; - else - j++; - up = !up; - } + void quick_adjust(int &i, int &j, bool &up) { + if (up) + i++; + else + j++; + up = !up; + } - void move(int &i, int &j, bool &up) { - if (up) { - i--; - j++; - } else { - i++; - j--; + void move(int &i, int &j, bool &up) { + if (up) { + i--; + j++; + } else { + i++; + j--; + } } - } - vector<int> findDiagonalOrder(vector<vector<int>> &mat) { - vector<int> res; - bool up = true; - int i = 0, j = 0; - int m = mat.size() - 1, n = mat[0].size() - 1; + vector<int> findDiagonalOrder(vector<vector<int>> &mat) { + vector<int> res; + bool up = true; + int i = 0, j = 0; + int m = mat.size() - 1, n = mat[0].size() - 1; - while (true) { - res.push_back(mat[i][j]); - if (i == m && j == n) break; + while (true) { + res.push_back(mat[i][j]); + if (i == m && j == n) break; - move(i, j, up); + move(i, j, up); - if (!valid(i, m, j, n)) { - quick_adjust(i, j, up); - while (!valid(i, m, j, n)) move(i, j, up); - } - } + if (!valid(i, m, j, n)) { + quick_adjust(i, j, up); + while (!valid(i, m, j, n)) + move(i, j, up); + } + } - return res; - } + return res; + } }; diff --git a/Problems/0501.cpp b/Problems/0501.cpp @@ -1,34 +1,34 @@ class Solution { -public: - vector<int> findMode(TreeNode *root) { - stack<TreeNode *> st; + public: + vector<int> findMode(TreeNode *root) { + stack<TreeNode *> st; - int maxi = INT_MIN, cnt = 0, prev = -1; - vector<int> res; - while (true) { - while (root) { - st.push(root); - root = root->left; - } - if (st.empty()) break; - root = st.top(), st.pop(); - if (root->val != prev) { + int maxi = INT_MIN, cnt = 0, prev = -1; + vector<int> res; + while (true) { + while (root) { + st.push(root); + root = root->left; + } + if (st.empty()) break; + root = st.top(), st.pop(); + if (root->val != prev) { + if (cnt >= maxi) { + if (cnt > maxi) res.clear(); + maxi = cnt; + res.push_back(prev); + } + prev = root->val; + cnt = 1; + } else + cnt++; + root = root->right; + } if (cnt >= maxi) { - if (cnt > maxi) res.clear(); - maxi = cnt; - res.push_back(prev); + if (cnt > maxi) res.clear(); + maxi = cnt; + res.push_back(prev); } - prev = root->val; - cnt = 1; - } else - cnt++; - root = root->right; - } - if (cnt >= maxi) { - if (cnt > maxi) res.clear(); - maxi = cnt; - res.push_back(prev); + return res; } - return res; - } }; diff --git a/Problems/0502.cpp b/Problems/0502.cpp @@ -1,35 +1,35 @@ class Solution { - typedef pair<int, int> pii; + typedef pair<int, int> pii; -public: - int findMaximizedCapital(int k, int w, vector<int> &profits, - vector<int> &capital) { - vector<pii> data(profits.size()); - for (int i = 0; i < profits.size(); i++) data[i] = {capital[i], profits[i]}; - sort(data.begin(), data.end()); + public: + int findMaximizedCapital(int k, int w, vector<int> &profits, vector<int> &capital) { + vector<pii> data(profits.size()); + for (int i = 0; i < profits.size(); i++) + data[i] = {capital[i], profits[i]}; + sort(data.begin(), data.end()); - auto cmp = [](const pii &a, const pii &b) { return a.second < b.second; }; - priority_queue<pii, vector<pii>, decltype(cmp)> pq(cmp); + auto cmp = [](const pii &a, const pii &b) { return a.second < b.second; }; + priority_queue<pii, vector<pii>, decltype(cmp)> pq(cmp); - int i = 0; - while (i < profits.size() && k) { - if (data[i].first <= w) - pq.push(data[i++]); - else { - while (!pq.empty() && data[i].first > w && k) { - w += pq.top().second; - pq.pop(); - k--; + int i = 0; + while (i < profits.size() && k) { + if (data[i].first <= w) + pq.push(data[i++]); + else { + while (!pq.empty() && data[i].first > w && k) { + w += pq.top().second; + pq.pop(); + k--; + } + if (pq.empty() && data[i].first > w) break; + } + } + while (!pq.empty() && k) { + w += pq.top().second; + pq.pop(); + k--; } - if (pq.empty() && data[i].first > w) break; - } - } - while (!pq.empty() && k) { - w += pq.top().second; - pq.pop(); - k--; - } - return w; - } + return w; + } }; diff --git a/Problems/0503.cpp b/Problems/0503.cpp @@ -1,24 +1,24 @@ class Solution { -public: - vector<int> nextGreaterElements(vector<int> &nums) { - vector<int> res(nums.size(), -1); - stack<int> st; + public: + vector<int> nextGreaterElements(vector<int> &nums) { + vector<int> res(nums.size(), -1); + stack<int> st; - for (int i = 0; i < nums.size(); i++) { - while (!st.empty() && nums[i] > nums[st.top()]) { - res[st.top()] = nums[i]; - st.pop(); - } - st.push(i); - } + for (int i = 0; i < nums.size(); i++) { + while (!st.empty() && nums[i] > nums[st.top()]) { + res[st.top()] = nums[i]; + st.pop(); + } + st.push(i); + } - for (int i = 0; !st.empty() && i < nums.size(); i++) { - while (!st.empty() && nums[i] > nums[st.top()]) { - res[st.top()] = nums[i]; - st.pop(); - } - } + for (int i = 0; !st.empty() && i < nums.size(); i++) { + while (!st.empty() && nums[i] > nums[st.top()]) { + res[st.top()] = nums[i]; + st.pop(); + } + } - return res; - } + return res; + } }; diff --git a/Problems/0509.cpp b/Problems/0509.cpp @@ -1,26 +1,27 @@ // memorization approach class Solution { -public: - int fib(int n) { - vector<int> f(31); - f[0] = 0; - f[1] = 1; - for (int i = 2; i <= n; i++) f[i] = f[i - 1] + f[i - 2]; - return f[n]; - } + public: + int fib(int n) { + vector<int> f(31); + f[0] = 0; + f[1] = 1; + for (int i = 2; i <= n; i++) + f[i] = f[i - 1] + f[i - 2]; + return f[n]; + } }; // optimized, memorize only the previous two values class Solution { -public: - int fib(int n) { - if (n == 0) return 0; - int a = 0, b = 1; - for (int i = 2; i <= n; i++) { - int tmp = a + b; - a = b; - b = tmp; + public: + int fib(int n) { + if (n == 0) return 0; + int a = 0, b = 1; + for (int i = 2; i <= n; i++) { + int tmp = a + b; + a = b; + b = tmp; + } + return b; } - return b; - } }; diff --git a/Problems/0516.cpp b/Problems/0516.cpp @@ -1,26 +1,25 @@ class Solution { - int len(const string &s, const int sa, const int sb, - vector<vector<int>> &mem) { - if (mem[sa][sb]) return mem[sa][sb]; + int len(const string &s, const int sa, const int sb, vector<vector<int>> &mem) { + if (mem[sa][sb]) return mem[sa][sb]; - int res = 0, a = sa, b = sb; - while (a < b) { - if (s[a] == s[b]) - a++, b--, res += 2; - else { - res += max(len(s, a + 1, b, mem), len(s, a, b - 1, mem)); - break; - } + int res = 0, a = sa, b = sb; + while (a < b) { + if (s[a] == s[b]) + a++, b--, res += 2; + else { + res += max(len(s, a + 1, b, mem), len(s, a, b - 1, mem)); + break; + } + } + if (a == b) res++; + mem[sa][sb] = res; + return res; } - if (a == b) res++; - mem[sa][sb] = res; - return res; - } -public: - int longestPalindromeSubseq(string s) { - int n = s.size(); - vector<vector<int>> mem(n, vector<int>(n)); - return len(s, 0, n - 1, mem); - } + public: + int longestPalindromeSubseq(string s) { + int n = s.size(); + vector<vector<int>> mem(n, vector<int>(n)); + return len(s, 0, n - 1, mem); + } }; diff --git a/Problems/0518.cpp b/Problems/0518.cpp @@ -1,13 +1,13 @@ class Solution { -public: - int change(int amount, vector<int> &coins) { - vector<long long> dp(amount + 1, 0); - dp[0] = 1; + public: + int change(int amount, vector<int> &coins) { + vector<long long> dp(amount + 1, 0); + dp[0] = 1; - for (int coin : coins) - for (int i = 0; i <= amount; i++) - if (i - coin >= 0) dp[i] += dp[i - coin]; + for (int coin : coins) + for (int i = 0; i <= amount; i++) + if (i - coin >= 0) dp[i] += dp[i - coin]; - return (int)dp.back(); - } + return (int)dp.back(); + } }; diff --git a/Problems/0520.cpp b/Problems/0520.cpp @@ -1,9 +1,9 @@ class Solution { -public: - bool detectCapitalUse(string word) { - int count = 0; - for (char &c : word) count += c == toupper(c); - return count == 0 || count == word.size() || - (count == 1 && word[0] == toupper(word[0])); - } + public: + bool detectCapitalUse(string word) { + int count = 0; + for (char &c : word) + count += c == toupper(c); + return count == 0 || count == word.size() || (count == 1 && word[0] == toupper(word[0])); + } }; diff --git a/Problems/0530.cpp b/Problems/0530.cpp @@ -1,21 +1,21 @@ class Solution { -public: - int getMinimumDifference(TreeNode *root) { - stack<TreeNode *> st; - int res = INT_MAX; - TreeNode *prev = new TreeNode(INT_MAX); - while (true) { - while (root) { - st.push(root); - root = root->left; - } - if (st.empty()) break; - root = st.top(); - st.pop(); - res = min(res, abs(prev->val - root->val)); - prev = root; - root = root->right; + public: + int getMinimumDifference(TreeNode *root) { + stack<TreeNode *> st; + int res = INT_MAX; + TreeNode *prev = new TreeNode(INT_MAX); + while (true) { + while (root) { + st.push(root); + root = root->left; + } + if (st.empty()) break; + root = st.top(); + st.pop(); + res = min(res, abs(prev->val - root->val)); + prev = root; + root = root->right; + } + return res; } - return res; - } }; diff --git a/Problems/0532.cpp b/Problems/0532.cpp @@ -1,16 +1,19 @@ class Solution { -public: - int findPairs(vector<int> &nums, int k) { - int res = 0; - if (k == 0) { - unordered_map<int, int> um; - for (int n : nums) um[n]++; - for (const auto &[n, v] : um) res += v >= 2; - return res; - } else { - unordered_set<int> us(nums.begin(), nums.end()); - for (const auto &n : us) res += us.count(n + k) + us.count(n - k); - return res / 2; + public: + int findPairs(vector<int> &nums, int k) { + int res = 0; + if (k == 0) { + unordered_map<int, int> um; + for (int n : nums) + um[n]++; + for (const auto &[n, v] : um) + res += v >= 2; + return res; + } else { + unordered_set<int> us(nums.begin(), nums.end()); + for (const auto &n : us) + res += us.count(n + k) + us.count(n - k); + return res / 2; + } } - } }; diff --git a/Problems/0535.cpp b/Problems/0535.cpp @@ -1,17 +1,15 @@ class Solution { unordered_map<string, int> um; vector<string> str; -public: - string encode(const string& longUrl) { - if(um.count(longUrl)) return to_string(um[longUrl]); + + public: + string encode(const string &longUrl) { + if (um.count(longUrl)) return to_string(um[longUrl]); um.insert({longUrl, str.size()}); str.push_back(longUrl); return to_string(str.size() - 1); } - string decode(const string& shortUrl) { - return str[stoi(shortUrl)]; - } + string decode(const string &shortUrl) { return str[stoi(shortUrl)]; } }; - diff --git a/Problems/0538.cpp b/Problems/0538.cpp @@ -1,19 +1,19 @@ class Solution { -public: - TreeNode *convertBST(TreeNode *root) { - TreeNode *head = root; - stack<TreeNode *> st; - int sum = 0; - while (true) { - while (root) { - st.push(root); - root = root->right; - } - if (st.empty()) break; - root = st.top(), st.pop(); - sum = root->val += sum; - root = root->left; + public: + TreeNode *convertBST(TreeNode *root) { + TreeNode *head = root; + stack<TreeNode *> st; + int sum = 0; + while (true) { + while (root) { + st.push(root); + root = root->right; + } + if (st.empty()) break; + root = st.top(), st.pop(); + sum = root->val += sum; + root = root->left; + } + return head; } - return head; - } }; diff --git a/Problems/0540.cpp b/Problems/0540.cpp @@ -1,15 +1,14 @@ class Solution { -public: - int singleNonDuplicate(vector<int> &nums) { - int low = 0, high = nums.size() - 1; - while (low < high) { - int mid = low + (high - low) / 2; - if ((mid % 2 == 0 && nums[mid] == nums[mid + 1]) || - (mid % 2 == 1 && nums[mid] == nums[mid - 1])) - low = mid + 1; - else - high = mid; + public: + int singleNonDuplicate(vector<int> &nums) { + int low = 0, high = nums.size() - 1; + while (low < high) { + int mid = low + (high - low) / 2; + if ((mid % 2 == 0 && nums[mid] == nums[mid + 1]) || (mid % 2 == 1 && nums[mid] == nums[mid - 1])) + low = mid + 1; + else + high = mid; + } + return nums[low]; } - return nums[low]; - } }; diff --git a/Problems/0542.cpp b/Problems/0542.cpp @@ -1,46 +1,41 @@ class Solution { - int m, n; - vector<pair<int, int>> offset = { - {-1, 0}, - { 1, 0}, - { 0, -1}, - { 0, 1} - }; + int m, n; + vector<pair<int, int>> offset = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; - int valid(int sr, int sc) { return sr >= 0 && sr < m && sc >= 0 && sc < n; } + int valid(int sr, int sc) { return sr >= 0 && sr < m && sc >= 0 && sc < n; } -public: - vector<vector<int>> updateMatrix(vector<vector<int>> &mat) { - m = mat.size(); - n = mat[0].size(); + public: + vector<vector<int>> updateMatrix(vector<vector<int>> &mat) { + m = mat.size(); + n = mat[0].size(); - vector<vector<int>> res(m, vector<int>(n, INT_MAX)); - queue<pair<int, int>> q; + vector<vector<int>> res(m, vector<int>(n, INT_MAX)); + queue<pair<int, int>> q; - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (mat[i][j] == 0) { - res[i][j] = 0; - q.push({i, j}); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 0) { + res[i][j] = 0; + q.push({i, j}); + } + } } - } - } - while (!q.empty()) { - auto [sr, sc] = q.front(); - q.pop(); - for (auto &p : offset) { - int nsr = sr + p.first; - int nsc = sc + p.second; - if (valid(nsr, nsc)) { - if (res[nsr][nsc] > res[sr][sc] + 1) { - res[nsr][nsc] = res[sr][sc] + 1; - q.push({nsr, nsc}); - } + while (!q.empty()) { + auto [sr, sc] = q.front(); + q.pop(); + for (auto &p : offset) { + int nsr = sr + p.first; + int nsc = sc + p.second; + if (valid(nsr, nsc)) { + if (res[nsr][nsc] > res[sr][sc] + 1) { + res[nsr][nsc] = res[sr][sc] + 1; + q.push({nsr, nsc}); + } + } + } } - } - } - return res; - } + return res; + } }; diff --git a/Problems/0543.cpp b/Problems/0543.cpp @@ -1,35 +1,35 @@ class Solution { -public: - int diameterOfBinaryTree(TreeNode *root) { - unordered_map<TreeNode *, int> um; - stack<TreeNode *> st; - int res = 0; + public: + int diameterOfBinaryTree(TreeNode *root) { + unordered_map<TreeNode *, int> um; + stack<TreeNode *> st; + int res = 0; - while (root) { - st.push(root); - root = root->left; - } - - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (um.find(root) == um.end()) { - um.insert({root, 1}); - st.push(root); - root = root->right; while (root) { - st.push(root); - root = root->left; + st.push(root); + root = root->left; } - } else { - if (!root->left && !root->right) continue; - int l = um[root->left]; - int r = um[root->right]; - res = max(l + r, res); - um[root] = 1 + max(l, r); - } - } - return res; - } + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (um.find(root) == um.end()) { + um.insert({root, 1}); + st.push(root); + root = root->right; + while (root) { + st.push(root); + root = root->left; + } + } else { + if (!root->left && !root->right) continue; + int l = um[root->left]; + int r = um[root->right]; + res = max(l + r, res); + um[root] = 1 + max(l, r); + } + } + + return res; + } }; diff --git a/Problems/0547.cpp b/Problems/0547.cpp @@ -1,44 +1,44 @@ class UnionFind { - vector<int> root, rank; - int n; + vector<int> root, rank; + int n; -public: - UnionFind(int n) : n(n), root(n), rank(n, 1) { - iota(root.begin(), root.end(), 0); - } + public: + UnionFind(int n) : n(n), root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } - void join(int x, int y) { - x = find(x), y = find(y); + void join(int x, int y) { + x = find(x), y = find(y); - if (x != y) { - if (rank[x] > rank[y]) swap(x, y); + if (x != y) { + if (rank[x] > rank[y]) swap(x, y); - root[x] = y; - rank[y] += rank[x]; + root[x] = y; + rank[y] += rank[x]; + } } - } - int count() { - int cnt = 0; - for (int i = 0; i < n; i++) cnt += root[i] == i; - return cnt; - } + int count() { + int cnt = 0; + for (int i = 0; i < n; i++) + cnt += root[i] == i; + return cnt; + } }; class Solution { -public: - int findCircleNum(vector<vector<int>> &isConnected) { - int n = isConnected.size(); - UnionFind uf(n); - for (int i = 0; i < n; i++) - for (int j = i + 1; j < n; j++) - if (isConnected[i][j]) uf.join(i, j); - - return uf.count(); - } + public: + int findCircleNum(vector<vector<int>> &isConnected) { + int n = isConnected.size(); + UnionFind uf(n); + for (int i = 0; i < n; i++) + for (int j = i + 1; j < n; j++) + if (isConnected[i][j]) uf.join(i, j); + + return uf.count(); + } }; diff --git a/Problems/0556.cpp b/Problems/0556.cpp @@ -1,24 +1,24 @@ class Solution { -public: - int nextGreaterElement(int n) { - string nums = to_string(n); + public: + int nextGreaterElement(int n) { + string nums = to_string(n); - int prev = 0; - stack<int> st; - for (int i = nums.size() - 1; i >= 0; i--) { - if (!st.empty() && nums[i] < nums[st.top()]) { - while (!st.empty() && nums[i] < nums[st.top()]) { - prev = st.top(); - st.pop(); + int prev = 0; + stack<int> st; + for (int i = nums.size() - 1; i >= 0; i--) { + if (!st.empty() && nums[i] < nums[st.top()]) { + while (!st.empty() && nums[i] < nums[st.top()]) { + prev = st.top(); + st.pop(); + } + swap(nums[i], nums[prev]); + reverse(nums.begin() + i + 1, nums.end()); + break; + } + st.push(i); } - swap(nums[i], nums[prev]); - reverse(nums.begin() + i + 1, nums.end()); - break; - } - st.push(i); - } - long long res = stoll(nums); - return (res > INT_MAX || (int)res == n) ? -1 : (int)res; - } + long long res = stoll(nums); + return (res > INT_MAX || (int)res == n) ? -1 : (int)res; + } }; diff --git a/Problems/0557.cpp b/Problems/0557.cpp @@ -1,15 +1,16 @@ class Solution { -public: - string reverseWords(string s) { - int last = -1; - for (int k = 0; k <= s.size(); k++) { - if (k == s.size() || s[k] == ' ') { - int i = last + 1; - int j = k - 1; - while (i < j) swap(s[i++], s[j--]); - last = k; - } + public: + string reverseWords(string s) { + int last = -1; + for (int k = 0; k <= s.size(); k++) { + if (k == s.size() || s[k] == ' ') { + int i = last + 1; + int j = k - 1; + while (i < j) + swap(s[i++], s[j--]); + last = k; + } + } + return s; } - return s; - } }; diff --git a/Problems/0559.cpp b/Problems/0559.cpp @@ -1,18 +1,19 @@ class Solution { -public: - int maxDepth(Node *root) { - if (!root) return 0; + public: + int maxDepth(Node *root) { + if (!root) return 0; - int lvl; - queue<Node *> q; - q.push(root); - for (lvl = 0; !q.empty(); lvl++) { - for (int t = q.size(); t > 0; t--) { - Node *root = q.front(); - q.pop(); - for (Node *c : root->children) q.push(c); - } + int lvl; + queue<Node *> q; + q.push(root); + for (lvl = 0; !q.empty(); lvl++) { + for (int t = q.size(); t > 0; t--) { + Node *root = q.front(); + q.pop(); + for (Node *c : root->children) + q.push(c); + } + } + return lvl; } - return lvl; - } }; diff --git a/Problems/0560.cpp b/Problems/0560.cpp @@ -1,17 +1,18 @@ class Solution { -public: - int subarraySum(vector<int> &nums, int k) { - int n = nums.size(), res = 0, sum = 0; - unordered_map<int, int> um; - vector<int> prefix(n); - for (int i = 0; i < n; i++) sum = prefix[i] = sum + nums[i]; + public: + int subarraySum(vector<int> &nums, int k) { + int n = nums.size(), res = 0, sum = 0; + unordered_map<int, int> um; + vector<int> prefix(n); + for (int i = 0; i < n; i++) + sum = prefix[i] = sum + nums[i]; - for (int i = 0; i < n; i++) { - if (prefix[i] == k) res++; - if (um.count(prefix[i] - k)) res += um[prefix[i] - k]; - um[prefix[i]]++; - } + for (int i = 0; i < n; i++) { + if (prefix[i] == k) res++; + if (um.count(prefix[i] - k)) res += um[prefix[i] - k]; + um[prefix[i]]++; + } - return res; - } + return res; + } }; diff --git a/Problems/0561.cpp b/Problems/0561.cpp @@ -1,21 +1,22 @@ class Solution { - const static int length = 20001; + const static int length = 20001; -public: - int arrayPairSum(vector<int> &nums) { - int arr[length] = {0}; + public: + int arrayPairSum(vector<int> &nums) { + int arr[length] = {0}; - for (int i : nums) arr[i + 10000]++; + for (int i : nums) + arr[i + 10000]++; - int res = 0; - int sub = 0; - for (int i = 0; i < length; i++) { - if (!arr[i]) continue; + int res = 0; + int sub = 0; + for (int i = 0; i < length; i++) { + if (!arr[i]) continue; - arr[i] -= sub; - res += (arr[i] / 2 + arr[i] % 2) * (i - 10000); - sub = arr[i] % 2; + arr[i] -= sub; + res += (arr[i] / 2 + arr[i] % 2) * (i - 10000); + sub = arr[i] % 2; + } + return res; } - return res; - } }; diff --git a/Problems/0563.cpp b/Problems/0563.cpp @@ -1,18 +1,18 @@ class Solution { - int res = 0; + int res = 0; - int sum_adding_tilt(TreeNode *root) { - if (!root) return 0; - int l = sum_adding_tilt(root->left); - int r = sum_adding_tilt(root->right); - res += abs(l - r); - return l + r + root->val; - } + int sum_adding_tilt(TreeNode *root) { + if (!root) return 0; + int l = sum_adding_tilt(root->left); + int r = sum_adding_tilt(root->right); + res += abs(l - r); + return l + r + root->val; + } -public: - int findTilt(TreeNode *root) { - res = 0; - sum_adding_tilt(root); - return res; - } + public: + int findTilt(TreeNode *root) { + res = 0; + sum_adding_tilt(root); + return res; + } }; diff --git a/Problems/0566.cpp b/Problems/0566.cpp @@ -1,20 +1,20 @@ class Solution { -public: - vector<vector<int>> matrixReshape(vector<vector<int>> &mat, int r, int c) { - int n = mat.size(), m = mat[0].size(); - if (m * n != r * c) return mat; - vector<vector<int>> nmat(r, vector<int>(c)); + public: + vector<vector<int>> matrixReshape(vector<vector<int>> &mat, int r, int c) { + int n = mat.size(), m = mat[0].size(); + if (m * n != r * c) return mat; + vector<vector<int>> nmat(r, vector<int>(c)); - int x = 0, y = 0; - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - nmat[x][y] = mat[i][j]; - y++; - x += y / c; - y %= c; - } - } + int x = 0, y = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + nmat[x][y] = mat[i][j]; + y++; + x += y / c; + y %= c; + } + } - return nmat; - } + return nmat; + } }; diff --git a/Problems/0567.cpp b/Problems/0567.cpp @@ -1 +1 @@ -Formating: Problems/0567.cpp +Formating : Problems / 0567.cpp diff --git a/Problems/0572.cpp b/Problems/0572.cpp @@ -1,47 +1,47 @@ class Solution { - bool strStr(string haystack, string needle) { - int m = haystack.size(), n = needle.size(); - vector<int> table(needle.size(), 0); + bool strStr(string haystack, string needle) { + int m = haystack.size(), n = needle.size(); + vector<int> table(needle.size(), 0); - for (int len = 0, j = 1; j < n;) { - if (needle[j] == needle[len]) - table[j++] = ++len; - else if (len) - len = table[len - 1]; - else - table[j++] = 0; - } + for (int len = 0, j = 1; j < n;) { + if (needle[j] == needle[len]) + table[j++] = ++len; + else if (len) + len = table[len - 1]; + else + table[j++] = 0; + } - for (int i = 0, j = 0; i < m;) { - if (haystack[i] == needle[j]) i++, j++; - if (j == n) return true; - if (i < m && haystack[i] != needle[j]) j ? j = table[j - 1] : i++; - } + for (int i = 0, j = 0; i < m;) { + if (haystack[i] == needle[j]) i++, j++; + if (j == n) return true; + if (i < m && haystack[i] != needle[j]) j ? j = table[j - 1] : i++; + } - return false; - } + return false; + } - string tree_preorder_string(TreeNode *root) { - if (!root) return ""; - string res = ""; - stack<TreeNode *> st; + string tree_preorder_string(TreeNode *root) { + if (!root) return ""; + string res = ""; + stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - res += root ? "_" + to_string(root->val) : "#"; - if (!root) continue; - st.push(root->right); - st.push(root->left); + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + res += root ? "_" + to_string(root->val) : "#"; + if (!root) continue; + st.push(root->right); + st.push(root->left); + } + return res; } - return res; - } -public: - bool isSubtree(TreeNode *root, TreeNode *subRoot) { - string tree = tree_preorder_string(root); - string sub = tree_preorder_string(subRoot); - return strStr(tree, sub); - } + public: + bool isSubtree(TreeNode *root, TreeNode *subRoot) { + string tree = tree_preorder_string(root); + string sub = tree_preorder_string(subRoot); + return strStr(tree, sub); + } }; diff --git a/Problems/0583.cpp b/Problems/0583.cpp @@ -1,18 +1,17 @@ class Solution { - vector<vector<int>> dp; + vector<vector<int>> dp; - int solve(const string &s1, const string &s2, int i, int j) { - if (i == s1.size() && j == s2.size()) return 0; - if (i == s1.size() || j == s2.size()) - return max(s1.size() - i, s2.size() - j); - if (dp[i][j] != INT_MAX) return dp[i][j]; - if (s1[i] == s2[j]) return solve(s1, s2, i + 1, j + 1); - return dp[i][j] = 1 + min(solve(s1, s2, i + 1, j), solve(s1, s2, i, j + 1)); - } + int solve(const string &s1, const string &s2, int i, int j) { + if (i == s1.size() && j == s2.size()) return 0; + if (i == s1.size() || j == s2.size()) return max(s1.size() - i, s2.size() - j); + if (dp[i][j] != INT_MAX) return dp[i][j]; + if (s1[i] == s2[j]) return solve(s1, s2, i + 1, j + 1); + return dp[i][j] = 1 + min(solve(s1, s2, i + 1, j), solve(s1, s2, i, j + 1)); + } -public: - int minDistance(const string &word1, const string &word2) { - dp.resize(size(word1) + 1, vector<int>(size(word2) + 1, INT_MAX)); - return solve(word1, word2, 0, 0); - } + public: + int minDistance(const string &word1, const string &word2) { + dp.resize(size(word1) + 1, vector<int>(size(word2) + 1, INT_MAX)); + return solve(word1, word2, 0, 0); + } }; diff --git a/Problems/0589.cpp b/Problems/0589.cpp @@ -1,17 +1,18 @@ class Solution { -public: - vector<int> preorder(Node *root) { - if (!root) return {}; - vector<int> res; - stack<Node *> st; - st.push(root); - while (!st.empty()) { - Node *root = st.top(); - st.pop(); - res.push_back(root->val); - reverse(root->children.begin(), root->children.end()); - for (Node *c : root->children) st.push(c); + public: + vector<int> preorder(Node *root) { + if (!root) return {}; + vector<int> res; + stack<Node *> st; + st.push(root); + while (!st.empty()) { + Node *root = st.top(); + st.pop(); + res.push_back(root->val); + reverse(root->children.begin(), root->children.end()); + for (Node *c : root->children) + st.push(c); + } + return res; } - return res; - } }; diff --git a/Problems/0590.cpp b/Problems/0590.cpp @@ -1,17 +1,18 @@ class Solution { -public: - vector<int> postorder(Node *root) { - if (!root) return {}; - vector<int> res; - stack<Node *> st; - st.push(root); - while (!st.empty()) { - Node *root = st.top(); - st.pop(); - for (Node *c : root->children) st.push(c); - res.push_back(root->val); + public: + vector<int> postorder(Node *root) { + if (!root) return {}; + vector<int> res; + stack<Node *> st; + st.push(root); + while (!st.empty()) { + Node *root = st.top(); + st.pop(); + for (Node *c : root->children) + st.push(c); + res.push_back(root->val); + } + reverse(res.begin(), res.end()); + return res; } - reverse(res.begin(), res.end()); - return res; - } }; diff --git a/Problems/0605.cpp b/Problems/0605.cpp @@ -1,18 +1,18 @@ class Solution { -public: - bool canPlaceFlowers(vector<int> &flowerbed, int n) { - int count = 1; - flowerbed.push_back(0); - flowerbed.push_back(1); - for (int crnt : flowerbed) { - if (!crnt) - count++; - else { - if (count >= 3) n -= (count - 3) / 2 + 1; - if (n <= 0) return true; - count = 0; - } + public: + bool canPlaceFlowers(vector<int> &flowerbed, int n) { + int count = 1; + flowerbed.push_back(0); + flowerbed.push_back(1); + for (int crnt : flowerbed) { + if (!crnt) + count++; + else { + if (count >= 3) n -= (count - 3) / 2 + 1; + if (n <= 0) return true; + count = 0; + } + } + return false; } - return false; - } }; diff --git a/Problems/0606.cpp b/Problems/0606.cpp @@ -1,29 +1,29 @@ class Solution { -public: - string tree2str(TreeNode *root) { - if (!root) return ""; + public: + string tree2str(TreeNode *root) { + if (!root) return ""; - string res = ""; - stack<TreeNode *> st; - unordered_set<TreeNode *> us; + string res = ""; + stack<TreeNode *> st; + unordered_set<TreeNode *> us; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - if (us.find(root) != us.end()) { - res += ")"; - st.pop(); - } else { - us.insert(root); - res += "(" + to_string(root->val); - if (!root->left && !root->right) continue; - if (root->right) st.push(root->right); - if (root->left) - st.push(root->left); - else - res += "()"; - } + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + if (us.find(root) != us.end()) { + res += ")"; + st.pop(); + } else { + us.insert(root); + res += "(" + to_string(root->val); + if (!root->left && !root->right) continue; + if (root->right) st.push(root->right); + if (root->left) + st.push(root->left); + else + res += "()"; + } + } + return res.substr(1, res.size() - 2); } - return res.substr(1, res.size() - 2); - } }; diff --git a/Problems/0617.cpp b/Problems/0617.cpp @@ -1,15 +1,14 @@ class Solution { -public: - TreeNode *mergeTrees(TreeNode *root1, TreeNode *root2) { - if (!root1 && !root2) return nullptr; - if (!root2) - return new TreeNode(root1->val, mergeTrees(root1->left, nullptr), - mergeTrees(root1->right, nullptr)); - if (!root1) - return new TreeNode(root2->val, mergeTrees(nullptr, root2->left), - mergeTrees(nullptr, root2->right)); - return new TreeNode(root1->val + root2->val, - mergeTrees(root1->left, root2->left), - mergeTrees(root1->right, root2->right)); - } + public: + TreeNode *mergeTrees(TreeNode *root1, TreeNode *root2) { + if (!root1 && !root2) return nullptr; + if (!root2) + return new TreeNode(root1->val, mergeTrees(root1->left, nullptr), + mergeTrees(root1->right, nullptr)); + if (!root1) + return new TreeNode(root2->val, mergeTrees(nullptr, root2->left), + mergeTrees(nullptr, root2->right)); + return new TreeNode(root1->val + root2->val, mergeTrees(root1->left, root2->left), + mergeTrees(root1->right, root2->right)); + } }; diff --git a/Problems/0621.cpp b/Problems/0621.cpp @@ -1,21 +1,22 @@ class Solution { -public: - int leastInterval(vector<char> &tasks, int n) { - if (n == 0) return tasks.size(); + public: + int leastInterval(vector<char> &tasks, int n) { + if (n == 0) return tasks.size(); - vector<int> count(26); - for (char t : tasks) count[t - 'A']++; + vector<int> count(26); + for (char t : tasks) + count[t - 'A']++; - int maxi = INT_MIN, cnt = 0; - for (int n : count) { - if (n == maxi) - cnt++; - else if (n > maxi) { - maxi = n; - cnt = 1; - } - } + int maxi = INT_MIN, cnt = 0; + for (int n : count) { + if (n == maxi) + cnt++; + else if (n > maxi) { + maxi = n; + cnt = 1; + } + } - return max((int)tasks.size(), (maxi - 1) * (n + 1) + cnt); - } + return max((int)tasks.size(), (maxi - 1) * (n + 1) + cnt); + } }; diff --git a/Problems/0637.cpp b/Problems/0637.cpp @@ -1,25 +1,25 @@ class Solution { -public: - vector<double> averageOfLevels(TreeNode *root) { - if (!root) return {}; + public: + vector<double> averageOfLevels(TreeNode *root) { + if (!root) return {}; - vector<double> res; - queue<TreeNode *> q; + vector<double> res; + queue<TreeNode *> q; - q.push(root); - for (int lvl = 0; !q.empty(); lvl++) { - int cnt = 0; - double sum = 0; - for (int t = q.size(); t > 0; t--) { - TreeNode *root = q.front(); - q.pop(); - sum += root->val; - cnt++; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } - res.push_back(sum / cnt); + q.push(root); + for (int lvl = 0; !q.empty(); lvl++) { + int cnt = 0; + double sum = 0; + for (int t = q.size(); t > 0; t--) { + TreeNode *root = q.front(); + q.pop(); + sum += root->val; + cnt++; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + res.push_back(sum / cnt); + } + return res; } - return res; - } }: diff --git a/Problems/0646.cpp b/Problems/0646.cpp @@ -1,32 +1,31 @@ // DP, O(n^2) class Solution { -public: - int findLongestChain(vector<vector<int>> &pairs) { - sort(begin(pairs), end(pairs)); - const int n = pairs.size(); - int res = 1, count[1001] = {0}; - for (int i = n - 1; i >= 0; i--) { - for (int j = i + 1; j < n; j++) { - if (pairs[i][1] < pairs[j][0]) count[i] = max(count[i], count[j]); - } - res = max(res, ++count[i]); - } + public: + int findLongestChain(vector<vector<int>> &pairs) { + sort(begin(pairs), end(pairs)); + const int n = pairs.size(); + int res = 1, count[1001] = {0}; + for (int i = n - 1; i >= 0; i--) { + for (int j = i + 1; j < n; j++) { + if (pairs[i][1] < pairs[j][0]) count[i] = max(count[i], count[j]); + } + res = max(res, ++count[i]); + } - return res; - } + return res; + } }; // Greedy, O(nlogn) class Solution { -public: - int findLongestChain(vector<vector<int>> &pairs) { - sort(pairs.begin(), pairs.end(), - [](const auto &a, const auto &b) { return a[1] < b[1]; }); + public: + int findLongestChain(vector<vector<int>> &pairs) { + sort(pairs.begin(), pairs.end(), [](const auto &a, const auto &b) { return a[1] < b[1]; }); - int curr = INT_MIN, ans = 0; - for (const auto &pair : pairs) { - if (pair[0] > curr) curr = pair[1], ans++; + int curr = INT_MIN, ans = 0; + for (const auto &pair : pairs) { + if (pair[0] > curr) curr = pair[1], ans++; + } + return ans; } - return ans; - } }; diff --git a/Problems/0649.cpp b/Problems/0649.cpp @@ -1,20 +1,21 @@ class Solution { -public: - string predictPartyVictory(string senate) { - queue<int> rq, dq; - int n = senate.size(); + public: + string predictPartyVictory(string senate) { + queue<int> rq, dq; + int n = senate.size(); - for (int i = 0; i < n; i++) (senate[i] == 'R' ? rq : dq).push(i); + for (int i = 0; i < n; i++) + (senate[i] == 'R' ? rq : dq).push(i); - while (!rq.empty() && !dq.empty()) { - int a = rq.front(), b = dq.front(); - rq.pop(), dq.pop(); - if (a < b) - rq.push(a + n); - else - dq.push(b + n); - } + while (!rq.empty() && !dq.empty()) { + int a = rq.front(), b = dq.front(); + rq.pop(), dq.pop(); + if (a < b) + rq.push(a + n); + else + dq.push(b + n); + } - return rq.size() ? "Radiant" : "Dire"; - } + return rq.size() ? "Radiant" : "Dire"; + } }; diff --git a/Problems/0652.cpp b/Problems/0652.cpp @@ -1,34 +1,33 @@ class Solution { -public: - vector<TreeNode *> findDuplicateSubtrees(TreeNode *root) { - if (!root) return {}; + public: + vector<TreeNode *> findDuplicateSubtrees(TreeNode *root) { + if (!root) return {}; - unordered_map<string, vector<TreeNode *>> seen; - unordered_map<TreeNode *, string> um; - vector<TreeNode *> res; - stack<TreeNode *> st; + unordered_map<string, vector<TreeNode *>> seen; + unordered_map<TreeNode *, string> um; + vector<TreeNode *> res; + stack<TreeNode *> st; - st.push(root); - um[nullptr] = "#"; - while (!st.empty()) { - auto root = st.top(); + st.push(root); + um[nullptr] = "#"; + while (!st.empty()) { + auto root = st.top(); - if (um.count(root)) { - um[root] = - to_string(root->val) + ' ' + um[root->left] + ' ' + um[root->right]; - seen[um[root]].push_back(root); - st.pop(); - continue; - } + if (um.count(root)) { + um[root] = to_string(root->val) + ' ' + um[root->left] + ' ' + um[root->right]; + seen[um[root]].push_back(root); + st.pop(); + continue; + } - um[root] = ""; - if (root->right) st.push(root->right); - if (root->left) st.push(root->left); - } + um[root] = ""; + if (root->right) st.push(root->right); + if (root->left) st.push(root->left); + } - for (const auto &[k, v] : seen) - if (v.size() > 1) res.push_back(v.back()); + for (const auto &[k, v] : seen) + if (v.size() > 1) res.push_back(v.back()); - return res; - } + return res; + } }; diff --git a/Problems/0653.cpp b/Problems/0653.cpp @@ -1,24 +1,25 @@ class Solution { - TreeNode *root; - TreeNode *find(int k) { - TreeNode *t = root; - while (t && t->val != k) t = t->val > k ? t->left : t->right; - return t; - } + TreeNode *root; + TreeNode *find(int k) { + TreeNode *t = root; + while (t && t->val != k) + t = t->val > k ? t->left : t->right; + return t; + } -public: - bool findTarget(TreeNode *root, int k) { - stack<TreeNode *> st; - st.push(this->root = root); - while (!st.empty()) { - TreeNode *t, *root = st.top(); - st.pop(); - while (root) { - if ((t = find(k - root->val)) && t != root) return true; - if (root->right) st.push(root->right); - root = root->left; - } + public: + bool findTarget(TreeNode *root, int k) { + stack<TreeNode *> st; + st.push(this->root = root); + while (!st.empty()) { + TreeNode *t, *root = st.top(); + st.pop(); + while (root) { + if ((t = find(k - root->val)) && t != root) return true; + if (root->right) st.push(root->right); + root = root->left; + } + } + return false; } - return false; - } }; diff --git a/Problems/0654.cpp b/Problems/0654.cpp @@ -1,33 +1,33 @@ class Solution { - struct record { - TreeNode **parent; - int start, end; - record(TreeNode **p, int s, int e) : parent(p), start(s), end(e) {} - }; + struct record { + TreeNode **parent; + int start, end; + record(TreeNode **p, int s, int e) : parent(p), start(s), end(e) {} + }; -public: - TreeNode *constructMaximumBinaryTree(vector<int> &nums) { - TreeNode *head, tmp; - stack<record> st; + public: + TreeNode *constructMaximumBinaryTree(vector<int> &nums) { + TreeNode *head, tmp; + stack<record> st; - head = new TreeNode(-1); - st.push({&head->right, 0, (int)nums.size()}); - while (!st.empty()) { - auto [root, start, end] = st.top(); - st.pop(); - while (start < end) { - int index = -1; - for (int i = start, maxi = INT_MIN; i < end; i++) - if (nums[i] > maxi) { - maxi = nums[i]; - index = i; - } - *root = new TreeNode(nums[index]); - st.push({&(*root)->left, start, index}); - root = &(*root)->right; - start = index + 1; - } + head = new TreeNode(-1); + st.push({&head->right, 0, (int)nums.size()}); + while (!st.empty()) { + auto [root, start, end] = st.top(); + st.pop(); + while (start < end) { + int index = -1; + for (int i = start, maxi = INT_MIN; i < end; i++) + if (nums[i] > maxi) { + maxi = nums[i]; + index = i; + } + *root = new TreeNode(nums[index]); + st.push({&(*root)->left, start, index}); + root = &(*root)->right; + start = index + 1; + } + } + return head->right; } - return head->right; - } }; diff --git a/Problems/0662.cpp b/Problems/0662.cpp @@ -1,25 +1,25 @@ class Solution { -public: - int widthOfBinaryTree(TreeNode *root) { - if (root == NULL) return 0; - queue<pair<TreeNode *, int>> q; + public: + int widthOfBinaryTree(TreeNode *root) { + if (root == NULL) return 0; + queue<pair<TreeNode *, int>> q; - int res = 1; - q.push({root, 0}); - while (!q.empty()) { - int start = q.front().second, end = q.back().second; + int res = 1; + q.push({root, 0}); + while (!q.empty()) { + int start = q.front().second, end = q.back().second; - res = max(res, end - start + 1); - for (int k = q.size(); k > 0; k--) { - pair<TreeNode *, int> p = q.front(); - q.pop(); - int idx = p.second - start; + res = max(res, end - start + 1); + for (int k = q.size(); k > 0; k--) { + pair<TreeNode *, int> p = q.front(); + q.pop(); + int idx = p.second - start; - if (p.first->left) q.push({p.first->left, 2ll * idx + 1}); - if (p.first->right) q.push({p.first->right, 2ll * idx + 2}); - } - } + if (p.first->left) q.push({p.first->left, 2ll * idx + 1}); + if (p.first->right) q.push({p.first->right, 2ll * idx + 2}); + } + } - return res; - } + return res; + } }; diff --git a/Problems/0664.cpp b/Problems/0664.cpp @@ -1,22 +1,22 @@ class Solution { - int dp[101][101]; - int rec(const string &s, int l, int r) { - if (dp[l][r] != -1) return dp[l][r]; - int res = s.size(), j = -1; - for (int i = l; i < r; i++) { - if (s[i] != s[r] && j == -1) j = i; - if (j != -1) res = min(res, 1 + rec(s, j, i) + rec(s, i + 1, r)); + int dp[101][101]; + int rec(const string &s, int l, int r) { + if (dp[l][r] != -1) return dp[l][r]; + int res = s.size(), j = -1; + for (int i = l; i < r; i++) { + if (s[i] != s[r] && j == -1) j = i; + if (j != -1) res = min(res, 1 + rec(s, j, i) + rec(s, i + 1, r)); + } + return dp[l][r] = j != -1 ? res : 0; } - return dp[l][r] = j != -1 ? res : 0; - } -public: - Solution() { memset(dp, 0xFF, sizeof(dp)); } - int strangePrinter(string &s) { - int j = 1; - for (int i = 1; i < s.size(); i++) - if (s[i] != s[i - 1]) s[j++] = s[i]; + public: + Solution() { memset(dp, 0xFF, sizeof(dp)); } + int strangePrinter(string &s) { + int j = 1; + for (int i = 1; i < s.size(); i++) + if (s[i] != s[i - 1]) s[j++] = s[i]; - return rec(s, 0, j - 1) + 1; - } + return rec(s, 0, j - 1) + 1; + } }; diff --git a/Problems/0669.cpp b/Problems/0669.cpp @@ -1,34 +1,34 @@ class Solution { -public: - TreeNode *trimBST(TreeNode *root, int low, int high) { - if (!root) return nullptr; - while (root) { - if (root->val < low) - root = root->right; - else if (root->val > high) - root = root->left; - else - break; - } - stack<pair<TreeNode *, TreeNode **>> st; - TreeNode *head = root, **link = nullptr; - while (true) { - while (root) { - if (root->val < low) - root = *link = root->right; - else if (root->val > high) - root = *link = root->left; - else { - if (root->right) st.push({root->right, &root->right}); - link = &root->left; - root = root->left; + public: + TreeNode *trimBST(TreeNode *root, int low, int high) { + if (!root) return nullptr; + while (root) { + if (root->val < low) + root = root->right; + else if (root->val > high) + root = root->left; + else + break; + } + stack<pair<TreeNode *, TreeNode **>> st; + TreeNode *head = root, **link = nullptr; + while (true) { + while (root) { + if (root->val < low) + root = *link = root->right; + else if (root->val > high) + root = *link = root->left; + else { + if (root->right) st.push({root->right, &root->right}); + link = &root->left; + root = root->left; + } + } + if (st.empty()) break; + root = st.top().first; + link = st.top().second; + st.pop(); } - } - if (st.empty()) break; - root = st.top().first; - link = st.top().second; - st.pop(); + return head; } - return head; - } }; diff --git a/Problems/0671.cpp b/Problems/0671.cpp @@ -1,21 +1,21 @@ class Solution { -public: - int findSecondMinimumValue(TreeNode *root) { - if (!root) return -1; - int val = root->val; - long long res = LONG_MAX; - stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (!root->left) continue; - int m = max(root->left->val, root->right->val); - if (m != val) res = min(res, (long long)m); - if (root->left->val == val) st.push(root->left); - if (root->right->val == val) st.push(root->right); - } + public: + int findSecondMinimumValue(TreeNode *root) { + if (!root) return -1; + int val = root->val; + long long res = LONG_MAX; + stack<TreeNode *> st; + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (!root->left) continue; + int m = max(root->left->val, root->right->val); + if (m != val) res = min(res, (long long)m); + if (root->left->val == val) st.push(root->left); + if (root->right->val == val) st.push(root->right); + } - return res != LONG_MAX ? res : -1; - } + return res != LONG_MAX ? res : -1; + } }; diff --git a/Problems/0673.cpp b/Problems/0673.cpp @@ -1,22 +1,21 @@ class Solution { -public: - int findNumberOfLIS(vector<int> &nums) { - int n = nums.size(), res = 0, max_len = 0; - vector<pair<int, int>> dp(n, {1, 1}); - for (int i = 0; i < n; i++) { - for (int j = 0; j < i; j++) { - if (nums[i] > nums[j]) { - if (dp[i].first == dp[j].first + 1) dp[i].second += dp[j].second; - if (dp[i].first < dp[j].first + 1) - dp[i] = {dp[j].first + 1, dp[j].second}; + public: + int findNumberOfLIS(vector<int> &nums) { + int n = nums.size(), res = 0, max_len = 0; + vector<pair<int, int>> dp(n, {1, 1}); + for (int i = 0; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + if (dp[i].first == dp[j].first + 1) dp[i].second += dp[j].second; + if (dp[i].first < dp[j].first + 1) dp[i] = {dp[j].first + 1, dp[j].second}; + } + } + if (max_len == dp[i].first) res += dp[i].second; + if (max_len < dp[i].first) { + max_len = dp[i].first; + res = dp[i].second; + } } - } - if (max_len == dp[i].first) res += dp[i].second; - if (max_len < dp[i].first) { - max_len = dp[i].first; - res = dp[i].second; - } + return res; } - return res; - } }; diff --git a/Problems/0684.cpp b/Problems/0684.cpp @@ -1,30 +1,30 @@ class Solution { -public: - int minReorder(int n, vector<vector<int>> &connections) { - vector<vector<int>> adj(n, vector<int>()); - vector<bool> visited(n, false); - stack<int> st; - int res = 0; + public: + int minReorder(int n, vector<vector<int>> &connections) { + vector<vector<int>> adj(n, vector<int>()); + vector<bool> visited(n, false); + stack<int> st; + int res = 0; - for (auto &e : connections) { - adj[e[0]].push_back(e[1]); - adj[e[1]].push_back(-e[0]); - } + for (auto &e : connections) { + adj[e[0]].push_back(e[1]); + adj[e[1]].push_back(-e[0]); + } - st.push(0); - visited[0] = true; - while (!st.empty()) { - int root = st.top(); - st.pop(); - for (auto c : adj[root]) { - int ac = abs(c); - if (!visited[ac]) { - res += c > 0; - visited[ac] = true; - st.push(ac); + st.push(0); + visited[0] = true; + while (!st.empty()) { + int root = st.top(); + st.pop(); + for (auto c : adj[root]) { + int ac = abs(c); + if (!visited[ac]) { + res += c > 0; + visited[ac] = true; + st.push(ac); + } + } } - } + return res; } - return res; - } }; diff --git a/Problems/0688.cpp b/Problems/0688.cpp @@ -1,25 +1,25 @@ class Solution { - bool valid(int n, int x, int y) { return x >= 0 && y >= 0 && x < n && y < n; } + bool valid(int n, int x, int y) { return x >= 0 && y >= 0 && x < n && y < n; } - double dp[25][25][101]; + double dp[25][25][101]; -public: - double knightProbability(int n, int k, int row, int column) { - static const int offset_x[] = {-2, -2, -1, 1, 2, 2, 1, -1}; - static const int offset_y[] = {-1, 1, 2, 2, 1, -1, -2, -2}; + public: + double knightProbability(int n, int k, int row, int column) { + static const int offset_x[] = {-2, -2, -1, 1, 2, 2, 1, -1}; + static const int offset_y[] = {-1, 1, 2, 2, 1, -1, -2, -2}; - if (!k) return 1; - if (dp[row][column][k]) return dp[row][column][k]; + if (!k) return 1; + if (dp[row][column][k]) return dp[row][column][k]; - double res = 0; - for (int i = 0; i < 8; i++) { - int x = row + offset_x[i]; - int y = column + offset_y[i]; + double res = 0; + for (int i = 0; i < 8; i++) { + int x = row + offset_x[i]; + int y = column + offset_y[i]; - if (!valid(n, x, y)) continue; - res += 0.125 * knightProbability(n, k - 1, x, y); - }; + if (!valid(n, x, y)) continue; + res += 0.125 * knightProbability(n, k - 1, x, y); + }; - return dp[row][column][k] = res; - } + return dp[row][column][k] = res; + } }; diff --git a/Problems/0692.cpp b/Problems/0692.cpp @@ -1,46 +1,51 @@ // sort: O(nlogn) class Solution { -public: - vector<string> topKFrequent(const vector<string> &words, int k) { - unordered_map<string, int> um; - for (const auto &w : words) um[w]++; - - vector<pair<int, string>> vec(um.size()); - vector<string> res(k); - - int count = 0; - for (const auto &[k, v] : um) vec[count++] = {-v, k}; - sort(vec.begin(), vec.end()); - for (int i = 0; i < k; i++) res[i] = vec[i].second; - - return res; - } + public: + vector<string> topKFrequent(const vector<string> &words, int k) { + unordered_map<string, int> um; + for (const auto &w : words) + um[w]++; + + vector<pair<int, string>> vec(um.size()); + vector<string> res(k); + + int count = 0; + for (const auto &[k, v] : um) + vec[count++] = {-v, k}; + sort(vec.begin(), vec.end()); + for (int i = 0; i < k; i++) + res[i] = vec[i].second; + + return res; + } }; // heap: O(nlogk) class Solution { - typedef pair<string, int> psi; - static constexpr const auto cmp = [](const psi &p1, const psi &p2) { - if (p1.second == p2.second) return p1.first < p2.first; - return p1.second > p2.second; - }; - -public: - vector<string> topKFrequent(const vector<string> &words, int k) { - unordered_map<string, int> um; - for (const auto &w : words) um[w]++; - - priority_queue<psi, vector<psi>, decltype(cmp)> pq(cmp); - vector<string> res(k); - - for (auto it : um) { - pq.push(it); - if (pq.size() > k) pq.pop(); + typedef pair<string, int> psi; + static constexpr const auto cmp = [](const psi &p1, const psi &p2) { + if (p1.second == p2.second) return p1.first < p2.first; + return p1.second > p2.second; + }; + + public: + vector<string> topKFrequent(const vector<string> &words, int k) { + unordered_map<string, int> um; + for (const auto &w : words) + um[w]++; + + priority_queue<psi, vector<psi>, decltype(cmp)> pq(cmp); + vector<string> res(k); + + for (auto it : um) { + pq.push(it); + if (pq.size() > k) pq.pop(); + } + + int count = k - 1; + while (!pq.empty()) + res[count--] = pq.top().first, pq.pop(); + + return res; } - - int count = k - 1; - while (!pq.empty()) res[count--] = pq.top().first, pq.pop(); - - return res; - } }; diff --git a/Problems/0695.cpp b/Problems/0695.cpp @@ -1 +1 @@ -Formating: Problems/0695.cpp +Formating : Problems / 0695.cpp diff --git a/Problems/0700.cpp b/Problems/0700.cpp @@ -1,12 +1,12 @@ class Solution { -public: - TreeNode *searchBST(TreeNode *root, int val) { - while (root && root->val != val) { - if (val < root->val) - root = root->left; - else - root = root->right; + public: + TreeNode *searchBST(TreeNode *root, int val) { + while (root && root->val != val) { + if (val < root->val) + root = root->left; + else + root = root->right; + } + return root; } - return root; - } }; diff --git a/Problems/0701.cpp b/Problems/0701.cpp @@ -1,15 +1,15 @@ class Solution { -public: - TreeNode *insertIntoBST(TreeNode *root, int val) { - if (!root) return new TreeNode(val); + public: + TreeNode *insertIntoBST(TreeNode *root, int val) { + if (!root) return new TreeNode(val); - TreeNode *prev = nullptr; - for (TreeNode *tmp = root; tmp;) { - prev = tmp; - tmp = val < tmp->val ? tmp->left : tmp->right; - } + TreeNode *prev = nullptr; + for (TreeNode *tmp = root; tmp;) { + prev = tmp; + tmp = val < tmp->val ? tmp->left : tmp->right; + } - (val > prev->val ? prev->right : prev->left) = new TreeNode(val); - return root; - } + (val > prev->val ? prev->right : prev->left) = new TreeNode(val); + return root; + } }; diff --git a/Problems/0703.cpp b/Problems/0703.cpp @@ -1,15 +1,16 @@ class KthLargest { - priority_queue<int, vector<int>, greater<int>> pq; - int k; + priority_queue<int, vector<int>, greater<int>> pq; + int k; -public: - KthLargest(int k, vector<int> &nums) : k(k), pq(nums.begin(), nums.end()) { - while (pq.size() > k) pq.pop(); - } + public: + KthLargest(int k, vector<int> &nums) : k(k), pq(nums.begin(), nums.end()) { + while (pq.size() > k) + pq.pop(); + } - int add(int val) { - pq.push(val); - if (pq.size() > k) pq.pop(); - return pq.top(); - } + int add(int val) { + pq.push(val); + if (pq.size() > k) pq.pop(); + return pq.top(); + } }; diff --git a/Problems/0704.cpp b/Problems/0704.cpp @@ -1,15 +1,15 @@ class Solution { -public: - int search(vector<int> &nums, int target) { - int low = 0, high = nums.size() - 1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (nums[mid] == target) return mid; - if (nums[mid] < target) - low = mid + 1; - else - high = mid - 1; + public: + int search(vector<int> &nums, int target) { + int low = 0, high = nums.size() - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] == target) return mid; + if (nums[mid] < target) + low = mid + 1; + else + high = mid - 1; + } + return -1; } - return -1; - } }; diff --git a/Problems/0705.cpp b/Problems/0705.cpp @@ -1,42 +1,41 @@ class MyHashSet { class Node { - public: - int val; - Node *next; + public: + int val; + Node *next; - Node(): val(-1), next(nullptr) {} - Node(int val, Node *next): val(val), next(next) {} + Node() : val(-1), next(nullptr) {} + Node(int val, Node *next) : val(val), next(next) {} }; static constexpr int SIZE = 10007; Node bucket[SIZE] = {}; - int hash(int key) { - return key % SIZE; - } -public: + int hash(int key) { return key % SIZE; } + + public: MyHashSet() {} - + void add(int key) { - if(contains(key)) return; - Node *b = &bucket[hash(key)]; - b->next = new Node(key, b->next); + if (contains(key)) return; + Node *b = &bucket[hash(key)]; + b->next = new Node(key, b->next); } - + void remove(int key) { - Node *prev = &bucket[hash(key)], *crnt = prev->next; - while(crnt && crnt->val != key) { - prev = crnt; - crnt = crnt->next; - } - if(!crnt) return; - prev->next = crnt->next; - delete crnt; + Node *prev = &bucket[hash(key)], *crnt = prev->next; + while (crnt && crnt->val != key) { + prev = crnt; + crnt = crnt->next; + } + if (!crnt) return; + prev->next = crnt->next; + delete crnt; } - + bool contains(int key) { - for(Node *crnt = bucket[hash(key)].next; crnt; crnt=crnt->next) - if(crnt->val == key) return true; - return false; + for (Node *crnt = bucket[hash(key)].next; crnt; crnt = crnt->next) + if (crnt->val == key) return true; + return false; } }; diff --git a/Problems/0706.cpp b/Problems/0706.cpp @@ -1,32 +1,32 @@ class MyHashMap { - const int mod = 9973; + const int mod = 9973; - vector<vector<pair<int, int>>> hm; - int hash(int key) { return key % mod; } + vector<vector<pair<int, int>>> hm; + int hash(int key) { return key % mod; } - int &find(int key) { - static int err = -1; - for (auto &[k, v] : hm[hash(key)]) - if (k == key) return v; - return err; - } + int &find(int key) { + static int err = -1; + for (auto &[k, v] : hm[hash(key)]) + if (k == key) return v; + return err; + } -public: - MyHashMap() : hm(mod) {} - void put(int key, int value) { - int &loc = find(key); - if (loc == -1) - hm[hash(key)].push_back({key, value}); - else - loc = value; - } - int get(int key) { return find(key); } - void remove(int key) { - vector<pair<int, int>> &row = hm[hash(key)]; - for (int i = 0; i < row.size(); i++) - if (row[i].first == key) { - row.erase(row.begin() + i); - break; - } - } + public: + MyHashMap() : hm(mod) {} + void put(int key, int value) { + int &loc = find(key); + if (loc == -1) + hm[hash(key)].push_back({key, value}); + else + loc = value; + } + int get(int key) { return find(key); } + void remove(int key) { + vector<pair<int, int>> &row = hm[hash(key)]; + for (int i = 0; i < row.size(); i++) + if (row[i].first == key) { + row.erase(row.begin() + i); + break; + } + } }; diff --git a/Problems/0707.cpp b/Problems/0707.cpp @@ -1,77 +1,80 @@ class MyLinkedList { - struct Node { - int val; - Node *next; - - Node(int val, Node *next = nullptr) : val(val), next(next) {} - }; - - Node *head = nullptr, *tail = nullptr; - int size = 0; - -public: - MyLinkedList() {} - - int get(int index) { - if (index >= size) return -1; - - Node *p = head; - while (index--) p = p->next; - return p->val; - } - - void addAtHead(int val) { - if (!head) - head = tail = new Node(val); - else - head = new Node(val, head); - size++; - } - - void addAtTail(int val) { - if (!head) - head = tail = new Node(val); - else - tail = tail->next = new Node(val); - size++; - } - - void addAtIndex(int index, int val) { - if (index > size) return; - - Node *p = head; - size++; - - if (index == 0) { - addAtHead(val); - return; + struct Node { + int val; + Node *next; + + Node(int val, Node *next = nullptr) : val(val), next(next) {} + }; + + Node *head = nullptr, *tail = nullptr; + int size = 0; + + public: + MyLinkedList() {} + + int get(int index) { + if (index >= size) return -1; + + Node *p = head; + while (index--) + p = p->next; + return p->val; } - while (--index) p = p->next; - p->next = new Node(val, p->next); - if (p == tail) tail = p->next; - } + void addAtHead(int val) { + if (!head) + head = tail = new Node(val); + else + head = new Node(val, head); + size++; + } - void deleteAtIndex(int index) { - if (index >= size) return; + void addAtTail(int val) { + if (!head) + head = tail = new Node(val); + else + tail = tail->next = new Node(val); + size++; + } - Node *t, *p; - size--; + void addAtIndex(int index, int val) { + if (index > size) return; - if (index == 0) { - cout << "head" << endl; - t = head; - head = head->next; - delete t; - return; + Node *p = head; + size++; + + if (index == 0) { + addAtHead(val); + return; + } + + while (--index) + p = p->next; + p->next = new Node(val, p->next); + if (p == tail) tail = p->next; } - p = head; - while (--index) p = p->next; + void deleteAtIndex(int index) { + if (index >= size) return; + + Node *t, *p; + size--; - t = p->next; - p->next = p->next->next; - if (t == tail) tail = p; - delete t; - } + if (index == 0) { + cout << "head" << endl; + t = head; + head = head->next; + delete t; + return; + } + + p = head; + while (--index) + p = p->next; + + t = p->next; + p->next = p->next->next; + if (t == tail) tail = p; + delete t; + } }; diff --git a/Problems/0712.cpp b/Problems/0712.cpp @@ -1,25 +1,25 @@ class Solution { - int dp[1001][1001]; - int rec(const string &s1, const string &s2, int l1, int l2) { - if (l1 >= s1.size() && l2 >= s2.size()) return 0; - if (dp[l1][l2] != -1) return dp[l1][l2]; + int dp[1001][1001]; + int rec(const string &s1, const string &s2, int l1, int l2) { + if (l1 >= s1.size() && l2 >= s2.size()) return 0; + if (dp[l1][l2] != -1) return dp[l1][l2]; - int res = INT_MAX; - if (s1[l1] == s2[l2]) res = min(res, rec(s1, s2, l1 + 1, l2 + 1)); - res = min(res, s1[l1] + rec(s1, s2, l1 + 1, l2)); - res = min(res, s2[l2] + rec(s1, s2, l1, l2 + 1)); + int res = INT_MAX; + if (s1[l1] == s2[l2]) res = min(res, rec(s1, s2, l1 + 1, l2 + 1)); + res = min(res, s1[l1] + rec(s1, s2, l1 + 1, l2)); + res = min(res, s2[l2] + rec(s1, s2, l1, l2 + 1)); - return dp[l1][l2] = res; - } + return dp[l1][l2] = res; + } -public: - Solution() { memset(dp, 0xFF, sizeof(dp)); } - int minimumDeleteSum(const string &s1, const string &s2) { - for (int i = s1.size() - 1, sum = 0; i >= 0; i--) - dp[i][s2.size()] = sum += s1[i]; - for (int i = s2.size() - 1, sum = 0; i >= 0; i--) - dp[s1.size()][i] = sum += s2[i]; + public: + Solution() { memset(dp, 0xFF, sizeof(dp)); } + int minimumDeleteSum(const string &s1, const string &s2) { + for (int i = s1.size() - 1, sum = 0; i >= 0; i--) + dp[i][s2.size()] = sum += s1[i]; + for (int i = s2.size() - 1, sum = 0; i >= 0; i--) + dp[s1.size()][i] = sum += s2[i]; - return rec(s1, s2, 0, 0); - } + return rec(s1, s2, 0, 0); + } }; diff --git a/Problems/0713.cpp b/Problems/0713.cpp @@ -1,16 +1,16 @@ class Solution { -public: - int numSubarrayProductLessThanK(vector<int> &nums, int k) { - int res = 0, count = 0, prod = 1, start = 0; - ; - for (int i = 0; i < nums.size(); i++) { - prod *= nums[i]; - while (prod >= k && start <= i) { - prod /= nums[start++]; - count--; - } - res += i - start + 1; + public: + int numSubarrayProductLessThanK(vector<int> &nums, int k) { + int res = 0, count = 0, prod = 1, start = 0; + ; + for (int i = 0; i < nums.size(); i++) { + prod *= nums[i]; + while (prod >= k && start <= i) { + prod /= nums[start++]; + count--; + } + res += i - start + 1; + } + return res; } - return res; - } }; diff --git a/Problems/0714.cpp b/Problems/0714.cpp @@ -1,2 +1 @@ -Formating: Problems/0309.cpp -Formating: Problems/0714.cpp +Formating : Problems / 0309.cpp Formating : Problems / 0714.cpp diff --git a/Problems/0724.cpp b/Problems/0724.cpp @@ -1,12 +1,12 @@ class Solution { -public: - int pivotIndex(vector<int> &nums) { - int left = 0; - int right = accumulate(nums.begin(), nums.end(), 0); - for (int i = 0; i < nums.size(); left += nums[i++]) { - right -= nums[i]; - if (left == right) return i; + public: + int pivotIndex(vector<int> &nums) { + int left = 0; + int right = accumulate(nums.begin(), nums.end(), 0); + for (int i = 0; i < nums.size(); left += nums[i++]) { + right -= nums[i]; + if (left == right) return i; + } + return -1; } - return -1; - } }; diff --git a/Problems/0733.cpp b/Problems/0733.cpp @@ -1,42 +1,41 @@ class Solution { - int m, n, src, color; - vector<vector<int>> *image; - queue<pair<int, int>> q; + int m, n, src, color; + vector<vector<int>> *image; + queue<pair<int, int>> q; - int valid(int sr, int sc) { return sr >= 0 && sr < m && sc >= 0 && sc < n; } + int valid(int sr, int sc) { return sr >= 0 && sr < m && sc >= 0 && sc < n; } - void add(int sr, int sc) { - if (valid(sr, sc) && (*image)[sr][sc] == src) { - (*image)[sr][sc] = color; - q.push(make_pair(sr, sc)); - } - } - -public: - vector<vector<int>> floodFill(vector<vector<int>> &image, int sr, int sc, - int color) { - src = image[sr][sc]; - if (src == color) return image; - - m = image.size(); - n = image[0].size(); - this->color = color; - this->image = &image; - - q.push(make_pair(sr, sc)); - image[sr][sc] = color; - - while (!q.empty()) { - int sr = q.front().first; - int sc = q.front().second; - q.pop(); - - add(sr + 1, sc); - add(sr - 1, sc); - add(sr, sc + 1); - add(sr, sc - 1); + void add(int sr, int sc) { + if (valid(sr, sc) && (*image)[sr][sc] == src) { + (*image)[sr][sc] = color; + q.push(make_pair(sr, sc)); + } } - return image; - } + public: + vector<vector<int>> floodFill(vector<vector<int>> &image, int sr, int sc, int color) { + src = image[sr][sc]; + if (src == color) return image; + + m = image.size(); + n = image[0].size(); + this->color = color; + this->image = &image; + + q.push(make_pair(sr, sc)); + image[sr][sc] = color; + + while (!q.empty()) { + int sr = q.front().first; + int sc = q.front().second; + q.pop(); + + add(sr + 1, sc); + add(sr - 1, sc); + add(sr, sc + 1); + add(sr, sc - 1); + } + + return image; + } }; diff --git a/Problems/0735.cpp b/Problems/0735.cpp @@ -1,11 +1,14 @@ class Solution { -public: - vector<int> asteroidCollision(vector<int>& asteroids) { + public: + vector<int> asteroidCollision(vector<int> &asteroids) { vector<int> st; for (int aster : asteroids) { - while (!st.empty() && st.back() > 0 && st.back() < -aster) st.pop_back(); - if (st.empty() || aster > 0 || st.back() < 0) st.push_back(aster); - else if (aster < 0 && st.back() == -aster) st.pop_back(); + while (!st.empty() && st.back() > 0 && st.back() < -aster) + st.pop_back(); + if (st.empty() || aster > 0 || st.back() < 0) + st.push_back(aster); + else if (aster < 0 && st.back() == -aster) + st.pop_back(); } return st; } diff --git a/Problems/0739.cpp b/Problems/0739.cpp @@ -1,20 +1,20 @@ class Solution { -public: - vector<int> dailyTemperatures(vector<int> &temps) { - stack<int> st({0}); + public: + vector<int> dailyTemperatures(vector<int> &temps) { + stack<int> st({0}); - for (int i = 1; i < temps.size(); ++i) { - while (!st.empty() && temps[i] > temps[st.top()]) { - temps[st.top()] = i - st.top(); - st.pop(); - } - st.push(i); - } + for (int i = 1; i < temps.size(); ++i) { + while (!st.empty() && temps[i] > temps[st.top()]) { + temps[st.top()] = i - st.top(); + st.pop(); + } + st.push(i); + } - while (!st.empty()) { - temps[st.top()] = 0; - st.pop(); + while (!st.empty()) { + temps[st.top()] = 0; + st.pop(); + } + return temps; } - return temps; - } }; diff --git a/Problems/0740.cpp b/Problems/0740.cpp @@ -1,17 +1,18 @@ class Solution { -public: - int deleteAndEarn(vector<int> &nums) { - int n = *max_element(nums.begin(), nums.end()) + 1; - vector<int> count(n); - for (int n : nums) count[n] += n; + public: + int deleteAndEarn(vector<int> &nums) { + int n = *max_element(nums.begin(), nums.end()) + 1; + vector<int> count(n); + for (int n : nums) + count[n] += n; - int prev1 = 0, prev2 = 0; - for (int i = 0; i < n; i++) { - int tmp = prev1; - prev1 = max(prev2 + count[i], prev1); - prev2 = tmp; - } + int prev1 = 0, prev2 = 0; + for (int i = 0; i < n; i++) { + int tmp = prev1; + prev1 = max(prev2 + count[i], prev1); + prev2 = tmp; + } - return prev1; - } + return prev1; + } }; diff --git a/Problems/0743.cpp b/Problems/0743.cpp @@ -1,25 +1,26 @@ class Solution { - typedef pair<int, int> edge; + typedef pair<int, int> edge; -public: - int networkDelayTime(vector<vector<int>> &times, int n, int k) { - vector<vector<edge>> adj(n + 1, vector<edge>()); - for (auto &p : times) adj[p[0]].push_back({p[2], p[1]}); + public: + int networkDelayTime(vector<vector<int>> &times, int n, int k) { + vector<vector<edge>> adj(n + 1, vector<edge>()); + for (auto &p : times) + adj[p[0]].push_back({p[2], p[1]}); - priority_queue<edge, vector<edge>, greater<edge>> st; - unordered_set<int> us; + priority_queue<edge, vector<edge>, greater<edge>> st; + unordered_set<int> us; - int time = 0; - st.push({0, k}); - while (!st.empty()) { - auto [t, root] = st.top(); - st.pop(); - if (us.count(root)) continue; - time = t; - us.insert(root); - for (auto &[time, dest] : adj[root]) - if (!us.count(dest)) st.push({t + time, dest}); + int time = 0; + st.push({0, k}); + while (!st.empty()) { + auto [t, root] = st.top(); + st.pop(); + if (us.count(root)) continue; + time = t; + us.insert(root); + for (auto &[time, dest] : adj[root]) + if (!us.count(dest)) st.push({t + time, dest}); + } + return us.size() == n ? time : -1; } - return us.size() == n ? time : -1; - } }; diff --git a/Problems/0744.cpp b/Problems/0744.cpp @@ -1,18 +1,18 @@ class Solution { -public: - char nextGreatestLetter(vector<char> &letters, char target) { - if (target >= letters.back()) return letters.front(); - int low = 0, high = letters.size() - 1; - target++; - while (low < high) { - int mid = low + (high - low) / 2; - if (letters[mid] == target) - return letters[mid]; - else if (letters[mid] < target) - low = mid + 1; - else - high = mid; + public: + char nextGreatestLetter(vector<char> &letters, char target) { + if (target >= letters.back()) return letters.front(); + int low = 0, high = letters.size() - 1; + target++; + while (low < high) { + int mid = low + (high - low) / 2; + if (letters[mid] == target) + return letters[mid]; + else if (letters[mid] < target) + low = mid + 1; + else + high = mid; + } + return letters[high]; } - return letters[high]; - } }; diff --git a/Problems/0746.cpp b/Problems/0746.cpp @@ -1,24 +1,24 @@ // memorization approach class Solution { -public: - int minCostClimbingStairs(vector<int> &cost) { - vector<int> vec(cost.size() + 2); - for (int i = 2; i <= cost.size(); i++) - vec[i] = min(vec[i - 1] + cost[i - 1], vec[i - 2] + cost[i - 2]); - return vec[cost.size()]; - } + public: + int minCostClimbingStairs(vector<int> &cost) { + vector<int> vec(cost.size() + 2); + for (int i = 2; i <= cost.size(); i++) + vec[i] = min(vec[i - 1] + cost[i - 1], vec[i - 2] + cost[i - 2]); + return vec[cost.size()]; + } }; // optimized, memorize only the previous two values class Solution { -public: - int minCostClimbingStairs(vector<int> &cost) { - int first = cost[0], second = cost[1]; - for (int i = 2; i < cost.size(); i++) { - int crnt = cost[i] + min(first, second); - first = second; - second = crnt; + public: + int minCostClimbingStairs(vector<int> &cost) { + int first = cost[0], second = cost[1]; + for (int i = 2; i < cost.size(); i++) { + int crnt = cost[i] + min(first, second); + first = second; + second = crnt; + } + return min(first, second); } - return min(first, second); - } }; diff --git a/Problems/0747.cpp b/Problems/0747.cpp @@ -1,18 +1,18 @@ class Solution { -public: - int dominantIndex(vector<int> &nums) { - int max1, max2, index; - max1 = max2 = index = 0; + public: + int dominantIndex(vector<int> &nums) { + int max1, max2, index; + max1 = max2 = index = 0; - for (int i = 0; i < nums.size(); i++) { - if (nums[i] > max1) { - index = i; - max2 = max1; - max1 = nums[i]; - } else if (nums[i] > max2) { - max2 = nums[i]; - } + for (int i = 0; i < nums.size(); i++) { + if (nums[i] > max1) { + index = i; + max2 = max1; + max1 = nums[i]; + } else if (nums[i] > max2) { + max2 = nums[i]; + } + } + return 2 * max2 <= max1 ? index : -1; } - return 2 * max2 <= max1 ? index : -1; - } }; diff --git a/Problems/0752.cpp b/Problems/0752.cpp @@ -1,35 +1,35 @@ class Solution { -public: - vector<string> neighbours(const string &code) { - vector<string> res; - for (int i = 0; i < 4; i++) { - for (int j = -1; j <= 1; j += 2) { - string s = code; - s[i] = (code[i] - '0' + j + 10) % 10 + '0'; - res.push_back(s); - } + public: + vector<string> neighbours(const string &code) { + vector<string> res; + for (int i = 0; i < 4; i++) { + for (int j = -1; j <= 1; j += 2) { + string s = code; + s[i] = (code[i] - '0' + j + 10) % 10 + '0'; + res.push_back(s); + } + } + return res; } - return res; - } - int openLock(vector<string> &deadends, string target) { - unordered_set<string> um(deadends.begin(), deadends.end()); - if (um.count("0000")) return -1; + int openLock(vector<string> &deadends, string target) { + unordered_set<string> um(deadends.begin(), deadends.end()); + if (um.count("0000")) return -1; - queue<string> q({"0000"}); - for (int cnt = 0; !q.empty(); ++cnt) { - for (int i = q.size(); i > 0; --i) { - string s = q.front(); - q.pop(); - if (s == target) return cnt; + queue<string> q({"0000"}); + for (int cnt = 0; !q.empty(); ++cnt) { + for (int i = q.size(); i > 0; --i) { + string s = q.front(); + q.pop(); + if (s == target) return cnt; - for (string &s : neighbours(s)) { - if (um.count(s)) continue; - um.insert(s); - q.push(s); + for (string &s : neighbours(s)) { + if (um.count(s)) continue; + um.insert(s); + q.push(s); + } + } } - } + return -1; } - return -1; - } }; diff --git a/Problems/0763.cpp b/Problems/0763.cpp @@ -1,29 +1,30 @@ class Solution { -public: - vector<int> partitionLabels(string s) { - unordered_set<char> seen; - array<int, 26> count = {0}; - vector<int> res; + public: + vector<int> partitionLabels(string s) { + unordered_set<char> seen; + array<int, 26> count = {0}; + vector<int> res; - for (char c : s) count[c - 'a']++; + for (char c : s) + count[c - 'a']++; - int len = 0, needed = 0; - for (int i = 0; i < s.size(); i++) { - len++; - if (seen.count(s[i])) - needed--; - else { - needed += count[s[i] - 'a'] - 1; - seen.insert(s[i]); - } + int len = 0, needed = 0; + for (int i = 0; i < s.size(); i++) { + len++; + if (seen.count(s[i])) + needed--; + else { + needed += count[s[i] - 'a'] - 1; + seen.insert(s[i]); + } - if (!needed) { - res.push_back(len); - seen.clear(); - len = 0; - } - } + if (!needed) { + res.push_back(len); + seen.clear(); + len = 0; + } + } - return res; - } + return res; + } }; diff --git a/Problems/0767.cpp b/Problems/0767.cpp @@ -1,32 +1,33 @@ class Solution { - typedef pair<int, char> pic; + typedef pair<int, char> pic; -public: - string reorganizeString(const string &s) { - priority_queue<pic> pq; - int count[27] = {0}; - string res; + public: + string reorganizeString(const string &s) { + priority_queue<pic> pq; + int count[27] = {0}; + string res; - for (char c : s) count[c & 0x1F]++; - for (int i = 1; i <= 26; i++) - if (count[i] > 0) pq.push({count[i], 'a' + i - 1}); + for (char c : s) + count[c & 0x1F]++; + for (int i = 1; i <= 26; i++) + if (count[i] > 0) pq.push({count[i], 'a' + i - 1}); - while (!pq.empty()) { - const auto [cnt, c] = pq.top(); - pq.pop(); - if (pq.empty()) { - if (cnt == 1) - return res + c; - else - return ""; - } else { - const auto [ocnt, oc] = pq.top(); - pq.pop(); - res += c, res += oc; - if (cnt - 1) pq.push({cnt - 1, c}); - if (ocnt - 1) pq.push({ocnt - 1, oc}); - } + while (!pq.empty()) { + const auto [cnt, c] = pq.top(); + pq.pop(); + if (pq.empty()) { + if (cnt == 1) + return res + c; + else + return ""; + } else { + const auto [ocnt, oc] = pq.top(); + pq.pop(); + res += c, res += oc; + if (cnt - 1) pq.push({cnt - 1, c}); + if (ocnt - 1) pq.push({ocnt - 1, oc}); + } + } + return res; } - return res; - } }; diff --git a/Problems/0783.cpp b/Problems/0783.cpp @@ -1,21 +1,21 @@ class Solution { -public: - int minDiffInBST(TreeNode *root) { - stack<TreeNode *> st; - int res = INT_MAX; - TreeNode *prev = new TreeNode(INT_MAX); - while (true) { - while (root) { - st.push(root); - root = root->left; - } - if (st.empty()) break; - root = st.top(); - st.pop(); - res = min(res, abs(prev->val - root->val)); - prev = root; - root = root->right; + public: + int minDiffInBST(TreeNode *root) { + stack<TreeNode *> st; + int res = INT_MAX; + TreeNode *prev = new TreeNode(INT_MAX); + while (true) { + while (root) { + st.push(root); + root = root->left; + } + if (st.empty()) break; + root = st.top(); + st.pop(); + res = min(res, abs(prev->val - root->val)); + prev = root; + root = root->right; + } + return res; } - return res; - } }; diff --git a/Problems/0784.cpp b/Problems/0784.cpp @@ -1,21 +1,22 @@ class Solution { - vector<string> res; + vector<string> res; - void rec(string &s, int st, string crnt) { - while (st < s.size() && !isalpha(s[st])) crnt += s[st++]; - if (st == s.size()) { - res.push_back(crnt); - return; - } + void rec(string &s, int st, string crnt) { + while (st < s.size() && !isalpha(s[st])) + crnt += s[st++]; + if (st == s.size()) { + res.push_back(crnt); + return; + } - char c = tolower(s[st]); - rec(s, st + 1, crnt + c); - rec(s, st + 1, crnt + (char)toupper(c)); - } + char c = tolower(s[st]); + rec(s, st + 1, crnt + c); + rec(s, st + 1, crnt + (char)toupper(c)); + } -public: - vector<string> letterCasePermutation(string s) { - rec(s, 0, ""); - return res; - } + public: + vector<string> letterCasePermutation(string s) { + rec(s, 0, ""); + return res; + } }; diff --git a/Problems/0785.cpp b/Problems/0785.cpp @@ -1,25 +1,25 @@ class Solution { -public: - bool isBipartite(vector<vector<int>> &graph) { - int n = graph.size(); - vector<int> color(n, 0); + public: + bool isBipartite(vector<vector<int>> &graph) { + int n = graph.size(); + vector<int> color(n, 0); - for (int i = 0; i < n; i++) { - if (color[i]) continue; - stack<int> st; - st.push(i), color[i] = 1; - while (!st.empty()) { - int root = st.top(); - st.pop(); - for (int c : graph[root]) { - if (color[root] == color[c]) return false; - if (!color[c]) { - st.push(c); - color[c] = -color[root]; - } + for (int i = 0; i < n; i++) { + if (color[i]) continue; + stack<int> st; + st.push(i), color[i] = 1; + while (!st.empty()) { + int root = st.top(); + st.pop(); + for (int c : graph[root]) { + if (color[root] == color[c]) return false; + if (!color[c]) { + st.push(c); + color[c] = -color[root]; + } + } + } } - } + return true; } - return true; - } }; diff --git a/Problems/0787.cpp b/Problems/0787.cpp @@ -1,31 +1,30 @@ class Solution { - struct edge { - int d, w, s; - edge(int d, int w, int s = -1) : d(d), w(w), s(s) {} - friend bool operator<(const edge &e1, const edge &e2) { - return e1.w > e2.w; - } - }; + struct edge { + int d, w, s; + edge(int d, int w, int s = -1) : d(d), w(w), s(s) {} + friend bool operator<(const edge &e1, const edge &e2) { return e1.w > e2.w; } + }; -public: - int findCheapestPrice(int n, vector<vector<int>> &flights, int src, int dst, - int k) { - vector<vector<edge>> adj(n); - for (auto &f : flights) adj[f[0]].push_back({f[1], f[2]}); + public: + int findCheapestPrice(int n, vector<vector<int>> &flights, int src, int dst, int k) { + vector<vector<edge>> adj(n); + for (auto &f : flights) + adj[f[0]].push_back({f[1], f[2]}); - vector<int> stop(n, INT_MAX); - priority_queue<edge> pq; + vector<int> stop(n, INT_MAX); + priority_queue<edge> pq; - pq.push({src, 0, 0}); - while (!pq.empty()) { - auto [d, w, s] = pq.top(); - pq.pop(); - if (s > stop[d] || s > k + 1) continue; + pq.push({src, 0, 0}); + while (!pq.empty()) { + auto [d, w, s] = pq.top(); + pq.pop(); + if (s > stop[d] || s > k + 1) continue; - stop[d] = s; - if (d == dst) return w; - for (auto [d1, w1, _] : adj[d]) pq.push({d1, w + w1, s + 1}); + stop[d] = s; + if (d == dst) return w; + for (auto [d1, w1, _] : adj[d]) + pq.push({d1, w + w1, s + 1}); + } + return -1; } - return -1; - } }; diff --git a/Problems/0797.cpp b/Problems/0797.cpp @@ -1,39 +1,39 @@ class Solution { -public: - vector<vector<int>> allPathsSourceTarget(vector<vector<int>> &graph) { - int n = graph.size(); + public: + vector<vector<int>> allPathsSourceTarget(vector<vector<int>> &graph) { + int n = graph.size(); - vector<vector<int>> res; - unordered_set<int> visited; - vector<int> path; - stack<int> st; + vector<vector<int>> res; + unordered_set<int> visited; + vector<int> path; + stack<int> st; - st.push(0); - while (!st.empty()) { - int root = st.top(); - st.pop(); + st.push(0); + while (!st.empty()) { + int root = st.top(); + st.pop(); - if (root == n - 1) { - path.push_back(root); - res.push_back(path); - path.pop_back(); - continue; - } + if (root == n - 1) { + path.push_back(root); + res.push_back(path); + path.pop_back(); + continue; + } - if (visited.count(root)) { - visited.erase(root); - path.pop_back(); - continue; - } + if (visited.count(root)) { + visited.erase(root); + path.pop_back(); + continue; + } - path.push_back(root); - visited.insert(root); - st.push(root); + path.push_back(root); + visited.insert(root); + st.push(root); - for (int n : graph[root]) - if (!visited.count(n)) st.push(n); - } + for (int n : graph[root]) + if (!visited.count(n)) st.push(n); + } - return res; - } + return res; + } }; diff --git a/Problems/0802.cpp b/Problems/0802.cpp @@ -1,73 +1,74 @@ class Solution { -public: - vector<int> eventualSafeNodes(const vector<vector<int>> &graph) { - int n = graph.size(); - vector<bool> visited(n, false), safe(n, false); - stack<int> st; - for (int i = 0; i < n; i++) { - if (visited[i]) continue; - st.push(i); - while (!st.empty()) { - int root = st.top(); - if (root == -1) { - st.pop(); - root = st.top(); - st.pop(); - bool s = true; - for (int c : graph[root]) - if (!safe[c]) { - s = false; - break; + public: + vector<int> eventualSafeNodes(const vector<vector<int>> &graph) { + int n = graph.size(); + vector<bool> visited(n, false), safe(n, false); + stack<int> st; + for (int i = 0; i < n; i++) { + if (visited[i]) continue; + st.push(i); + while (!st.empty()) { + int root = st.top(); + if (root == -1) { + st.pop(); + root = st.top(); + st.pop(); + bool s = true; + for (int c : graph[root]) + if (!safe[c]) { + s = false; + break; + } + safe[root] = s; + continue; + } + if (visited[root]) { + st.pop(); + continue; + }; + visited[root] = true; + st.push(-1); + for (int c : graph[root]) + if (!visited[c]) st.push(c); } - safe[root] = s; - continue; } - if (visited[root]) { - st.pop(); - continue; - }; - visited[root] = true; - st.push(-1); - for (int c : graph[root]) - if (!visited[c]) st.push(c); - } + vector<int> res; + for (int i = 0; i < n; i++) + if (safe[i]) res.push_back(i); + return res; } - vector<int> res; - for (int i = 0; i < n; i++) - if (safe[i]) res.push_back(i); - return res; - } }; // Cleaner code, more memory class Solution { - int safe[100001] = {0}, count[10001] = {0}; + int safe[100001] = {0}, count[10001] = {0}; -public: - vector<int> eventualSafeNodes(const vector<vector<int>> &graph) { - int n = graph.size(); - vector<vector<int>> adj(n); - for (int i = 0; i < n; i++) { - count[i] += graph[i].size(); - for (int node : graph[i]) adj[node].push_back(i); - } + public: + vector<int> eventualSafeNodes(const vector<vector<int>> &graph) { + int n = graph.size(); + vector<vector<int>> adj(n); + for (int i = 0; i < n; i++) { + count[i] += graph[i].size(); + for (int node : graph[i]) + adj[node].push_back(i); + } - queue<int> q; - for (int i = 0; i < n; i++) - if (!count[i]) q.push(i); + queue<int> q; + for (int i = 0; i < n; i++) + if (!count[i]) q.push(i); - while (!q.empty()) { - int root = q.front(); - q.pop(); - safe[root] = true; + while (!q.empty()) { + int root = q.front(); + q.pop(); + safe[root] = true; - for (auto node : adj[root]) - if (!--count[node]) q.push(node); - } + for (auto node : adj[root]) + if (!--count[node]) q.push(node); + } - vector<int> res; - for (int i = 0; i < graph.size(); i++) - if (safe[i]) res.push_back(i); - return res; - } + vector<int> res; + for (int i = 0; i < graph.size(); i++) + if (safe[i]) res.push_back(i); + return res; + } }; diff --git a/Problems/0807.cpp b/Problems/0807.cpp @@ -1,19 +1,19 @@ class Solution { -public: - int maxIncreaseKeepingSkyline(const vector<vector<int>>& grid) { - int row[51] = { 0 }, col[51] = { 0 }; + public: + int maxIncreaseKeepingSkyline(const vector<vector<int>> &grid) { + int row[51] = {0}, col[51] = {0}; int n = grid.size(); - for(int i=0; i<n; i++) { - for(int j=0; j<n; j++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { row[i] = max(row[i], grid[i][j]); col[j] = max(col[j], grid[i][j]); } } int res = 0; - for(int i=0; i<n; i++) { - for(int j=0; j<n; j++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { res += min(row[i], col[j]) - grid[i][j]; } } diff --git a/Problems/0808.cpp b/Problems/0808.cpp @@ -1,17 +1,15 @@ class Solution { - double dp[200][200] = {0}; + double dp[200][200] = {0}; - double calc(int a, int b) { - if (a <= 0 && b <= 0) return 0.5; - if (a <= 0) return 1; - if (b <= 0) return 0; - if (dp[a][b] > 0) return dp[a][b]; - return dp[a][b] = 0.25 * (calc(a - 4, b) + calc(a - 3, b - 1) + - calc(a - 2, b - 2) + calc(a - 1, b - 3)); - } + double calc(int a, int b) { + if (a <= 0 && b <= 0) return 0.5; + if (a <= 0) return 1; + if (b <= 0) return 0; + if (dp[a][b] > 0) return dp[a][b]; + return dp[a][b] = + 0.25 * (calc(a - 4, b) + calc(a - 3, b - 1) + calc(a - 2, b - 2) + calc(a - 1, b - 3)); + } -public: - double soupServings(int n) { - return n > 4800 ? 1.0 : calc(ceil(n / 25.0), ceil(n / 25.0)); - } + public: + double soupServings(int n) { return n > 4800 ? 1.0 : calc(ceil(n / 25.0), ceil(n / 25.0)); } }; diff --git a/Problems/0811.cpp b/Problems/0811.cpp @@ -1,19 +1,20 @@ class Solution { -public: - vector<string> subdomainVisits(const vector<string> &cpdomains) { - unordered_map<string, int> um; - for (const auto &s : cpdomains) { - int start, pos; - pos = start = s.find(' '); - int value = stoi(s.substr(0, pos)); - while (pos != string::npos) { - um[s.substr(pos + 1)] += value; - pos = s.find('.', pos + 1); - } + public: + vector<string> subdomainVisits(const vector<string> &cpdomains) { + unordered_map<string, int> um; + for (const auto &s : cpdomains) { + int start, pos; + pos = start = s.find(' '); + int value = stoi(s.substr(0, pos)); + while (pos != string::npos) { + um[s.substr(pos + 1)] += value; + pos = s.find('.', pos + 1); + } + } + vector<string> res; + res.reserve(um.size()); + for (const auto &[s, n] : um) + res.push_back(to_string(n) + " " + s); + return res; } - vector<string> res; - res.reserve(um.size()); - for (const auto &[s, n] : um) res.push_back(to_string(n) + " " + s); - return res; - } }; diff --git a/Problems/0814.cpp b/Problems/0814.cpp @@ -1,32 +1,32 @@ class Solution { -public: - TreeNode *pruneTree(TreeNode *root) { - TreeNode dummy(1, root, nullptr); - unordered_set<TreeNode *> has; - stack<TreeNode *> st; - st.push(&dummy); - while (!st.empty()) { - TreeNode *root = st.top(); - if (!root) { - st.pop(); - root = st.top(), st.pop(); - if (has.count(root->left)) - has.insert(root); - else - root->left = nullptr; + public: + TreeNode *pruneTree(TreeNode *root) { + TreeNode dummy(1, root, nullptr); + unordered_set<TreeNode *> has; + stack<TreeNode *> st; + st.push(&dummy); + while (!st.empty()) { + TreeNode *root = st.top(); + if (!root) { + st.pop(); + root = st.top(), st.pop(); + if (has.count(root->left)) + has.insert(root); + else + root->left = nullptr; - if (has.count(root->right)) - has.insert(root); - else - root->right = nullptr; + if (has.count(root->right)) + has.insert(root); + else + root->right = nullptr; - if (root->val == 1) has.insert(root); - continue; - } - st.push(nullptr); - if (root->left) st.push(root->left); - if (root->right) st.push(root->right); + if (root->val == 1) has.insert(root); + continue; + } + st.push(nullptr); + if (root->left) st.push(root->left); + if (root->right) st.push(root->right); + } + return dummy.left; } - return dummy.left; - } }; diff --git a/Problems/0815.cpp b/Problems/0815.cpp @@ -1,32 +1,32 @@ class Solution { -public: - int numBusesToDestination(vector<vector<int>> &routes, int source, - int target) { - if (source == target) return 0; + public: + int numBusesToDestination(vector<vector<int>> &routes, int source, int target) { + if (source == target) return 0; - unordered_map<int, vector<int>> adj; - queue<int> q; + unordered_map<int, vector<int>> adj; + queue<int> q; - for (int i = 0; i < routes.size(); i++) - for (auto s : routes[i]) adj[s].push_back(i); - if (!adj.count(target)) return -1; + for (int i = 0; i < routes.size(); i++) + for (auto s : routes[i]) + adj[s].push_back(i); + if (!adj.count(target)) return -1; - q.push(source); - for (int lvl = 1; !q.empty(); lvl++) { - for (int k = q.size(); k > 0; k--) { - int crnt = q.front(); - q.pop(); - for (int r : adj[crnt]) { - for (int v : routes[r]) { - if (v == target) return lvl; - q.push(v); - } - routes[r].clear(); + q.push(source); + for (int lvl = 1; !q.empty(); lvl++) { + for (int k = q.size(); k > 0; k--) { + int crnt = q.front(); + q.pop(); + for (int r : adj[crnt]) { + for (int v : routes[r]) { + if (v == target) return lvl; + q.push(v); + } + routes[r].clear(); + } + adj[crnt].clear(); + } } - adj[crnt].clear(); - } - } - return -1; - } + return -1; + } }; diff --git a/Problems/0837.cpp b/Problems/0837.cpp @@ -1,17 +1,17 @@ class Solution { -public: - double new21Game(int n, int k, int maxPts) { - if (k == 0 || n >= k + maxPts) return 1.0; - vector<double> dp(n + 1); - double sum = 1.0, ans = 0.0; + public: + double new21Game(int n, int k, int maxPts) { + if (k == 0 || n >= k + maxPts) return 1.0; + vector<double> dp(n + 1); + double sum = 1.0, ans = 0.0; - dp[0] = 1.0; - for (int i = 1; i < n + 1; i++) { - dp[i] = sum / maxPts; - (i < k ? sum : ans) += dp[i]; - if (i - maxPts >= 0) sum -= dp[i - maxPts]; - } + dp[0] = 1.0; + for (int i = 1; i < n + 1; i++) { + dp[i] = sum / maxPts; + (i < k ? sum : ans) += dp[i]; + if (i - maxPts >= 0) sum -= dp[i - maxPts]; + } - return ans; - } + return ans; + } }; diff --git a/Problems/0839.cpp b/Problems/0839.cpp @@ -1,53 +1,52 @@ class UnionFind { - int n, cnt = n; - vector<int> root, size; + int n, cnt = n; + vector<int> root, size; -public: - UnionFind(int n) : n(n), root(n), size(n, 1) { - iota(root.begin(), root.end(), 0); - } + public: + UnionFind(int n) : n(n), root(n), size(n, 1) { iota(root.begin(), root.end(), 0); } - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (size[x] > size[y]) swap(x, y); - root[x] = y; - size[y] += size[x]; - cnt--; + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (size[x] > size[y]) swap(x, y); + root[x] = y; + size[y] += size[x]; + cnt--; + } } - } - int count() { return cnt; } - bool connected(int x, int y) { return find(x) == find(y); } + int count() { return cnt; } + bool connected(int x, int y) { return find(x) == find(y); } }; class Solution { - bool similar(const string &s1, const string &s2) { - int diff = 0; - for (int i = 0; i < s1.size(); i++) { - if (s1[i] == s2[i]) continue; - if (diff < 2) - diff++; - else - return false; + bool similar(const string &s1, const string &s2) { + int diff = 0; + for (int i = 0; i < s1.size(); i++) { + if (s1[i] == s2[i]) continue; + if (diff < 2) + diff++; + else + return false; + } + return true; } - return true; - } -public: - int numSimilarGroups(const vector<string> &strs) { - int n = strs.size(); - UnionFind uf(n); - for (int i = 0; i < n; i++) { - for (int j = i + 1; j < n; j++) { - if (similar(strs[i], strs[j])) uf.join(i, j); - } + public: + int numSimilarGroups(const vector<string> &strs) { + int n = strs.size(); + UnionFind uf(n); + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (similar(strs[i], strs[j])) uf.join(i, j); + } + } + return uf.count(); } - return uf.count(); - } }; diff --git a/Problems/0841.cpp b/Problems/0841.cpp @@ -1,21 +1,21 @@ class Solution { -public: - bool canVisitAllRooms(vector<vector<int>> &rooms) { - unordered_set<int> us; - queue<int> q; + public: + bool canVisitAllRooms(vector<vector<int>> &rooms) { + unordered_set<int> us; + queue<int> q; - q.push(0); - us.insert(0); - while (!q.empty()) { - int room = q.front(); - q.pop(); - for (int key : rooms[room]) { - if (!us.count(key)) { - us.insert(key); - q.push(key); + q.push(0); + us.insert(0); + while (!q.empty()) { + int room = q.front(); + q.pop(); + for (int key : rooms[room]) { + if (!us.count(key)) { + us.insert(key); + q.push(key); + } + } } - } + return us.size() == rooms.size(); } - return us.size() == rooms.size(); - } }; diff --git a/Problems/0844.cpp b/Problems/0844.cpp @@ -1,36 +1,36 @@ class Solution { -public: - bool backspaceCompare(string s, string t) { - int i = s.size() - 1, j = t.size() - 1; - int skipS = 0, skipT = 0; + public: + bool backspaceCompare(string s, string t) { + int i = s.size() - 1, j = t.size() - 1; + int skipS = 0, skipT = 0; - while (i >= 0 || j >= 0) { - while (i >= 0) { - if (s[i] == '#') { - skipS++, i--; - } else if (skipS > 0) { - skipS--; - i--; - } else - break; - } - while (j >= 0) { - if (t[j] == '#') { - skipT++, j--; - } else if (skipT > 0) { - skipT--; - j--; - } else - break; - } - if (i >= 0 && j >= 0 && s[i] != t[j]) return false; + while (i >= 0 || j >= 0) { + while (i >= 0) { + if (s[i] == '#') { + skipS++, i--; + } else if (skipS > 0) { + skipS--; + i--; + } else + break; + } + while (j >= 0) { + if (t[j] == '#') { + skipT++, j--; + } else if (skipT > 0) { + skipT--; + j--; + } else + break; + } + if (i >= 0 && j >= 0 && s[i] != t[j]) return false; - if ((i >= 0) != (j >= 0)) return false; + if ((i >= 0) != (j >= 0)) return false; - i--; - j--; - } + i--; + j--; + } - return true; - } + return true; + } }; diff --git a/Problems/0846.cpp b/Problems/0846.cpp @@ -1,55 +1,52 @@ class Solution { - typedef tuple<int, int, char> record; + typedef tuple<int, int, char> record; - int cantor(int a, int b) { return (a + b + 1) * (a + b) / 2 + b; } + int cantor(int a, int b) { return (a + b + 1) * (a + b) / 2 + b; } - int hash(const record &r) { - return cantor(get<0>(r), cantor(get<1>(r), get<2>(r))); - } + int hash(const record &r) { return cantor(get<0>(r), cantor(get<1>(r), get<2>(r))); } - int n, m; - int valid(int x, int y) { return x >= 0 && y >= 0 && x < n && y < m; } + int n, m; + int valid(int x, int y) { return x >= 0 && y >= 0 && x < n && y < m; } -public: - int shortestPathAllKeys(const vector<string> &grid) { - static const int offset_x[] = {0, 0, 1, -1}; - static const int offset_y[] = {1, -1, 0, 0}; - n = grid.size(), m = grid[0].size(); + public: + int shortestPathAllKeys(const vector<string> &grid) { + static const int offset_x[] = {0, 0, 1, -1}; + static const int offset_y[] = {1, -1, 0, 0}; + n = grid.size(), m = grid[0].size(); - int start_x = -1, start_y = -1, goal = 0; - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - if (grid[i][j] == '@') - start_x = i, start_y = j; - else if (islower(grid[i][j])) - goal |= 1 << (grid[i][j] & 0xF); - } - } + int start_x = -1, start_y = -1, goal = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (grid[i][j] == '@') + start_x = i, start_y = j; + else if (islower(grid[i][j])) + goal |= 1 << (grid[i][j] & 0xF); + } + } - unordered_set<int> visited; - queue<record> q; - q.push({start_x, start_y, 0}); - visited.insert(hash(q.front())); - for (int step = 0; !q.empty(); step++) { - for (int k = q.size(); k > 0; k--) { - auto [x, y, keys] = q.front(); - q.pop(); - if (keys == goal) return step; - for (int k = 0; k < 4; k++) { - int i = x + offset_x[k], j = y + offset_y[k], key = keys; - if (!valid(i, j) || grid[i][j] == '#') continue; - if (isupper(grid[i][j]) && !(key & (1 << (grid[i][j] & 0xF)))) - continue; - if (islower(grid[i][j])) key |= 1 << (grid[i][j] & 0xF); - const record r = {i, j, key}; - if (!visited.count(hash(r))) { - visited.insert(hash(r)); - q.push(r); - } + unordered_set<int> visited; + queue<record> q; + q.push({start_x, start_y, 0}); + visited.insert(hash(q.front())); + for (int step = 0; !q.empty(); step++) { + for (int k = q.size(); k > 0; k--) { + auto [x, y, keys] = q.front(); + q.pop(); + if (keys == goal) return step; + for (int k = 0; k < 4; k++) { + int i = x + offset_x[k], j = y + offset_y[k], key = keys; + if (!valid(i, j) || grid[i][j] == '#') continue; + if (isupper(grid[i][j]) && !(key & (1 << (grid[i][j] & 0xF)))) continue; + if (islower(grid[i][j])) key |= 1 << (grid[i][j] & 0xF); + const record r = {i, j, key}; + if (!visited.count(hash(r))) { + visited.insert(hash(r)); + q.push(r); + } + } + } } - } - } - return -1; - } + return -1; + } }; diff --git a/Problems/0851.cpp b/Problems/0851.cpp @@ -1,29 +1,29 @@ class Solution { -public: - vector<int> loudAndRich(vector<vector<int>> &richer, vector<int> &quiet) { - const int n = quiet.size(); - vector<vector<int>> adj(n); - vector<int> count(n); - vector<int> res(n); - iota(res.begin(), res.end(), 0); + public: + vector<int> loudAndRich(vector<vector<int>> &richer, vector<int> &quiet) { + const int n = quiet.size(); + vector<vector<int>> adj(n); + vector<int> count(n); + vector<int> res(n); + iota(res.begin(), res.end(), 0); - for (auto &p : richer) { - adj[p[0]].push_back(p[1]); - count[p[1]]++; - } + for (auto &p : richer) { + adj[p[0]].push_back(p[1]); + count[p[1]]++; + } - queue<int> q; - for (int i = 0; i < n; i++) - if (!count[i]) q.push(i); + queue<int> q; + for (int i = 0; i < n; i++) + if (!count[i]) q.push(i); - while (!q.empty()) { - int crnt = q.front(); - q.pop(); - for (int &c : adj[crnt]) { - if (quiet[res[c]] > quiet[res[crnt]]) res[c] = res[crnt]; - if (!--count[c]) q.push(c); - } + while (!q.empty()) { + int crnt = q.front(); + q.pop(); + for (int &c : adj[crnt]) { + if (quiet[res[c]] > quiet[res[crnt]]) res[c] = res[crnt]; + if (!--count[c]) q.push(c); + } + } + return res; } - return res; - } }; diff --git a/Problems/0852.cpp b/Problems/0852.cpp @@ -1,15 +1,15 @@ class Solution { -public: - int peakIndexInMountainArray(const vector<int> &arr) { - int low = 1, high = arr.size() - 2; - while (low <= high) { - int mid = low + (high - low) / 2; - if (arr[mid - 1] < arr[mid] && arr[mid] > arr[mid + 1]) return mid; - if (arr[mid - 1] < arr[mid]) - low = mid + 1; - else - high = mid - 1; + public: + int peakIndexInMountainArray(const vector<int> &arr) { + int low = 1, high = arr.size() - 2; + while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid - 1] < arr[mid] && arr[mid] > arr[mid + 1]) return mid; + if (arr[mid - 1] < arr[mid]) + low = mid + 1; + else + high = mid - 1; + } + return -1; } - return -1; - } }; diff --git a/Problems/0853.cpp b/Problems/0853.cpp @@ -1,44 +1,44 @@ class Solution { -public: - int carFleet(int target, vector<int> &position, vector<int> &speed) { - int n = position.size(); - if (!n) return 0; - vector<pair<int, double>> vp(n + 1); + public: + int carFleet(int target, vector<int> &position, vector<int> &speed) { + int n = position.size(); + if (!n) return 0; + vector<pair<int, double>> vp(n + 1); - for (int i = 0; i < n; i++) - vp[i] = {position[i], (double)(target - position[i]) / speed[i]}; - sort(vp.rbegin(), vp.rend()); + for (int i = 0; i < n; i++) + vp[i] = {position[i], (double)(target - position[i]) / speed[i]}; + sort(vp.rbegin(), vp.rend()); - int res = 0; - double ct = 0; - for (int i = 0; i < n; i++) { - auto [_, time] = vp[i]; - if (time > ct) { - res++; - ct = time; - } + int res = 0; + double ct = 0; + for (int i = 0; i < n; i++) { + auto [_, time] = vp[i]; + if (time > ct) { + res++; + ct = time; + } + } + return res; } - return res; - } }; // Using map for the heavy lifting class Solution { -public: - int carFleet(int target, vector<int> &position, vector<int> &speed) { - map<int, double> mp; + public: + int carFleet(int target, vector<int> &position, vector<int> &speed) { + map<int, double> mp; - for (int i = 0; i < speed.size(); i++) - mp[-position[i]] = (double)(target - position[i]) / speed[i]; + for (int i = 0; i < speed.size(); i++) + mp[-position[i]] = (double)(target - position[i]) / speed[i]; - int res = 0; - double ct = 0; - for (auto [_, time] : mp) { - if (time > ct) { - res++; - ct = time; - } + int res = 0; + double ct = 0; + for (auto [_, time] : mp) { + if (time > ct) { + res++; + ct = time; + } + } + return res; } - return res; - } }; diff --git a/Problems/0859.cpp b/Problems/0859.cpp @@ -1,22 +1,22 @@ class Solution { -public: - bool buddyStrings(const string &s, const string &goal) { - int a = -1, b = -1, dup = 0, count[26] = {0}; - if (s.size() != goal.size()) return false; - for (int i = 0; i < s.size(); i++) { - if (count[s[i] & 0xF]) dup = 1; - count[s[i] & 0xF] = 1; - if (s[i] != goal[i]) { - if (a == -1) - a = i; - else if (b == -1) - b = i; - else - return false; - } + public: + bool buddyStrings(const string &s, const string &goal) { + int a = -1, b = -1, dup = 0, count[26] = {0}; + if (s.size() != goal.size()) return false; + for (int i = 0; i < s.size(); i++) { + if (count[s[i] & 0xF]) dup = 1; + count[s[i] & 0xF] = 1; + if (s[i] != goal[i]) { + if (a == -1) + a = i; + else if (b == -1) + b = i; + else + return false; + } + } + if (a == -1) return dup; + if (b == -1) return false; + return s[a] == goal[b] && s[b] == goal[a]; } - if (a == -1) return dup; - if (b == -1) return false; - return s[a] == goal[b] && s[b] == goal[a]; - } }; diff --git a/Problems/0861.cpp b/Problems/0861.cpp @@ -1,20 +1,20 @@ class Solution { -public: - int matrixScore(const vector<vector<int>> &grid) { - int n = grid.size(), m = grid[0].size(); - unordered_set<int> flipped; - for (int i = 0; i < n; i++) { - if (grid[i][0]) continue; - flipped.insert(i); - } + public: + int matrixScore(const vector<vector<int>> &grid) { + int n = grid.size(), m = grid[0].size(); + unordered_set<int> flipped; + for (int i = 0; i < n; i++) { + if (grid[i][0]) continue; + flipped.insert(i); + } - int res = n * (1 << m - 1); - for (int j = 1; j < m; j++) { - int count = 0; - for (int i = 0; i < n; i++) - count += flipped.count(i) ? !grid[i][j] : grid[i][j]; - res += max(count, n - count) * (1 << m - j - 1); + int res = n * (1 << m - 1); + for (int j = 1; j < m; j++) { + int count = 0; + for (int i = 0; i < n; i++) + count += flipped.count(i) ? !grid[i][j] : grid[i][j]; + res += max(count, n - count) * (1 << m - j - 1); + } + return res; } - return res; - } }; diff --git a/Problems/0863.cpp b/Problems/0863.cpp @@ -1,52 +1,52 @@ class Solution { - TreeNode *parent[501]; - void find(TreeNode *root, TreeNode *target) { - queue<TreeNode *> q({root}); + TreeNode *parent[501]; + void find(TreeNode *root, TreeNode *target) { + queue<TreeNode *> q({root}); - parent[root->val] = NULL; - while (!q.empty()) { - for (int k = q.size(); k > 0; k--) { - TreeNode *root = q.front(); - q.pop(); - if (root == target) return; - if (root->left) { - parent[root->left->val] = root; - q.push(root->left); + parent[root->val] = NULL; + while (!q.empty()) { + for (int k = q.size(); k > 0; k--) { + TreeNode *root = q.front(); + q.pop(); + if (root == target) return; + if (root->left) { + parent[root->left->val] = root; + q.push(root->left); + } + if (root->right) { + parent[root->right->val] = root; + q.push(root->right); + } + } } - if (root->right) { - parent[root->right->val] = root; - q.push(root->right); - } - } } - } -public: - vector<int> distanceK(TreeNode *root, TreeNode *target, int k) { - if (k == 0) return {target->val}; - find(root, target); + public: + vector<int> distanceK(TreeNode *root, TreeNode *target, int k) { + if (k == 0) return {target->val}; + find(root, target); - vector<int> res; - while (k-- >= 0) { - queue<TreeNode *> q({target}); - for (int i = 0; i <= k && !q.empty(); i++) { - for (int t = q.size(); t > 0; t--) { - TreeNode *root = q.front(); - q.pop(); - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } - } - while (!q.empty()) { - res.push_back(q.front()->val); - q.pop(); - } + vector<int> res; + while (k-- >= 0) { + queue<TreeNode *> q({target}); + for (int i = 0; i <= k && !q.empty(); i++) { + for (int t = q.size(); t > 0; t--) { + TreeNode *root = q.front(); + q.pop(); + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + } + while (!q.empty()) { + res.push_back(q.front()->val); + q.pop(); + } - TreeNode *p = parent[target->val]; - if (!p) break; - (p->left == target ? p->left : p->right) = NULL; - target = p; + TreeNode *p = parent[target->val]; + if (!p) break; + (p->left == target ? p->left : p->right) = NULL; + target = p; + } + return res; } - return res; - } }; diff --git a/Problems/0872.cpp b/Problems/0872.cpp @@ -1,27 +1,25 @@ class Solution { - vector<int> sequence(TreeNode *root) { - if (!root) return {}; + vector<int> sequence(TreeNode *root) { + if (!root) return {}; - vector<int> res; - stack<TreeNode *> st; + vector<int> res; + stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (!root->left && !root->right) { - res.push_back(root->val); - continue; - } - if (root->left) st.push(root->left); - if (root->right) st.push(root->right); - } + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (!root->left && !root->right) { + res.push_back(root->val); + continue; + } + if (root->left) st.push(root->left); + if (root->right) st.push(root->right); + } - return res; - } + return res; + } -public: - bool leafSimilar(TreeNode *root1, TreeNode *root2) { - return sequence(root1) == sequence(root2); - } + public: + bool leafSimilar(TreeNode *root1, TreeNode *root2) { return sequence(root1) == sequence(root2); } }; diff --git a/Problems/0875.cpp b/Problems/0875.cpp @@ -1,15 +1,16 @@ class Solution { -public: - int minEatingSpeed(vector<int> &piles, int h) { - int low = 1, high = INT_MAX, mid, count; - while (low < high) { - mid = low + (high - low) / 2, count = 0; - for (int pile : piles) count += ceil((double)pile / mid); - if (count <= h) - high = mid; - else - low = mid + 1; + public: + int minEatingSpeed(vector<int> &piles, int h) { + int low = 1, high = INT_MAX, mid, count; + while (low < high) { + mid = low + (high - low) / 2, count = 0; + for (int pile : piles) + count += ceil((double)pile / mid); + if (count <= h) + high = mid; + else + low = mid + 1; + } + return low; } - return low; - } }; diff --git a/Problems/0876.cpp b/Problems/0876.cpp @@ -1,14 +1,14 @@ class Solution { -public: - ListNode *middleNode(ListNode *head) { - ListNode *fast, *slow; - fast = slow = head; - while (fast->next && fast->next->next) { - fast = fast->next->next; - slow = slow->next; - } - if (fast->next) slow = slow->next; + public: + ListNode *middleNode(ListNode *head) { + ListNode *fast, *slow; + fast = slow = head; + while (fast->next && fast->next->next) { + fast = fast->next->next; + slow = slow->next; + } + if (fast->next) slow = slow->next; - return slow; - } + return slow; + } }; diff --git a/Problems/0879.cpp b/Problems/0879.cpp @@ -1,19 +1,19 @@ class Solution { -public: - int profitableSchemes(int n, int minProfit, const vector<int> &group, - const vector<int> &profit) { - int dp[101][101] = {{1}}; - int res = 0, mod = 1e9 + 7; - for (int k = 0; k < group.size(); k++) { - int g = group[k], p = profit[k]; - for (int i = minProfit; i >= 0; i--) { - for (int j = n - g; j >= 0; j--) { - int &cache = dp[min(i + p, minProfit)][j + g]; - cache = (cache + dp[i][j]) % mod; + public: + int profitableSchemes(int n, int minProfit, const vector<int> &group, const vector<int> &profit) { + int dp[101][101] = {{1}}; + int res = 0, mod = 1e9 + 7; + for (int k = 0; k < group.size(); k++) { + int g = group[k], p = profit[k]; + for (int i = minProfit; i >= 0; i--) { + for (int j = n - g; j >= 0; j--) { + int &cache = dp[min(i + p, minProfit)][j + g]; + cache = (cache + dp[i][j]) % mod; + } + } } - } + for (int x : dp[minProfit]) + res = (res + x) % mod; + return res; } - for (int x : dp[minProfit]) res = (res + x) % mod; - return res; - } }; diff --git a/Problems/0881.cpp b/Problems/0881.cpp @@ -1,14 +1,14 @@ class Solution { -public: - int numRescueBoats(vector<int> &people, int limit) { - sort(people.begin(), people.end()); - int low = 0, high = people.size() - 1, res = 0; - while (low <= high) { - if (people[low] + people[high] <= limit) low++; - high--; - res++; - } + public: + int numRescueBoats(vector<int> &people, int limit) { + sort(people.begin(), people.end()); + int low = 0, high = people.size() - 1, res = 0; + while (low <= high) { + if (people[low] + people[high] <= limit) low++; + high--; + res++; + } - return res; - } + return res; + } }; diff --git a/Problems/0884.cpp b/Problems/0884.cpp @@ -1,20 +1,22 @@ class Solution { -public: - vector<string> uncommonFromSentences(string s1, string s2) { - unordered_map<string, int> um; - stringstream ss; - string t; + public: + vector<string> uncommonFromSentences(string s1, string s2) { + unordered_map<string, int> um; + stringstream ss; + string t; - ss.str(s1); - while (ss >> t) um[t]++; + ss.str(s1); + while (ss >> t) + um[t]++; - ss.str(s2); - ss.clear(); - while (ss >> t) um[t]++; + ss.str(s2); + ss.clear(); + while (ss >> t) + um[t]++; - vector<string> res; - for (auto &[str, cnt] : um) - if (cnt == 1) res.push_back(str); - return res; - } + vector<string> res; + for (auto &[str, cnt] : um) + if (cnt == 1) res.push_back(str); + return res; + } }; diff --git a/Problems/0885.cpp b/Problems/0885.cpp @@ -1,22 +1,21 @@ class Solution { -public: - vector<vector<int>> spiralMatrixIII(const int rows, const int cols, int x, - int y) { - static const int8_t offset_x[4] = {0, 1, 0, -1}; - static const int8_t offset_y[4] = {1, 0, -1, 0}; - vector<vector<int>> res; - res.reserve(rows * cols); - int dir = 0, cnt = 1, len = 1; + public: + vector<vector<int>> spiralMatrixIII(const int rows, const int cols, int x, int y) { + static const int8_t offset_x[4] = {0, 1, 0, -1}; + static const int8_t offset_y[4] = {1, 0, -1, 0}; + vector<vector<int>> res; + res.reserve(rows * cols); + int dir = 0, cnt = 1, len = 1; - while (res.size() < rows * cols) { - for (int i = 0; i < len; i++) { - if (x >= 0 && x < rows && y >= 0 && y < cols) res.push_back({x, y}); - x += offset_x[dir], y += offset_y[dir]; - } - len += dir & 1; - dir = (dir + 1) & 0x3; - } + while (res.size() < rows * cols) { + for (int i = 0; i < len; i++) { + if (x >= 0 && x < rows && y >= 0 && y < cols) res.push_back({x, y}); + x += offset_x[dir], y += offset_y[dir]; + } + len += dir & 1; + dir = (dir + 1) & 0x3; + } - return res; - } + return res; + } }; diff --git a/Problems/0886.cpp b/Problems/0886.cpp @@ -1,30 +1,30 @@ class Solution { -public: - bool possibleBipartition(int n, vector<vector<int>> &dislikes) { - vector<vector<int>> adj(n + 1, vector<int>()); - for (auto &p : dislikes) { - adj[p[0]].push_back(p[1]); - adj[p[1]].push_back(p[0]); - } + public: + bool possibleBipartition(int n, vector<vector<int>> &dislikes) { + vector<vector<int>> adj(n + 1, vector<int>()); + for (auto &p : dislikes) { + adj[p[0]].push_back(p[1]); + adj[p[1]].push_back(p[0]); + } - stack<int> st; - vector<int> color(n + 1, -1); - for (int i = 1; i <= n; i++) { - if (color[i] != -1) continue; - color[i] = 0; - st.push(i); - while (!st.empty()) { - int root = st.top(); - st.pop(); - for (int child : adj[root]) { - if (color[child] == color[root]) return false; - if (color[child] == -1) { - color[child] = !color[root]; - st.push(child); - } + stack<int> st; + vector<int> color(n + 1, -1); + for (int i = 1; i <= n; i++) { + if (color[i] != -1) continue; + color[i] = 0; + st.push(i); + while (!st.empty()) { + int root = st.top(); + st.pop(); + for (int child : adj[root]) { + if (color[child] == color[root]) return false; + if (color[child] == -1) { + color[child] = !color[root]; + st.push(child); + } + } + } } - } + return true; } - return true; - } }; diff --git a/Problems/0890.cpp b/Problems/0890.cpp @@ -1,28 +1,27 @@ class Solution { -public: - vector<string> findAndReplacePattern(const vector<string> &words, - const string &pattern) { - vector<string> res; - static int um[27] = {0}; - static bool used[27] = {0}; - for (const auto &word : words) { - for (int i = 0; i < pattern.size(); i++) { - const uint8_t w = word[i] & 0x1F; - const uint8_t p = pattern[i] & 0x1F; - if (um[w]) { - if (um[w] != p) goto next; - continue; + public: + vector<string> findAndReplacePattern(const vector<string> &words, const string &pattern) { + vector<string> res; + static int um[27] = {0}; + static bool used[27] = {0}; + for (const auto &word : words) { + for (int i = 0; i < pattern.size(); i++) { + const uint8_t w = word[i] & 0x1F; + const uint8_t p = pattern[i] & 0x1F; + if (um[w]) { + if (um[w] != p) goto next; + continue; + } + if (used[p]) goto next; + used[p] = true; + um[w] = p; + } + res.push_back(word); + next:; + memset(um, 0x00, sizeof(um)); + memset(used, 0x00, sizeof(used)); } - if (used[p]) goto next; - used[p] = true; - um[w] = p; - } - res.push_back(word); - next:; - memset(um, 0x00, sizeof(um)); - memset(used, 0x00, sizeof(used)); - } - return res; - } + return res; + } }; diff --git a/Problems/0894.cpp b/Problems/0894.cpp @@ -1,35 +1,33 @@ class Solution { - TreeNode *duplicate(TreeNode *root) { - TreeNode *dup = new TreeNode(root->val); - if (root->left) dup->left = duplicate(root->left); - if (root->right) dup->right = duplicate(root->right); - return dup; - } + TreeNode *duplicate(TreeNode *root) { + TreeNode *dup = new TreeNode(root->val); + if (root->left) dup->left = duplicate(root->left); + if (root->right) dup->right = duplicate(root->right); + return dup; + } - vector<TreeNode *> dp[20]; + vector<TreeNode *> dp[20]; -public: - vector<TreeNode *> allPossibleFBT(int n) { - if (n % 2 == 0) return {}; - if (1 == n) return {new TreeNode(0)}; + public: + vector<TreeNode *> allPossibleFBT(int n) { + if (n % 2 == 0) return {}; + if (1 == n) return {new TreeNode(0)}; - if (!dp[n].empty()) return dp[n]; + if (!dp[n].empty()) return dp[n]; - vector<TreeNode *> ret; - for (int i = 2; i <= n; i += 2) { - auto left = allPossibleFBT(i - 1); - auto right = allPossibleFBT(n - i); - for (int l = 0; l < left.size(); l++) { - for (int r = 0; r < right.size(); r++) { - ret.push_back(new TreeNode(0)); - ret.back()->left = - (r == right.size() - 1) ? left[l] : duplicate(left[l]); - ret.back()->right = - (l == left.size() - 1) ? right[r] : duplicate(right[r]); + vector<TreeNode *> ret; + for (int i = 2; i <= n; i += 2) { + auto left = allPossibleFBT(i - 1); + auto right = allPossibleFBT(n - i); + for (int l = 0; l < left.size(); l++) { + for (int r = 0; r < right.size(); r++) { + ret.push_back(new TreeNode(0)); + ret.back()->left = (r == right.size() - 1) ? left[l] : duplicate(left[l]); + ret.back()->right = (l == left.size() - 1) ? right[r] : duplicate(right[r]); + } + } } - } - } - return dp[n] = ret; - } + return dp[n] = ret; + } }; diff --git a/Problems/0897.cpp b/Problems/0897.cpp @@ -1,21 +1,21 @@ class Solution { -public: - TreeNode *increasingBST(TreeNode *root) { - TreeNode *head, *tmp; - tmp = head = new TreeNode(); - stack<TreeNode *> st; - while (true) { - while (root) { - st.push(root); - root = root->left; - } - if (st.empty()) break; - root = st.top(); - st.pop(); - tmp = tmp->right = root; - tmp->left = nullptr; - root = root->right; + public: + TreeNode *increasingBST(TreeNode *root) { + TreeNode *head, *tmp; + tmp = head = new TreeNode(); + stack<TreeNode *> st; + while (true) { + while (root) { + st.push(root); + root = root->left; + } + if (st.empty()) break; + root = st.top(); + st.pop(); + tmp = tmp->right = root; + tmp->left = nullptr; + root = root->right; + } + return head->right; } - return head->right; - } }; diff --git a/Problems/0901.cpp b/Problems/0901.cpp @@ -1,20 +1,20 @@ class StockSpanner { - static const int length = 10001; - int size = 0; - pair<int, int> stocks[length]; + static const int length = 10001; + int size = 0; + pair<int, int> stocks[length]; -public: - StockSpanner() {} + public: + StockSpanner() {} - int next(int price) { - int index = size - 1; - while (index >= 0) - if (price >= stocks[index].first) - index -= stocks[index].second; - else - break; - int span = size - index; - stocks[size++] = make_pair(price, span); - return span; - } + int next(int price) { + int index = size - 1; + while (index >= 0) + if (price >= stocks[index].first) + index -= stocks[index].second; + else + break; + int span = size - index; + stocks[size++] = make_pair(price, span); + return span; + } }; diff --git a/Problems/0904.cpp b/Problems/0904.cpp @@ -1,39 +1,39 @@ class Solution { -public: - int totalFruit(vector<int> &fruits) { - pair<int, int> used = {fruits[0], -1}, count = {0, 0}, pos = {0, 0}; - int start = 0, res = 0; + public: + int totalFruit(vector<int> &fruits) { + pair<int, int> used = {fruits[0], -1}, count = {0, 0}, pos = {0, 0}; + int start = 0, res = 0; - for (start = 0; start < fruits.size(); start++) - if (fruits[start] != used.first) - break; - else - count.first++; + for (start = 0; start < fruits.size(); start++) + if (fruits[start] != used.first) + break; + else + count.first++; - if (start == fruits.size()) return count.first; + if (start == fruits.size()) return count.first; - used.second = fruits[start]; - for (int i = start; i < fruits.size(); i++) { - if (fruits[i] == used.first) - count.first++, pos.first++, pos.second = 0; - else if (fruits[i] == used.second) - count.second++, pos.first = 0, pos.second++; - else { - res = max(res, count.first + count.second); - if (fruits[i - 1] == used.second) { - used.first = fruits[i]; - count = pos; - pos = {1, 0}; - count.first++; - } else { - used.second = fruits[i]; - count = pos; - pos = {0, 1}; - count.second++; + used.second = fruits[start]; + for (int i = start; i < fruits.size(); i++) { + if (fruits[i] == used.first) + count.first++, pos.first++, pos.second = 0; + else if (fruits[i] == used.second) + count.second++, pos.first = 0, pos.second++; + else { + res = max(res, count.first + count.second); + if (fruits[i - 1] == used.second) { + used.first = fruits[i]; + count = pos; + pos = {1, 0}; + count.first++; + } else { + used.second = fruits[i]; + count = pos; + pos = {0, 1}; + count.second++; + } + } } - } - } - return max(res, count.first + count.second); - } + return max(res, count.first + count.second); + } }; diff --git a/Problems/0905.cpp b/Problems/0905.cpp @@ -1,11 +1,11 @@ class Solution { -public: - vector<int> sortArrayByParity(vector<int> &nums) { - vector<int> res; - for (int i : nums) - if (i % 2 == 0) res.push_back(i); - for (int i : nums) - if (i % 2 == 1) res.push_back(i); - return res; - } + public: + vector<int> sortArrayByParity(vector<int> &nums) { + vector<int> res; + for (int i : nums) + if (i % 2 == 0) res.push_back(i); + for (int i : nums) + if (i % 2 == 1) res.push_back(i); + return res; + } }; diff --git a/Problems/0909.cpp b/Problems/0909.cpp @@ -1,40 +1,40 @@ class Solution { -public: - int snakesAndLadders(vector<vector<int>> &board) { - const int n = board.size(); + public: + int snakesAndLadders(vector<vector<int>> &board) { + const int n = board.size(); - // index directy with a square instead of a coordinate - vector<int> cord(n * n + 1); + // index directy with a square instead of a coordinate + vector<int> cord(n * n + 1); - int crnt = 1, x = n - 1, y = 0, dir = 1; - while (crnt <= n * n) { - cord[crnt] = board[x][y]; - if (crnt % n == 0) - x--, dir *= -1; - else - y += dir; - crnt++; - } + int crnt = 1, x = n - 1, y = 0, dir = 1; + while (crnt <= n * n) { + cord[crnt] = board[x][y]; + if (crnt % n == 0) + x--, dir *= -1; + else + y += dir; + crnt++; + } - vector<bool> visited(n * n + 1); - queue<pair<int, int>> q; - int res = INT_MAX; + vector<bool> visited(n * n + 1); + queue<pair<int, int>> q; + int res = INT_MAX; - q.push({1, 0}), visited[1] = true; - while (!q.empty()) { - auto [crnt, move] = q.front(); - q.pop(); + q.push({1, 0}), visited[1] = true; + while (!q.empty()) { + auto [crnt, move] = q.front(); + q.pop(); - if (crnt == n * n) return move; + if (crnt == n * n) return move; - for (int i = 0; i < 6; i++) { - if (++crnt > n * n) break; - int square = cord[crnt] == -1 ? crnt : cord[crnt]; - if (visited[square]) continue; - visited[square] = true; - q.push({square, move + 1}); - } + for (int i = 0; i < 6; i++) { + if (++crnt > n * n) break; + int square = cord[crnt] == -1 ? crnt : cord[crnt]; + if (visited[square]) continue; + visited[square] = true; + q.push({square, move + 1}); + } + } + return -1; } - return -1; - } }; diff --git a/Problems/0912.cpp b/Problems/0912.cpp @@ -1,4 +1,3 @@ -Formating: Problems/0164.cpp -Formating: Problems/0164.cpp -Formating: Problems/0912.cpp -Formating: Problems/2343.cpp +Formating + : Problems / + 0164.cpp Formating : Problems / 0164.cpp Formating : Problems / 0912.cpp Formating : Problems / 2343.cpp diff --git a/Problems/0915.cpp b/Problems/0915.cpp @@ -1,18 +1,18 @@ class Solution { -public: - int partitionDisjoint(vector<int> &nums) { - int n = nums.size(); - vector<int> left(n), right(n); + public: + int partitionDisjoint(vector<int> &nums) { + int n = nums.size(); + vector<int> left(n), right(n); - left[0] = nums[0]; - right.back() = nums.back(); - for (int i = 1; i < nums.size(); i++) { - left[i] = max(nums[i], left[i - 1]); - right[n - i - 1] = min(nums[n - i - 1], right[n - i]); - } + left[0] = nums[0]; + right.back() = nums.back(); + for (int i = 1; i < nums.size(); i++) { + left[i] = max(nums[i], left[i - 1]); + right[n - i - 1] = min(nums[n - i - 1], right[n - i]); + } - for (int i = 0; i < n - 1; i++) - if (left[i] <= right[i + 1]) return i + 1; - return -1; - } + for (int i = 0; i < n - 1; i++) + if (left[i] <= right[i + 1]) return i + 1; + return -1; + } }; diff --git a/Problems/0918.cpp b/Problems/0918.cpp @@ -1,17 +1,17 @@ class Solution { -public: - int maxSubarraySumCircular(vector<int> &nums) { - int total, maxSum, curMax, minSum, curMin; + public: + int maxSubarraySumCircular(vector<int> &nums) { + int total, maxSum, curMax, minSum, curMin; - total = curMax = curMin = 0; - maxSum = minSum = nums[0]; - for (int &n : nums) { - curMax = max(curMax + n, n); - maxSum = max(maxSum, curMax); - curMin = min(curMin + n, n); - minSum = min(minSum, curMin); - total += n; + total = curMax = curMin = 0; + maxSum = minSum = nums[0]; + for (int &n : nums) { + curMax = max(curMax + n, n); + maxSum = max(maxSum, curMax); + curMin = min(curMin + n, n); + minSum = min(minSum, curMin); + total += n; + } + return maxSum > 0 ? max(maxSum, total - minSum) : maxSum; } - return maxSum > 0 ? max(maxSum, total - minSum) : maxSum; - } }; diff --git a/Problems/0920.cpp b/Problems/0920.cpp @@ -1,17 +1,17 @@ class Solution { - static const int MOD = 1e9 + 7; - long dp[101][101] = {1, 0}; + static const int MOD = 1e9 + 7; + long dp[101][101] = {1, 0}; -public: - int numMusicPlaylists(int n, int goal, int k) { - for (int i = 1; i <= goal; i++) { - for (int j = 1; j <= n; j++) { - dp[i][j] = (dp[i - 1][j - 1] * (n - (j - 1))) % MOD; - if (j > k) { - dp[i][j] = (dp[i][j] + (dp[i - 1][j] * (j - k)) % MOD) % MOD; + public: + int numMusicPlaylists(int n, int goal, int k) { + for (int i = 1; i <= goal; i++) { + for (int j = 1; j <= n; j++) { + dp[i][j] = (dp[i - 1][j - 1] * (n - (j - 1))) % MOD; + if (j > k) { + dp[i][j] = (dp[i][j] + (dp[i - 1][j] * (j - k)) % MOD) % MOD; + } + } } - } + return (int)dp[goal][n]; } - return (int)dp[goal][n]; - } }; diff --git a/Problems/0921.cpp b/Problems/0921.cpp @@ -1,17 +1,17 @@ class Solution { -public: - int minAddToMakeValid(const string &s) { - int res = 0, cnt = 0; - for (char c : s) { - if (c == '(') - cnt++; - else if (c == ')') { - if (cnt > 0) - cnt--; - else - res++; - } + public: + int minAddToMakeValid(const string &s) { + int res = 0, cnt = 0; + for (char c : s) { + if (c == '(') + cnt++; + else if (c == ')') { + if (cnt > 0) + cnt--; + else + res++; + } + } + return res + cnt; } - return res + cnt; - } }; diff --git a/Problems/0926.cpp b/Problems/0926.cpp @@ -1,12 +1,12 @@ class Solution { -public: - int minFlipsMonoIncr(string s) { - int res = 0, num = 0; - for (char c : s) - if (c == '0') - res = min(num, res + 1); - else - ++num; - return res; - } + public: + int minFlipsMonoIncr(string s) { + int res = 0, num = 0; + for (char c : s) + if (c == '0') + res = min(num, res + 1); + else + ++num; + return res; + } }; diff --git a/Problems/0931.cpp b/Problems/0931.cpp @@ -1,27 +1,28 @@ class Solution { - int n; + int n; - bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < n; } + bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < n; } -public: - int minFallingPathSum(vector<vector<int>> &matrix) { - n = matrix.size(); + public: + int minFallingPathSum(vector<vector<int>> &matrix) { + n = matrix.size(); - for (int i = n - 2; i >= 0; i--) { - for (int j = 0; j < n; j++) { - int mini = INT_MAX; - for (int k = -1; k <= 1; k++) { - int x = i + 1; - int y = j + k; - if (!valid(x, y)) continue; - mini = min(mini, matrix[x][y]); + for (int i = n - 2; i >= 0; i--) { + for (int j = 0; j < n; j++) { + int mini = INT_MAX; + for (int k = -1; k <= 1; k++) { + int x = i + 1; + int y = j + k; + if (!valid(x, y)) continue; + mini = min(mini, matrix[x][y]); + } + matrix[i][j] += mini; + } } - matrix[i][j] += mini; - } - } - int mini = INT_MAX; - for (int i = 0; i < n; i++) mini = min(mini, matrix[0][i]); - return mini; - } + int mini = INT_MAX; + for (int i = 0; i < n; i++) + mini = min(mini, matrix[0][i]); + return mini; + } }; diff --git a/Problems/0933.cpp b/Problems/0933.cpp @@ -1,10 +1,11 @@ class RecentCounter { - queue<int> q; + queue<int> q; -public: - int ping(int t) { - q.push(t); - while (t - 3000 > q.front()) q.pop(); - return q.size(); - } + public: + int ping(int t) { + q.push(t); + while (t - 3000 > q.front()) + q.pop(); + return q.size(); + } }; diff --git a/Problems/0934.cpp b/Problems/0934.cpp @@ -1,58 +1,58 @@ class Solution { - static const constexpr int offs_x[] = {1, 0, -1, 0}; - static const constexpr int offs_y[] = {0, 1, 0, -1}; + static const constexpr int offs_x[] = {1, 0, -1, 0}; + static const constexpr int offs_y[] = {0, 1, 0, -1}; - int n; + int n; - bool valid(int i, int j) { return i >= 0 && i < n && j >= 0 && j < n; } + bool valid(int i, int j) { return i >= 0 && i < n && j >= 0 && j < n; } -public: - int shortestBridge(vector<vector<int>> &grid) { - queue<pair<int, int>> dq1, dq2; - n = grid.size(); + public: + int shortestBridge(vector<vector<int>> &grid) { + queue<pair<int, int>> dq1, dq2; + n = grid.size(); - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - if (!grid[i][j]) continue; - dq1.push({i, j}); - grid[i][j] = 2; - goto parse; - } - } + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (!grid[i][j]) continue; + dq1.push({i, j}); + grid[i][j] = 2; + goto parse; + } + } - return -1; - - parse: - while (!dq1.empty()) { - auto [i, j] = dq1.front(); - dq1.pop(); - for (int k = 0; k < 4; k++) { - int a = i + offs_x[k], b = j + offs_y[k]; - if (!valid(a, b)) continue; - if (grid[a][b] == 1) - dq1.push({a, b}); - else if (grid[a][b] == 0) - dq2.push({a, b}); - grid[a][b] = 2; - } - } + return -1; + + parse: + while (!dq1.empty()) { + auto [i, j] = dq1.front(); + dq1.pop(); + for (int k = 0; k < 4; k++) { + int a = i + offs_x[k], b = j + offs_y[k]; + if (!valid(a, b)) continue; + if (grid[a][b] == 1) + dq1.push({a, b}); + else if (grid[a][b] == 0) + dq2.push({a, b}); + grid[a][b] = 2; + } + } - for (int lvl = 1; !dq2.empty(); lvl++) { - for (int k = dq2.size(); k > 0; k--) { - auto [i, j] = dq2.front(); - dq2.pop(); - for (int k = 0; k < 4; k++) { - int a = i + offs_x[k], b = j + offs_y[k]; - if (!valid(a, b)) continue; - if (grid[a][b] == 1) - return lvl; - else if (grid[a][b] == 0) - dq2.push({a, b}); - grid[a][b] = 2; + for (int lvl = 1; !dq2.empty(); lvl++) { + for (int k = dq2.size(); k > 0; k--) { + auto [i, j] = dq2.front(); + dq2.pop(); + for (int k = 0; k < 4; k++) { + int a = i + offs_x[k], b = j + offs_y[k]; + if (!valid(a, b)) continue; + if (grid[a][b] == 1) + return lvl; + else if (grid[a][b] == 0) + dq2.push({a, b}); + grid[a][b] = 2; + } + } } - } - } - return -1; - } + return -1; + } }; diff --git a/Problems/0938.cpp b/Problems/0938.cpp @@ -1,21 +1,21 @@ class Solution { -public: - Solution() { - ios_base::sync_with_stdio(false); - cin.tie(nullptr); - cout.tie(nullptr); - } - int rangeSumBST(TreeNode *root, int low, int high) { - int sum = 0; - stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (root->val >= low && root->val <= high) sum += root->val; - if (root->left && root->val > low) st.push(root->left); - if (root->right && root->val < high) st.push(root->right); + public: + Solution() { + ios_base::sync_with_stdio(false); + cin.tie(nullptr); + cout.tie(nullptr); + } + int rangeSumBST(TreeNode *root, int low, int high) { + int sum = 0; + stack<TreeNode *> st; + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (root->val >= low && root->val <= high) sum += root->val; + if (root->left && root->val > low) st.push(root->left); + if (root->right && root->val < high) st.push(root->right); + } + return sum; } - return sum; - } }; diff --git a/Problems/0941.cpp b/Problems/0941.cpp @@ -1,16 +1,18 @@ class Solution { -public: - bool validMountainArray(vector<int> &arr) { - int i = 0; - while (i < arr.size() - 1 && arr[i] < arr[i + 1]) i++; + public: + bool validMountainArray(vector<int> &arr) { + int i = 0; + while (i < arr.size() - 1 && arr[i] < arr[i + 1]) + i++; - if (i == 0) return false; + if (i == 0) return false; - int j = i; - while (i < arr.size() - 1 && arr[i] > arr[i + 1]) i++; + int j = i; + while (i < arr.size() - 1 && arr[i] > arr[i + 1]) + i++; - if (i == j) return false; + if (i == j) return false; - return i == arr.size() - 1; - } + return i == arr.size() - 1; + } }; diff --git a/Problems/0944.cpp b/Problems/0944.cpp @@ -1,15 +1,15 @@ class Solution { -public: - int minDeletionSize(vector<string> &strs) { - int count = 0; - for (int i = 0; i < strs[0].size(); i++) { - for (int j = 1; j < strs.size(); j++) { - if (strs[j][i] < strs[j - 1][i]) { - count++; - break; + public: + int minDeletionSize(vector<string> &strs) { + int count = 0; + for (int i = 0; i < strs[0].size(); i++) { + for (int j = 1; j < strs.size(); j++) { + if (strs[j][i] < strs[j - 1][i]) { + count++; + break; + } + } } - } + return count; } - return count; - } }; diff --git a/Problems/0946.cpp b/Problems/0946.cpp @@ -1,26 +1,26 @@ class Solution { -public: - bool validateStackSequences(vector<int> &pushed, vector<int> &popped) { - int n = pushed.size(), m = popped.size(); - int i = 0, j = 0; - stack<int> st; + public: + bool validateStackSequences(vector<int> &pushed, vector<int> &popped) { + int n = pushed.size(), m = popped.size(); + int i = 0, j = 0; + stack<int> st; - while (i < n || j < m) { - if (st.empty()) { - if (i < n) - st.push(pushed[i++]); - else - return false; - } else { - if (st.top() == popped[j]) - st.pop(), j++; - else if (i < n) - st.push(pushed[i++]); - else - return false; - } - } + while (i < n || j < m) { + if (st.empty()) { + if (i < n) + st.push(pushed[i++]); + else + return false; + } else { + if (st.top() == popped[j]) + st.pop(), j++; + else if (i < n) + st.push(pushed[i++]); + else + return false; + } + } - return true; - } + return true; + } }; diff --git a/Problems/0947.cpp b/Problems/0947.cpp @@ -1,31 +1,31 @@ class Solution { -public: - int removeStones(vector<vector<int>> &stones) { - unordered_map<int, vector<int>> rows, cols; - unordered_set<int> seen; + public: + int removeStones(vector<vector<int>> &stones) { + unordered_map<int, vector<int>> rows, cols; + unordered_set<int> seen; - for (int s = 0; s < size(stones); ++s) - rows[stones[s][0]].push_back(s), cols[stones[s][1]].push_back(s); + for (int s = 0; s < size(stones); ++s) + rows[stones[s][0]].push_back(s), cols[stones[s][1]].push_back(s); - int c = 0; - stack<int> st; - for (int s = 0; s < size(stones); ++s) { - if (seen.count(s)) continue; - st.push(s); - while (!st.empty()) { - int s = st.top(); - st.pop(); - if (seen.count(s)) continue; - seen.insert(s); - int r = stones[s][0], c = stones[s][1]; - for (auto ss : rows[r]) - if (!seen.count(ss)) st.push(ss); - for (auto ss : cols[c]) - if (!seen.count(ss)) st.push(ss); - } - c++; - } + int c = 0; + stack<int> st; + for (int s = 0; s < size(stones); ++s) { + if (seen.count(s)) continue; + st.push(s); + while (!st.empty()) { + int s = st.top(); + st.pop(); + if (seen.count(s)) continue; + seen.insert(s); + int r = stones[s][0], c = stones[s][1]; + for (auto ss : rows[r]) + if (!seen.count(ss)) st.push(ss); + for (auto ss : cols[c]) + if (!seen.count(ss)) st.push(ss); + } + c++; + } - return size(stones) - c; - } + return size(stones) - c; + } }; diff --git a/Problems/0950.cpp b/Problems/0950.cpp @@ -1,22 +1,21 @@ class Solution { -public: - vector<int> deckRevealedIncreasing(vector<int> &deck) { - sort(deck.begin(), deck.end(), - [](const int a, const int b) { return a > b; }); - deque<int> q; - vector<int> res; + public: + vector<int> deckRevealedIncreasing(vector<int> &deck) { + sort(deck.begin(), deck.end(), [](const int a, const int b) { return a > b; }); + deque<int> q; + vector<int> res; - for (int i = 0; i < deck.size() - 1; i++) { - q.push_back(deck[i]); - q.push_back(q.front()); - q.pop_front(); - } - q.push_back(deck[deck.size() - 1]); + for (int i = 0; i < deck.size() - 1; i++) { + q.push_back(deck[i]); + q.push_back(q.front()); + q.pop_front(); + } + q.push_back(deck[deck.size() - 1]); - while (!q.empty()) { - res.push_back(q.back()); - q.pop_back(); + while (!q.empty()) { + res.push_back(q.back()); + q.pop_back(); + } + return res; } - return res; - } }; diff --git a/Problems/0953.cpp b/Problems/0953.cpp @@ -1,10 +1,11 @@ class Solution { -public: - bool isAlienSorted(vector<string> &words, string order) { - vector<char> um(26); - for (int i = 0; i < order.size(); i++) um[order[i] - 'a'] = 'a' + i; - for (string &word : words) - for_each(word.begin(), word.end(), [&um](char &c) { c = um[c - 'a']; }); - return is_sorted(words.begin(), words.end()); - } + public: + bool isAlienSorted(vector<string> &words, string order) { + vector<char> um(26); + for (int i = 0; i < order.size(); i++) + um[order[i] - 'a'] = 'a' + i; + for (string &word : words) + for_each(word.begin(), word.end(), [&um](char &c) { c = um[c - 'a']; }); + return is_sorted(words.begin(), words.end()); + } }; diff --git a/Problems/0956.cpp b/Problems/0956.cpp @@ -1,18 +1,18 @@ class Solution { -public: - int tallestBillboard(const vector<int> &rods) { - int sum = accumulate(rods.begin(), rods.end(), 0); - vector<int> dp(sum + 1, -1); - dp[0] = 0; + public: + int tallestBillboard(const vector<int> &rods) { + int sum = accumulate(rods.begin(), rods.end(), 0); + vector<int> dp(sum + 1, -1); + dp[0] = 0; - for (int rod : rods) { - vector<int> dpc = dp; - for (int i = 0; i <= sum - rod; i++) { - if (dpc[i] < 0) continue; - dp[i + rod] = max(dp[i + rod], dpc[i]); - dp[abs(i - rod)] = max(dp[abs(i - rod)], dpc[i] + min(i, rod)); - } + for (int rod : rods) { + vector<int> dpc = dp; + for (int i = 0; i <= sum - rod; i++) { + if (dpc[i] < 0) continue; + dp[i + rod] = max(dp[i + rod], dpc[i]); + dp[abs(i - rod)] = max(dp[abs(i - rod)], dpc[i] + min(i, rod)); + } + } + return dp[0]; } - return dp[0]; - } }; diff --git a/Problems/0958.cpp b/Problems/0958.cpp @@ -1,20 +1,20 @@ class Solution { -public: - bool isCompleteTree(TreeNode *root) { - queue<TreeNode *> q; - int had_empty = 0; - q.push(root); - while (!q.empty()) { - TreeNode *root = q.front(); - q.pop(); - if (!root) { - had_empty = 1; - continue; - } - if (had_empty) return false; - q.push(root->left); - q.push(root->right); + public: + bool isCompleteTree(TreeNode *root) { + queue<TreeNode *> q; + int had_empty = 0; + q.push(root); + while (!q.empty()) { + TreeNode *root = q.front(); + q.pop(); + if (!root) { + had_empty = 1; + continue; + } + if (had_empty) return false; + q.push(root->left); + q.push(root->right); + } + return true; } - return true; - } }; diff --git a/Problems/0959.cpp b/Problems/0959.cpp @@ -1,81 +1,76 @@ class UnionFind { - vector<int> root, rank; - int n; + vector<int> root, rank; + int n; -public: - UnionFind(int n) : n(n), root(n), rank(n, 1) { - iota(root.begin(), root.end(), 0); - } + public: + UnionFind(int n) : n(n), root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } - void join(int x, int y) { - x = find(x), y = find(y); + void join(int x, int y) { + x = find(x), y = find(y); - if (x != y) { - if (rank[x] > rank[y]) swap(x, y); + if (x != y) { + if (rank[x] > rank[y]) swap(x, y); - root[x] = y; - rank[y] += rank[x]; + root[x] = y; + rank[y] += rank[x]; + } } - } - int count() { - int cnt = 0; - for (int i = 0; i < n; i++) cnt += root[i] == i; - return cnt; - } + int count() { + int cnt = 0; + for (int i = 0; i < n; i++) + cnt += root[i] == i; + return cnt; + } - void set_invalid(int x) { root[x] = -1; } + void set_invalid(int x) { root[x] = -1; } }; class Solution { - int n; + int n; - int get_base_index(int x, int y) { return (n * x + y) * 2; } + int get_base_index(int x, int y) { return (n * x + y) * 2; } - bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < n; } + bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < n; } - int get_start_offset(char c, int k) { - if (c == '/') - return (k % 2 == 0) ? 1 : 0; - else - return (k == 0 || k == 3) ? 1 : 0; - } + int get_start_offset(char c, int k) { + if (c == '/') + return (k % 2 == 0) ? 1 : 0; + else + return (k == 0 || k == 3) ? 1 : 0; + } - int get_index(char c, int k, int x, int y, bool dest) { - int offset = get_start_offset(c, k); - if (dest) offset = !offset; - return get_base_index(x, y) + (c != ' ') * offset; - } + int get_index(char c, int k, int x, int y, bool dest) { + int offset = get_start_offset(c, k); + if (dest) offset = !offset; + return get_base_index(x, y) + (c != ' ') * offset; + } -public: - int regionsBySlashes(vector<string> &grid) { - n = grid.size(); - UnionFind uf(2 * n * n); + public: + int regionsBySlashes(vector<string> &grid) { + n = grid.size(); + UnionFind uf(2 * n * n); - vector<pair<int, int>> offset = { - { 0, 1}, - { 0, -1}, - { 1, 0}, - {-1, 0} - }; - for (int x = 0; x < n; x++) { - for (int y = 0; y < n; y++) { - for (int k = 0; k < 4; k++) { - int nx = x + offset[k].first, ny = y + offset[k].second; - if (!valid(nx, ny)) continue; - int index = get_index(grid[x][y], k, x, y, 0); - int nindex = get_index(grid[nx][ny], k, nx, ny, 1); - uf.join(index, nindex); + vector<pair<int, int>> offset = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + for (int x = 0; x < n; x++) { + for (int y = 0; y < n; y++) { + for (int k = 0; k < 4; k++) { + int nx = x + offset[k].first, ny = y + offset[k].second; + if (!valid(nx, ny)) continue; + int index = get_index(grid[x][y], k, x, y, 0); + int nindex = get_index(grid[nx][ny], k, nx, ny, 1); + uf.join(index, nindex); + } + if (grid[x][y] == ' ') uf.set(get_base_index(x, y) + 1); + } } - if (grid[x][y] == ' ') uf.set(get_base_index(x, y) + 1); - } - } - return uf.count(); - } + return uf.count(); + } }; diff --git a/Problems/0965.cpp b/Problems/0965.cpp @@ -1,19 +1,19 @@ class Solution { -public: - bool isUnivalTree(TreeNode *root) { - if (!root) return true; - int val = root->val; - stack<TreeNode *> st; + public: + bool isUnivalTree(TreeNode *root) { + if (!root) return true; + int val = root->val; + stack<TreeNode *> st; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (root->val != val) return false; - if (root->left) st.push(root->left); - if (root->right) st.push(root->right); - } + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (root->val != val) return false; + if (root->left) st.push(root->left); + if (root->right) st.push(root->right); + } - return true; - } + return true; + } }; diff --git a/Problems/0973.cpp b/Problems/0973.cpp @@ -1,17 +1,18 @@ class Solution { - typedef pair<double, int> pdi; + typedef pair<double, int> pdi; -public: - vector<vector<int>> kClosest(vector<vector<int>> &points, int k) { - auto cmp = [](const pdi &a, const pdi &b) { return a.first < b.first; }; - priority_queue<pdi, vector<pdi>, decltype(cmp)> pq(cmp); - for (int i = 0; i < points.size(); i++) { - pq.push({sqrt(pow(points[i][0], 2) + pow(points[i][1], 2)), i}); - if (pq.size() > k) pq.pop(); - } + public: + vector<vector<int>> kClosest(vector<vector<int>> &points, int k) { + auto cmp = [](const pdi &a, const pdi &b) { return a.first < b.first; }; + priority_queue<pdi, vector<pdi>, decltype(cmp)> pq(cmp); + for (int i = 0; i < points.size(); i++) { + pq.push({sqrt(pow(points[i][0], 2) + pow(points[i][1], 2)), i}); + if (pq.size() > k) pq.pop(); + } - vector<vector<int>> res(k); - while (k--) res[k] = points[pq.top().second], pq.pop(); - return res; - } + vector<vector<int>> res(k); + while (k--) + res[k] = points[pq.top().second], pq.pop(); + return res; + } }; diff --git a/Problems/0974.cpp b/Problems/0974.cpp @@ -1,16 +1,16 @@ class Solution { -public: - int subarraysDivByK(vector<int> &nums, int k) { - int n = nums.size(), sum = 0, res = 0; - vector<int> dp(k, 0); + public: + int subarraysDivByK(vector<int> &nums, int k) { + int n = nums.size(), sum = 0, res = 0; + vector<int> dp(k, 0); - dp[0] = 1; - for (int num : nums) { - sum += num; - int rem = sum % k; - if (rem < 0) rem += k; - res += dp[rem]++; + dp[0] = 1; + for (int num : nums) { + sum += num; + int rem = sum % k; + if (rem < 0) rem += k; + res += dp[rem]++; + } + return res; } - return res; - } }; diff --git a/Problems/0977.cpp b/Problems/0977.cpp @@ -1,35 +1,36 @@ // Intuitive solution class Solution { -public: - vector<int> sortedSquares(vector<int> &nums) { - vector<int> res; - int i = 0, j = nums.size() - 1; - while (i <= j) { - int n1 = nums[i] * nums[i]; - int n2 = nums[j] * nums[j]; - if (n1 > n2) { - res.push_back(n1); - i++; - } else { - res.push_back(n2); - j--; - } + public: + vector<int> sortedSquares(vector<int> &nums) { + vector<int> res; + int i = 0, j = nums.size() - 1; + while (i <= j) { + int n1 = nums[i] * nums[i]; + int n2 = nums[j] * nums[j]; + if (n1 > n2) { + res.push_back(n1); + i++; + } else { + res.push_back(n2); + j--; + } + } + reverse(res.begin(), res.end()); + return res; } - reverse(res.begin(), res.end()); - return res; - } }; // Intuitive solution, better execution // avoids recomputation of squares // avoids reversal of the array class Solution { -public: - vector<int> sortedSquares(vector<int> &nums) { - int n = nums.size(), i = 0, j = nums.size() - 1; - vector<int> res(n); - for_each(nums.begin(), nums.end(), [](int &a) { a *= a; }); - while (i <= j) res[--n] = nums[i] > nums[j] ? nums[i++] : nums[j--]; - return res; - } + public: + vector<int> sortedSquares(vector<int> &nums) { + int n = nums.size(), i = 0, j = nums.size() - 1; + vector<int> res(n); + for_each(nums.begin(), nums.end(), [](int &a) { a *= a; }); + while (i <= j) + res[--n] = nums[i] > nums[j] ? nums[i++] : nums[j--]; + return res; + } }; diff --git a/Problems/0980.cpp b/Problems/0980.cpp @@ -1,56 +1,51 @@ class Solution { - vector<pair<int, int>> offset = { - { 0, 1}, - { 0, -1}, - { 1, 0}, - {-1, 0} - }; - int m, n; - - bool valid(int x, int y) { return x >= 0 && x < m && y >= 0 && y < n; } - - int find(vector<vector<int>> &grid, int x, int y, int obs) { - stack<pair<int, int>> st; - st.push({x, y}); - - int count = 0, goal = m * n - obs - 1, crnt = 0; - while (!st.empty()) { - auto p = st.top(); - - if (grid[p.first][p.second] == 3) { - st.pop(); - grid[p.first][p.second] = 0; - crnt--; - continue; - } - - grid[p.first][p.second] = 3; - crnt++; - for (auto &o : offset) { - int x = p.first + o.first; - int y = p.second + o.second; - if (!valid(x, y) || grid[x][y] == 3 || grid[x][y] == -1) continue; - if (grid[x][y] == 2) - count += crnt == goal; - else - st.push({x, y}); - } + vector<pair<int, int>> offset = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int m, n; + + bool valid(int x, int y) { return x >= 0 && x < m && y >= 0 && y < n; } + + int find(vector<vector<int>> &grid, int x, int y, int obs) { + stack<pair<int, int>> st; + st.push({x, y}); + + int count = 0, goal = m * n - obs - 1, crnt = 0; + while (!st.empty()) { + auto p = st.top(); + + if (grid[p.first][p.second] == 3) { + st.pop(); + grid[p.first][p.second] = 0; + crnt--; + continue; + } + + grid[p.first][p.second] = 3; + crnt++; + for (auto &o : offset) { + int x = p.first + o.first; + int y = p.second + o.second; + if (!valid(x, y) || grid[x][y] == 3 || grid[x][y] == -1) continue; + if (grid[x][y] == 2) + count += crnt == goal; + else + st.push({x, y}); + } + } + return count; + } + + public: + int uniquePathsIII(vector<vector<int>> &grid) { + m = grid.size(), n = grid[0].size(); + + int x, y, count = 0; + for (int i = 0; i < m; i++) + for (int j = 0; j < n; j++) + if (grid[i][j] == 1) + x = i, y = j; + else if (grid[i][j] == -1) + count++; + + return find(grid, x, y, count); } - return count; - } - -public: - int uniquePathsIII(vector<vector<int>> &grid) { - m = grid.size(), n = grid[0].size(); - - int x, y, count = 0; - for (int i = 0; i < m; i++) - for (int j = 0; j < n; j++) - if (grid[i][j] == 1) - x = i, y = j; - else if (grid[i][j] == -1) - count++; - - return find(grid, x, y, count); - } }; diff --git a/Problems/0983.cpp b/Problems/0983.cpp @@ -1,19 +1,20 @@ class Solution { - vector<int> pass = {1, 7, 30}; - unordered_map<int, int> dp; + vector<int> pass = {1, 7, 30}; + unordered_map<int, int> dp; -public: - int mincostTickets(vector<int> &days, vector<int> &costs, int start = 0) { - if (start >= days.size()) return 0; - if (dp.count(start)) return dp[start]; + public: + int mincostTickets(vector<int> &days, vector<int> &costs, int start = 0) { + if (start >= days.size()) return 0; + if (dp.count(start)) return dp[start]; - int res = INT_MAX; - for (int k = 0, j = 0; k < pass.size(); k++) { - while (j < days.size() && days[j] - days[start] < pass[k]) j++; - res = min(res, costs[k] + mincostTickets(days, costs, j)); - } + int res = INT_MAX; + for (int k = 0, j = 0; k < pass.size(); k++) { + while (j < days.size() && days[j] - days[start] < pass[k]) + j++; + res = min(res, costs[k] + mincostTickets(days, costs, j)); + } - dp[start] = res; - return res; - } + dp[start] = res; + return res; + } }; diff --git a/Problems/0986.cpp b/Problems/0986.cpp @@ -1,25 +1,25 @@ class Solution { -public: - vector<vector<int>> intervalIntersection(vector<vector<int>> &firstList, - vector<vector<int>> &secondList) { - vector<vector<int>> res; + public: + vector<vector<int>> intervalIntersection(vector<vector<int>> &firstList, + vector<vector<int>> &secondList) { + vector<vector<int>> res; - int n = firstList.size(), m = secondList.size(), i = 0, j = 0; - while (i < n && j < m) { - const vector<int> &a = firstList[i], b = secondList[j]; - if (a[1] < b[0]) - i++; - else if (a[0] > b[1]) - j++; - else { - res.push_back({max(a[0], b[0]), min(a[1], b[1])}); - if (a[1] < b[1]) - i++; - else - j++; - } - } + int n = firstList.size(), m = secondList.size(), i = 0, j = 0; + while (i < n && j < m) { + const vector<int> &a = firstList[i], b = secondList[j]; + if (a[1] < b[0]) + i++; + else if (a[0] > b[1]) + j++; + else { + res.push_back({max(a[0], b[0]), min(a[1], b[1])}); + if (a[1] < b[1]) + i++; + else + j++; + } + } - return res; - } + return res; + } }; diff --git a/Problems/0989.cpp b/Problems/0989.cpp @@ -1,15 +1,15 @@ class Solution { -public: - vector<int> addToArrayForm(vector<int> &num, int k) { - vector<int> res; + public: + vector<int> addToArrayForm(vector<int> &num, int k) { + vector<int> res; - for (int i = num.size() - 1; i >= 0 || k; i--) { - if (i >= 0) k += num[i]; - res.push_back(k % 10); - k /= 10; - } + for (int i = num.size() - 1; i >= 0 || k; i--) { + if (i >= 0) k += num[i]; + res.push_back(k % 10); + k /= 10; + } - reverse(res.begin(), res.end()); - return res; - } + reverse(res.begin(), res.end()); + return res; + } }; diff --git a/Problems/0990.cpp b/Problems/0990.cpp @@ -1,35 +1,34 @@ class UnionFind { - vector<int> root, rank; + vector<int> root, rank; -public: - UnionFind(int n) : root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } + public: + UnionFind(int n) : root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } - int find(int x) { - if (x == root[x]) return x; - return root[x] = find(root[x]); - } + int find(int x) { + if (x == root[x]) return x; + return root[x] = find(root[x]); + } - void join(int x, int y) { - x = find(x), y = find(y); + void join(int x, int y) { + x = find(x), y = find(y); - if (x != y) { - if (rank[x] > rank[y]) swap(x, y); - root[y] = x; - rank[x] += x == y; + if (x != y) { + if (rank[x] > rank[y]) swap(x, y); + root[y] = x; + rank[x] += x == y; + } } - } }; class Solution { -public: - bool equationsPossible(vector<string> &equations) { - UnionFind uf(26); - for (auto &s : equations) - if (s[1] == '=') uf.join(s[0] - 'a', s[3] - 'a'); + public: + bool equationsPossible(vector<string> &equations) { + UnionFind uf(26); + for (auto &s : equations) + if (s[1] == '=') uf.join(s[0] - 'a', s[3] - 'a'); - for (auto &s : equations) - if (s[1] == '!' && uf.find(s[0] - 'a') == uf.find(s[3] - 'a')) - return false; - return true; - } + for (auto &s : equations) + if (s[1] == '!' && uf.find(s[0] - 'a') == uf.find(s[3] - 'a')) return false; + return true; + } }; diff --git a/Problems/0993.cpp b/Problems/0993.cpp @@ -1,31 +1,31 @@ class Solution { -public: - bool isCousins(TreeNode *root, int x, int y) { - if (!root) return {}; + public: + bool isCousins(TreeNode *root, int x, int y) { + if (!root) return {}; - bool fx = false, fy = false; - queue<TreeNode *> q; - q.push(root); - for (int lvl = 0; !q.empty(); lvl++) { - for (int t = q.size(); t > 0; t--) { - TreeNode *root = q.front(); - q.pop(); - if (root->left && root->right) - if ((root->left->val == x && root->right->val == y) || - (root->left->val == y && root->right->val == x)) - return false; + bool fx = false, fy = false; + queue<TreeNode *> q; + q.push(root); + for (int lvl = 0; !q.empty(); lvl++) { + for (int t = q.size(); t > 0; t--) { + TreeNode *root = q.front(); + q.pop(); + if (root->left && root->right) + if ((root->left->val == x && root->right->val == y) || + (root->left->val == y && root->right->val == x)) + return false; - if (root->val == x) fx = true; - if (root->val == y) fy = true; + if (root->val == x) fx = true; + if (root->val == y) fy = true; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } - if (fx && fy) return true; + if (fx && fy) return true; - if (fx || fy) return false; + if (fx || fy) return false; + } + return false; } - return false; - } }; diff --git a/Problems/0994.cpp b/Problems/0994.cpp @@ -1 +1 @@ -Formating: Problems/0994.cpp +Formating : Problems / 0994.cpp diff --git a/Problems/0997.cpp b/Problems/0997.cpp @@ -1,19 +1,19 @@ class Solution { -public: - int findJudge(int n, vector<vector<int>> &trust) { - if (n == 1 && trust.empty()) return 1; + public: + int findJudge(int n, vector<vector<int>> &trust) { + if (n == 1 && trust.empty()) return 1; - vector<int> trusted(n + 1, 0); - unordered_set<int> trusting; + vector<int> trusted(n + 1, 0); + unordered_set<int> trusting; - for (auto &p : trust) { - trusting.insert(p[0]); - trusted[p[1]]++; - } + for (auto &p : trust) { + trusting.insert(p[0]); + trusted[p[1]]++; + } - for (int i = 1; i <= n; i++) - if (trusted[i] == n - 1 && !trusting.count(i)) return i; + for (int i = 1; i <= n; i++) + if (trusted[i] == n - 1 && !trusting.count(i)) return i; - return -1; - } + return -1; + } }; diff --git a/Problems/1008.cpp b/Problems/1008.cpp @@ -1,20 +1,21 @@ class Solution { -public: - TreeNode *bstFromPreorder(vector<int> &preorder) { - int index = 0; - TreeNode *root = new TreeNode(preorder[index++]); - stack<TreeNode *> st; - st.push(root); - while (index < preorder.size()) { - int val = preorder[index++]; - if (val < st.top()->val) { - st.push(st.top()->left = new TreeNode(val)); - } else { - TreeNode *crnt = nullptr; - while (!st.empty() && val > st.top()->val) crnt = st.top(), st.pop(); - st.push(crnt->right = new TreeNode(val)); - } + public: + TreeNode *bstFromPreorder(vector<int> &preorder) { + int index = 0; + TreeNode *root = new TreeNode(preorder[index++]); + stack<TreeNode *> st; + st.push(root); + while (index < preorder.size()) { + int val = preorder[index++]; + if (val < st.top()->val) { + st.push(st.top()->left = new TreeNode(val)); + } else { + TreeNode *crnt = nullptr; + while (!st.empty() && val > st.top()->val) + crnt = st.top(), st.pop(); + st.push(crnt->right = new TreeNode(val)); + } + } + return root; } - return root; - } }; diff --git a/Problems/1011.cpp b/Problems/1011.cpp @@ -1,17 +1,18 @@ class Solution { -public: - int shipWithinDays(vector<int> &weights, int days) { - int left = 0, right = 25000000; - for (int w : weights) left = max(left, w); - while (left < right) { - int mid = (left + right) / 2, need = 1, cur = 0; - for (int i = 0; i < weights.size() && need <= days; cur += weights[i++]) - if (cur + weights[i] > mid) cur = 0, need++; - if (need > days) - left = mid + 1; - else - right = mid; + public: + int shipWithinDays(vector<int> &weights, int days) { + int left = 0, right = 25000000; + for (int w : weights) + left = max(left, w); + while (left < right) { + int mid = (left + right) / 2, need = 1, cur = 0; + for (int i = 0; i < weights.size() && need <= days; cur += weights[i++]) + if (cur + weights[i] > mid) cur = 0, need++; + if (need > days) + left = mid + 1; + else + right = mid; + } + return left; } - return left; - } }; diff --git a/Problems/1014.cpp b/Problems/1014.cpp @@ -1 +1 @@ -Formating: Problems/1014.cpp +Formating : Problems / 1014.cpp diff --git a/Problems/1019.cpp b/Problems/1019.cpp @@ -1,20 +1,20 @@ class Solution { -public: - vector<int> nextLargerNodes(ListNode *head) { - if (!head) return {}; + public: + vector<int> nextLargerNodes(ListNode *head) { + if (!head) return {}; - int len = 0, i = 0; - vector<int> res; - stack<pair<int, int>> st; + int len = 0, i = 0; + vector<int> res; + stack<pair<int, int>> st; - for (ListNode *p = head; p; p = p->next, i++) { - res.push_back(0); - while (!st.empty() && p->val > st.top().first) { - res[st.top().second] = p->val; - st.pop(); - } - st.push({p->val, i}); + for (ListNode *p = head; p; p = p->next, i++) { + res.push_back(0); + while (!st.empty() && p->val > st.top().first) { + res[st.top().second] = p->val; + st.pop(); + } + st.push({p->val, i}); + } + return res; } - return res; - } }; diff --git a/Problems/1020.cpp b/Problems/1020.cpp @@ -1,37 +1,37 @@ class Solution { - int n, m; - bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } + int n, m; + bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } - int flood_fill(vector<vector<int>> &grid, int x, int y) { - grid[x][y] = 0; - int count = 1; - if (valid(x + 1, y) && grid[x + 1][y]) count += flood_fill(grid, x + 1, y); - if (valid(x - 1, y) && grid[x - 1][y]) count += flood_fill(grid, x - 1, y); - if (valid(x, y + 1) && grid[x][y + 1]) count += flood_fill(grid, x, y + 1); - if (valid(x, y - 1) && grid[x][y - 1]) count += flood_fill(grid, x, y - 1); - return count; - } - -public: - int numEnclaves(vector<vector<int>> &grid) { - n = grid.size(), m = grid[0].size(); - for (int i = 0; i < n; i++) { - if (grid[i][0]) flood_fill(grid, i, 0); - if (grid[i][m - 1]) flood_fill(grid, i, m - 1); - } - for (int i = 0; i < m; i++) { - if (grid[0][i]) flood_fill(grid, 0, i); - if (grid[n - 1][i]) flood_fill(grid, n - 1, i); + int flood_fill(vector<vector<int>> &grid, int x, int y) { + grid[x][y] = 0; + int count = 1; + if (valid(x + 1, y) && grid[x + 1][y]) count += flood_fill(grid, x + 1, y); + if (valid(x - 1, y) && grid[x - 1][y]) count += flood_fill(grid, x - 1, y); + if (valid(x, y + 1) && grid[x][y + 1]) count += flood_fill(grid, x, y + 1); + if (valid(x, y - 1) && grid[x][y - 1]) count += flood_fill(grid, x, y - 1); + return count; } - int res = 0; - for (int i = 1; i < n - 1; i++) { - for (int j = 1; j < m - 1; j++) { - if (!grid[i][j]) continue; - res += flood_fill(grid, i, j); - } - } + public: + int numEnclaves(vector<vector<int>> &grid) { + n = grid.size(), m = grid[0].size(); + for (int i = 0; i < n; i++) { + if (grid[i][0]) flood_fill(grid, i, 0); + if (grid[i][m - 1]) flood_fill(grid, i, m - 1); + } + for (int i = 0; i < m; i++) { + if (grid[0][i]) flood_fill(grid, 0, i); + if (grid[n - 1][i]) flood_fill(grid, n - 1, i); + } - return res; - } + int res = 0; + for (int i = 1; i < n - 1; i++) { + for (int j = 1; j < m - 1; j++) { + if (!grid[i][j]) continue; + res += flood_fill(grid, i, j); + } + } + + return res; + } }; diff --git a/Problems/1022.cpp b/Problems/1022.cpp @@ -1,22 +1,22 @@ class Solution { -public: - int sumRootToLeaf(TreeNode *root) { - if (!root) return 0; - stack<pair<TreeNode *, int>> st; - int sum = 0; + public: + int sumRootToLeaf(TreeNode *root) { + if (!root) return 0; + stack<pair<TreeNode *, int>> st; + int sum = 0; - st.push({root, 0}); - while (!st.empty()) { - TreeNode *root = st.top().first; - int val = (st.top().second << 1) | root->val; - st.pop(); - if (!root->left && !root->right) { - sum += val; - continue; - } - if (root->left) st.push({root->left, val}); - if (root->right) st.push({root->right, val}); + st.push({root, 0}); + while (!st.empty()) { + TreeNode *root = st.top().first; + int val = (st.top().second << 1) | root->val; + st.pop(); + if (!root->left && !root->right) { + sum += val; + continue; + } + if (root->left) st.push({root->left, val}); + if (root->right) st.push({root->right, val}); + } + return sum; } - return sum; - } }; diff --git a/Problems/1026.cpp b/Problems/1026.cpp @@ -1,30 +1,21 @@ class Solution { -public: - int maxAncestorDiff(TreeNode *root) { - if (!root) return 0; - int res = 0; - stack<pair<TreeNode *, pair<int, int>>> st; - st.push({ - root, {root->val, root->val} - }); - while (!st.empty()) { - TreeNode *root = st.top().first; - int maxi = st.top().second.first; - int mini = st.top().second.second; - st.pop(); - res = max(res, abs(maxi - root->val)); - res = max(res, abs(mini - root->val)); - if (root->left) - st.push({ - root->left, - {max(maxi, root->left->val), min(mini, root->left->val)} - }); - if (root->right) - st.push({ - root->right, - {max(maxi, root->right->val), min(mini, root->right->val)} - }); + public: + int maxAncestorDiff(TreeNode *root) { + if (!root) return 0; + int res = 0; + stack<pair<TreeNode *, pair<int, int>>> st; + st.push({root, {root->val, root->val}}); + while (!st.empty()) { + TreeNode *root = st.top().first; + int maxi = st.top().second.first; + int mini = st.top().second.second; + st.pop(); + res = max(res, abs(maxi - root->val)); + res = max(res, abs(mini - root->val)); + if (root->left) st.push({root->left, {max(maxi, root->left->val), min(mini, root->left->val)}}); + if (root->right) + st.push({root->right, {max(maxi, root->right->val), min(mini, root->right->val)}}); + } + return res; } - return res; - } }; diff --git a/Problems/1027.cpp b/Problems/1027.cpp @@ -1,28 +1,29 @@ class Solution { -public: - int longestArithSeqLength(vector<int> &nums) { - unordered_map<int, vector<int>> um; - int res = 2; + public: + int longestArithSeqLength(vector<int> &nums) { + unordered_map<int, vector<int>> um; + int res = 2; - for (int i = 0; i < nums.size(); i++) um[nums[i]].push_back(i); - for (const auto &[num1, vec1] : um) { - res = max(res, (int)vec1.size()); - for (const auto &[num2, vec2] : um) { - if (num1 == num2) continue; + for (int i = 0; i < nums.size(); i++) + um[nums[i]].push_back(i); + for (const auto &[num1, vec1] : um) { + res = max(res, (int)vec1.size()); + for (const auto &[num2, vec2] : um) { + if (num1 == num2) continue; - auto it = lower_bound(vec2.begin(), vec2.end(), vec1.front() + 1); - if (it == vec2.end()) continue; + auto it = lower_bound(vec2.begin(), vec2.end(), vec1.front() + 1); + if (it == vec2.end()) continue; - int diff = num2 - num1, crnt = *it, count = 2, next; - while (true) { - if (!um.count(next = nums[crnt] + diff)) break; - auto it = lower_bound(um[next].begin(), um[next].end(), crnt + 1); - if (it == um[next].end()) break; - crnt = *it, count++; + int diff = num2 - num1, crnt = *it, count = 2, next; + while (true) { + if (!um.count(next = nums[crnt] + diff)) break; + auto it = lower_bound(um[next].begin(), um[next].end(), crnt + 1); + if (it == um[next].end()) break; + crnt = *it, count++; + } + res = max(res, count); + } } - res = max(res, count); - } + return res; } - return res; - } }; diff --git a/Problems/1035.cpp b/Problems/1035.cpp @@ -1,22 +1,20 @@ class Solution { - int dp[500][500]; + int dp[500][500]; -public: - Solution() { memset(dp, 0xFF, sizeof(dp)); } + public: + Solution() { memset(dp, 0xFF, sizeof(dp)); } - int maxUncrossedLines(const vector<int> &nums1, const vector<int> &nums2, - int i = 0, int j = 0) { - if (i >= nums1.size() || j >= nums2.size()) return 0; - if (dp[i][j] != -1) return dp[i][j]; + int maxUncrossedLines(const vector<int> &nums1, const vector<int> &nums2, int i = 0, int j = 0) { + if (i >= nums1.size() || j >= nums2.size()) return 0; + if (dp[i][j] != -1) return dp[i][j]; - int res; - if (nums1[i] == nums2[j]) - res = 1 + maxUncrossedLines(nums1, nums2, i + 1, j + 1); - else { - res = max(maxUncrossedLines(nums1, nums2, i + 1, j), - maxUncrossedLines(nums1, nums2, i, j + 1)); - } + int res; + if (nums1[i] == nums2[j]) + res = 1 + maxUncrossedLines(nums1, nums2, i + 1, j + 1); + else { + res = max(maxUncrossedLines(nums1, nums2, i + 1, j), maxUncrossedLines(nums1, nums2, i, j + 1)); + } - return dp[i][j] = res; - } + return dp[i][j] = res; + } }; diff --git a/Problems/1038.cpp b/Problems/1038.cpp @@ -1,19 +1,19 @@ class Solution { -public: - TreeNode *bstToGst(TreeNode *root) { - TreeNode *head = root; - stack<TreeNode *> st; - int sum = 0; - while (true) { - while (root) { - st.push(root); - root = root->right; - } - if (st.empty()) break; - root = st.top(), st.pop(); - sum = root->val += sum; - root = root->left; + public: + TreeNode *bstToGst(TreeNode *root) { + TreeNode *head = root; + stack<TreeNode *> st; + int sum = 0; + while (true) { + while (root) { + st.push(root); + root = root->right; + } + if (st.empty()) break; + root = st.top(), st.pop(); + sum = root->val += sum; + root = root->left; + } + return head; } - return head; - } }; diff --git a/Problems/1042.cpp b/Problems/1042.cpp @@ -1,24 +1,25 @@ class Solution { -public: - vector<int> gardenNoAdj(int n, vector<vector<int>> &paths) { - vector<vector<int>> adj(n); - for (auto &p : paths) { - adj[p[0] - 1].push_back(p[1] - 1); - adj[p[1] - 1].push_back(p[0] - 1); - } + public: + vector<int> gardenNoAdj(int n, vector<vector<int>> &paths) { + vector<vector<int>> adj(n); + for (auto &p : paths) { + adj[p[0] - 1].push_back(p[1] - 1); + adj[p[1] - 1].push_back(p[0] - 1); + } - vector<int> res(n); - for (int i = 0; i < n; i++) { - bitset<5> colors; + vector<int> res(n); + for (int i = 0; i < n; i++) { + bitset<5> colors; - for (int c : adj[i]) colors.set(res[c]); + for (int c : adj[i]) + colors.set(res[c]); - for (int j = 1; j < 5; j++) { - if (colors[j]) continue; - res[i] = j; - break; - } + for (int j = 1; j < 5; j++) { + if (colors[j]) continue; + res[i] = j; + break; + } + } + return res; } - return res; - } }; diff --git a/Problems/1046.cpp b/Problems/1046.cpp @@ -1,19 +1,19 @@ class Solution { -public: - int lastStoneWeight(vector<int> &stones) { - int n = stones.size(); - make_heap(stones.begin(), stones.end()); - while (stones.size() > 1) { - int x, y; - pop_heap(stones.begin(), stones.end()); - y = stones.back(), stones.pop_back(); - pop_heap(stones.begin(), stones.end()); - x = stones.back(), stones.pop_back(); - if (x != y) { - stones.push_back(y - x); - push_heap(stones.begin(), stones.end()); - } + public: + int lastStoneWeight(vector<int> &stones) { + int n = stones.size(); + make_heap(stones.begin(), stones.end()); + while (stones.size() > 1) { + int x, y; + pop_heap(stones.begin(), stones.end()); + y = stones.back(), stones.pop_back(); + pop_heap(stones.begin(), stones.end()); + x = stones.back(), stones.pop_back(); + if (x != y) { + stones.push_back(y - x); + push_heap(stones.begin(), stones.end()); + } + } + return !stones.empty() ? stones.back() : 0; } - return !stones.empty() ? stones.back() : 0; - } }; diff --git a/Problems/1047.cpp b/Problems/1047.cpp @@ -1,19 +1,19 @@ class Solution { -public: - string removeDuplicates(string s) { - stack<char> st; - for (char c : s) - if (st.empty() || c != st.top()) - st.push(c); - else - st.pop(); + public: + string removeDuplicates(string s) { + stack<char> st; + for (char c : s) + if (st.empty() || c != st.top()) + st.push(c); + else + st.pop(); - string res = ""; - while (!st.empty()) { - res += st.top(); - st.pop(); + string res = ""; + while (!st.empty()) { + res += st.top(); + st.pop(); + } + reverse(res.begin(), res.end()); + return res; } - reverse(res.begin(), res.end()); - return res; - } }; diff --git a/Problems/1051.cpp b/Problems/1051.cpp @@ -1,13 +1,13 @@ class Solution { -public: - int heightChecker(vector<int> &heights) { - int count = 0; - vector<int> exp = heights; - sort(exp.begin(), exp.end()); + public: + int heightChecker(vector<int> &heights) { + int count = 0; + vector<int> exp = heights; + sort(exp.begin(), exp.end()); - for (int i = 0; i < heights.size(); i++) - if (heights[i] != exp[i]) count++; + for (int i = 0; i < heights.size(); i++) + if (heights[i] != exp[i]) count++; - return count; - } + return count; + } }; diff --git a/Problems/1061.cpp b/Problems/1061.cpp @@ -1,32 +1,35 @@ class UnionFind { - int n, cnt = n; - vector<int> root; + int n, cnt = n; + vector<int> root; -public: - UnionFind(int n) : n(n), root(n) { iota(root.begin(), root.end(), 0); } + public: + UnionFind(int n) : n(n), root(n) { iota(root.begin(), root.end(), 0); } - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (y > x) swap(x, y); - root[x] = y; + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (y > x) swap(x, y); + root[x] = y; + } } - } }; class Solution { -public: - string smallestEquivalentString(string s1, string s2, string baseStr) { - UnionFind uf(126); + public: + string smallestEquivalentString(string s1, string s2, string baseStr) { + UnionFind uf(126); - for (int i = 0; i < s1.size(); i++) uf.join(s1[i], s2[i]); + for (int i = 0; i < s1.size(); i++) + uf.join(s1[i], s2[i]); - for (char &c : baseStr) c = uf.find(c); - return baseStr; - } + for (char &c : baseStr) + c = uf.find(c); + return baseStr; + } }; diff --git a/Problems/1071.cpp b/Problems/1071.cpp @@ -1,7 +1,7 @@ class Solution { -public: + public: string gcdOfStrings(string str1, string str2) { - if(str1 + str2 != str2 + str1) return ""; - return str1.substr(0, gcd(str1.size() ,str2.size())); + if (str1 + str2 != str2 + str1) return ""; + return str1.substr(0, gcd(str1.size(), str2.size())); } }; diff --git a/Problems/1079.cpp b/Problems/1079.cpp @@ -1,25 +1,25 @@ class Solution { - unordered_set<string> us; - bool used[8] = {false}; - string crnt; + unordered_set<string> us; + bool used[8] = {false}; + string crnt; - void rec(const string &tiles) { - us.insert(crnt); - if (crnt.size() == tiles.size()) return; + void rec(const string &tiles) { + us.insert(crnt); + if (crnt.size() == tiles.size()) return; - for (int i = 0; i < tiles.size(); i++) { - if (used[i]) continue; - used[i] = true; - crnt.push_back(tiles[i]); - rec(tiles); - crnt.pop_back(); - used[i] = false; + for (int i = 0; i < tiles.size(); i++) { + if (used[i]) continue; + used[i] = true; + crnt.push_back(tiles[i]); + rec(tiles); + crnt.pop_back(); + used[i] = false; + } } - } -public: - int numTilePossibilities(const string tiles) { - rec(tiles); - return us.size() - 1; - } + public: + int numTilePossibilities(const string tiles) { + rec(tiles); + return us.size() - 1; + } }; diff --git a/Problems/1089.cpp b/Problems/1089.cpp @@ -1,26 +1,26 @@ class Solution { -public: - void duplicateZeros(vector<int> &arr) { - int cnt = 0; - int len = arr.size() - 1; - for (int i = 0; i + cnt <= len; i++) - if (arr[i] == 0) { - if (i + cnt == len) { - arr[len] = 0; - len -= 1; - break; - } - cnt++; - } + public: + void duplicateZeros(vector<int> &arr) { + int cnt = 0; + int len = arr.size() - 1; + for (int i = 0; i + cnt <= len; i++) + if (arr[i] == 0) { + if (i + cnt == len) { + arr[len] = 0; + len -= 1; + break; + } + cnt++; + } - for (int i = len - cnt; i >= 0; i--) { - if (arr[i] == 0) { - arr[i + cnt] = 0; - cnt--; - arr[i + cnt] = 0; - } else { - arr[i + cnt] = arr[i]; - } + for (int i = len - cnt; i >= 0; i--) { + if (arr[i] == 0) { + arr[i + cnt] = 0; + cnt--; + arr[i + cnt] = 0; + } else { + arr[i + cnt] = arr[i]; + } + } } - } }; diff --git a/Problems/1091.cpp b/Problems/1091.cpp @@ -1,36 +1,28 @@ class Solution { - int n; + int n; - bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < n; } + bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < n; } -public: - int shortestPathBinaryMatrix(vector<vector<int>> &grid) { - if (grid[0][0] == 1 || grid.back().back() == 1) return -1; - n = grid.size(); + public: + int shortestPathBinaryMatrix(vector<vector<int>> &grid) { + if (grid[0][0] == 1 || grid.back().back() == 1) return -1; + n = grid.size(); - queue<pair<int, int>> q; - q.push({0, 0}); - vector<pair<int, int>> offsets = { - {-1, 0}, - {-1, 1}, - { 0, 1}, - { 1, 1}, - { 1, 0}, - { 1, -1}, - { 0, -1}, - {-1, -1} - }; - while (!q.empty()) { - auto [a, b] = q.front(); - q.pop(); - if (a == n - 1 && b == n - 1) return grid[a][b] + 1; - for (auto [ox, oy] : offsets) { - int x = a + ox, y = b + oy; - if (!valid(x, y) || grid[x][y] > 0) continue; - grid[x][y] = grid[a][b] + 1; - q.push({x, y}); - } + queue<pair<int, int>> q; + q.push({0, 0}); + vector<pair<int, int>> offsets = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, + {1, 0}, {1, -1}, {0, -1}, {-1, -1}}; + while (!q.empty()) { + auto [a, b] = q.front(); + q.pop(); + if (a == n - 1 && b == n - 1) return grid[a][b] + 1; + for (auto [ox, oy] : offsets) { + int x = a + ox, y = b + oy; + if (!valid(x, y) || grid[x][y] > 0) continue; + grid[x][y] = grid[a][b] + 1; + q.push({x, y}); + } + } + return -1; } - return -1; - } }; diff --git a/Problems/1095.cpp b/Problems/1095.cpp @@ -1,10 +1,10 @@ #include <cmath> class Solution { -public: - int findNumbers(vector<int> &nums) { - int res = 0; - for (int i : nums) - if (int(log10(i) + 1) % 2 == 0) res++; - return res; - } + public: + int findNumbers(vector<int> &nums) { + int res = 0; + for (int i : nums) + if (int(log10(i) + 1) % 2 == 0) res++; + return res; + } }; diff --git a/Problems/1099.cpp b/Problems/1099.cpp @@ -1,12 +1,12 @@ class Solution { -public: - vector<int> replaceElements(vector<int> &arr) { - int maxi = -1; - for (int i = arr.size() - 1; i >= 0; i--) { - int tmp = arr[i]; - arr[i] = maxi; - maxi = max(maxi, tmp); + public: + vector<int> replaceElements(vector<int> &arr) { + int maxi = -1; + for (int i = arr.size() - 1; i >= 0; i--) { + int tmp = arr[i]; + arr[i] = maxi; + maxi = max(maxi, tmp); + } + return arr; } - return arr; - } }; diff --git a/Problems/1104.cpp b/Problems/1104.cpp @@ -1,21 +1,21 @@ #define LOG2(X) ((unsigned)(8 * sizeof(int) - __builtin_clz((X)) - 1)) class Solution { - int flip(int label) { - int log = LOG2(label), floor = 1 << log, ceil = (1 << log + 1) - 1; - return floor + ceil - label; - } + int flip(int label) { + int log = LOG2(label), floor = 1 << log, ceil = (1 << log + 1) - 1; + return floor + ceil - label; + } -public: - vector<int> pathInZigZagTree(int label) { - bool rev = LOG2(label) % 2; - vector<int> res({label}); - if (rev) label = flip(label); - while ((label /= 2) > 0) { - rev = !rev; - res.push_back(!rev ? label : flip(label)); + public: + vector<int> pathInZigZagTree(int label) { + bool rev = LOG2(label) % 2; + vector<int> res({label}); + if (rev) label = flip(label); + while ((label /= 2) > 0) { + rev = !rev; + res.push_back(!rev ? label : flip(label)); + } + reverse(res.begin(), res.end()); + return res; } - reverse(res.begin(), res.end()); - return res; - } }; diff --git a/Problems/1111.cpp b/Problems/1111.cpp @@ -1,13 +1,13 @@ class Solution { -public: - vector<int> maxDepthAfterSplit(const string &seq) { - vector<int> res; - res.reserve(seq.size()); - for (int i = 0, count = 0; i < seq.size(); i++) { - if (seq[i] == '(') count++; - res.push_back(count % 2); - if (seq[i] == ')') count--; + public: + vector<int> maxDepthAfterSplit(const string &seq) { + vector<int> res; + res.reserve(seq.size()); + for (int i = 0, count = 0; i < seq.size(); i++) { + if (seq[i] == '(') count++; + res.push_back(count % 2); + if (seq[i] == ')') count--; + } + return res; } - return res; - } }; diff --git a/Problems/1125.cpp b/Problems/1125.cpp @@ -1,32 +1,32 @@ class Solution { -public: - vector<int> smallestSufficientTeam(vector<string> &req_skills, - vector<vector<string>> &people) { - int n = people.size(), m = req_skills.size(); - unordered_map<string, int> index; - for (int i = 0; i < m; i++) index[req_skills[i]] = i; - vector<int> masks(n); - for (int i = 0; i < n; i++) { - for (string skill : people[i]) masks[i] |= 1 << index[skill]; - } + public: + vector<int> smallestSufficientTeam(vector<string> &req_skills, vector<vector<string>> &people) { + int n = people.size(), m = req_skills.size(); + unordered_map<string, int> index; + for (int i = 0; i < m; i++) + index[req_skills[i]] = i; + vector<int> masks(n); + for (int i = 0; i < n; i++) { + for (string skill : people[i]) + masks[i] |= 1 << index[skill]; + } - vector<long long> dp(1 << m, (1LL << n) - 1); - dp[0] = 0; - for (int mask = 1; mask < (1 << m); mask++) { - for (int i = 0; i < n; i++) { - int smask = mask & ~masks[i]; - if (smask == mask) continue; - long long pmask = dp[smask] | (1LL << i); - if (__builtin_popcountll(pmask) < __builtin_popcountll(dp[mask])) - dp[mask] = pmask; - } - } + vector<long long> dp(1 << m, (1LL << n) - 1); + dp[0] = 0; + for (int mask = 1; mask < (1 << m); mask++) { + for (int i = 0; i < n; i++) { + int smask = mask & ~masks[i]; + if (smask == mask) continue; + long long pmask = dp[smask] | (1LL << i); + if (__builtin_popcountll(pmask) < __builtin_popcountll(dp[mask])) dp[mask] = pmask; + } + } - long long answerMask = dp[(1 << m) - 1]; - vector<int> res; - for (int i = 0; i < n; i++) { - if ((answerMask >> i) & 1) res.push_back(i); + long long answerMask = dp[(1 << m) - 1]; + vector<int> res; + for (int i = 0; i < n; i++) { + if ((answerMask >> i) & 1) res.push_back(i); + } + return res; } - return res; - } }; diff --git a/Problems/1129.cpp b/Problems/1129.cpp @@ -1,35 +1,37 @@ class Solution { - typedef vector<vector<int>> ADJ; + typedef vector<vector<int>> ADJ; -public: - vector<int> shortestAlternatingPaths(int n, vector<vector<int>> &redEdges, - vector<vector<int>> &blueEdges) { - vector<vector<int>> dist(2, vector<int>(n, INT_MAX)); - vector<ADJ> adj(2, ADJ(n)); - queue<pair<int, int>> q; + public: + vector<int> shortestAlternatingPaths(int n, vector<vector<int>> &redEdges, + vector<vector<int>> &blueEdges) { + vector<vector<int>> dist(2, vector<int>(n, INT_MAX)); + vector<ADJ> adj(2, ADJ(n)); + queue<pair<int, int>> q; - for (auto &e : redEdges) adj[0][e[0]].push_back(e[1]); - for (auto &e : blueEdges) adj[1][e[0]].push_back(e[1]); + for (auto &e : redEdges) + adj[0][e[0]].push_back(e[1]); + for (auto &e : blueEdges) + adj[1][e[0]].push_back(e[1]); - q.push({0, 0}); - q.push({0, 1}); - dist[0][0] = dist[1][0] = 0; - while (!q.empty()) { - auto [crnt, col] = q.front(); - q.pop(); - for (int c : adj[!col][crnt]) { - if (dist[!col][c] != INT_MAX) continue; - dist[!col][c] = dist[col][crnt] + 1; - q.push({c, !col}); - } - } + q.push({0, 0}); + q.push({0, 1}); + dist[0][0] = dist[1][0] = 0; + while (!q.empty()) { + auto [crnt, col] = q.front(); + q.pop(); + for (int c : adj[!col][crnt]) { + if (dist[!col][c] != INT_MAX) continue; + dist[!col][c] = dist[col][crnt] + 1; + q.push({c, !col}); + } + } - vector<int> res(n); - for (int i = 0; i < n; i++) { - res[i] = min(dist[0][i], dist[1][i]); - if (res[i] == INT_MAX) res[i] = -1; - } + vector<int> res(n); + for (int i = 0; i < n; i++) { + res[i] = min(dist[0][i], dist[1][i]); + if (res[i] == INT_MAX) res[i] = -1; + } - return res; - } + return res; + } }; diff --git a/Problems/1137.cpp b/Problems/1137.cpp @@ -1,29 +1,30 @@ // memorization approach class Solution { -public: - int tribonacci(int n) { - vector<int> f(38); - f[0] = 0; - f[1] = 1; - f[2] = 1; - for (int i = 3; i <= n; i++) f[i] = f[i - 1] + f[i - 2] + f[i - 3]; - return f[n]; - } + public: + int tribonacci(int n) { + vector<int> f(38); + f[0] = 0; + f[1] = 1; + f[2] = 1; + for (int i = 3; i <= n; i++) + f[i] = f[i - 1] + f[i - 2] + f[i - 3]; + return f[n]; + } }; // optimized, memorize only the previous three values class Solution { -public: - int tribonacci(int n) { - if (n == 0) return 0; - if (n == 1) return 1; - int a = 0, b = 1, c = 1; - for (int i = 3; i <= n; i++) { - int tmp = a + b + c; - a = b; - b = c; - c = tmp; + public: + int tribonacci(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + int a = 0, b = 1, c = 1; + for (int i = 3; i <= n; i++) { + int tmp = a + b + c; + a = b; + b = c; + c = tmp; + } + return c; } - return c; - } }; diff --git a/Problems/1140.cpp b/Problems/1140.cpp @@ -1,23 +1,23 @@ class Solution { - int dp[10001][101]; + int dp[10001][101]; -public: - Solution() { memset(dp, 0, sizeof(dp)); } + public: + Solution() { memset(dp, 0, sizeof(dp)); } - int stoneGameII(const vector<int> &piles) { - int n = piles.size(); - vector<int> sum(n + 1, 0); - for (int i = n - 1; i >= 0; i--) { - dp[i][n] = sum[i] = sum[i + 1] + piles[i]; - } + int stoneGameII(const vector<int> &piles) { + int n = piles.size(); + vector<int> sum(n + 1, 0); + for (int i = n - 1; i >= 0; i--) { + dp[i][n] = sum[i] = sum[i + 1] + piles[i]; + } - for (int i = n - 1; i >= 0; i--) { - for (int j = n - 1; j >= 1; j--) { - for (int X = 1; X <= 2 * j && i + X <= n; X++) { - dp[i][j] = max(dp[i][j], sum[i] - dp[i + X][max(j, X)]); + for (int i = n - 1; i >= 0; i--) { + for (int j = n - 1; j >= 1; j--) { + for (int X = 1; X <= 2 * j && i + X <= n; X++) { + dp[i][j] = max(dp[i][j], sum[i] - dp[i + X][max(j, X)]); + } + } } - } + return dp[0][1]; } - return dp[0][1]; - } }; diff --git a/Problems/1143.cpp b/Problems/1143.cpp @@ -1,37 +1,35 @@ // Top-down DP class Solution { - int search(const string &text1, const string &text2, int si, int sj, - vector<vector<int>> &dp) { - if (si == text1.size() || sj == text2.size()) return 0; - if (dp[si][sj] != -1) return dp[si][sj]; - int len = 0, i = si, j = sj; - while (i < text1.size() && j < text2.size() && text1[i] == text2[j]) - i++, j++, len++; + int search(const string &text1, const string &text2, int si, int sj, vector<vector<int>> &dp) { + if (si == text1.size() || sj == text2.size()) return 0; + if (dp[si][sj] != -1) return dp[si][sj]; + int len = 0, i = si, j = sj; + while (i < text1.size() && j < text2.size() && text1[i] == text2[j]) + i++, j++, len++; - if (i == text1.size() || j == text2.size()) return dp[si][sj] = len; - return dp[si][sj] = len + max(search(text1, text2, i + 1, j, dp), - search(text1, text2, i, j + 1, dp)); - } + if (i == text1.size() || j == text2.size()) return dp[si][sj] = len; + return dp[si][sj] = len + max(search(text1, text2, i + 1, j, dp), search(text1, text2, i, j + 1, dp)); + } -public: - int longestCommonSubsequence(string text1, string text2) { - vector<vector<int>> dp(text1.size(), vector<int>(text2.size(), -1)); - return search(text1, text2, 0, 0, dp); - } + public: + int longestCommonSubsequence(string text1, string text2) { + vector<vector<int>> dp(text1.size(), vector<int>(text2.size(), -1)); + return search(text1, text2, 0, 0, dp); + } }; // Bottom-up DP class Solution { -public: - int longestCommonSubsequence(string text1, string text2) { - vector<vector<int>> dp(text1.size() + 1, vector<int>(text2.size() + 1, 0)); - for (int i = 0; i < text1.size(); i++) - for (int j = 0; j < text2.size(); j++) - if (text1[i] == text2[j]) - dp[i + 1][j + 1] = 1 + dp[i][j]; - else - dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1]); + public: + int longestCommonSubsequence(string text1, string text2) { + vector<vector<int>> dp(text1.size() + 1, vector<int>(text2.size() + 1, 0)); + for (int i = 0; i < text1.size(); i++) + for (int j = 0; j < text2.size(); j++) + if (text1[i] == text2[j]) + dp[i + 1][j + 1] = 1 + dp[i][j]; + else + dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1]); - return dp.back().back(); - } + return dp.back().back(); + } }; diff --git a/Problems/1146.cpp b/Problems/1146.cpp @@ -1,35 +1,30 @@ class SnapshotArray { - vector<vector<pair<int, int>>> diffs; - int id = 0; + vector<vector<pair<int, int>>> diffs; + int id = 0; -public: - SnapshotArray(int length) - : diffs(length, - { - {0, 0} - }), - id() {} - int snap() { return id++; } + public: + SnapshotArray(int length) : diffs(length, {{0, 0}}), id() {} + int snap() { return id++; } - void set(int index, int val) { - if (diffs[index].back().first != id) - diffs[index].push_back({id, val}); - else - diffs[index].back().second = val; - } + void set(int index, int val) { + if (diffs[index].back().first != id) + diffs[index].push_back({id, val}); + else + diffs[index].back().second = val; + } - int get(int index, int snap_id) { - const vector<pair<int, int>> &vec = diffs[index]; - int low = 0, high = vec.size() - 1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (vec[mid].first == snap_id) - return vec[mid].second; - else if (vec[mid].first < snap_id) - low = mid + 1; - else - high = mid - 1; + int get(int index, int snap_id) { + const vector<pair<int, int>> &vec = diffs[index]; + int low = 0, high = vec.size() - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (vec[mid].first == snap_id) + return vec[mid].second; + else if (vec[mid].first < snap_id) + low = mid + 1; + else + high = mid - 1; + } + return diffs[index][high].second; } - return diffs[index][high].second; - } }; diff --git a/Problems/1161.cpp b/Problems/1161.cpp @@ -1,24 +1,24 @@ class Solution { -public: - int maxLevelSum(TreeNode *root) { - queue<TreeNode *> q; - q.push(root); + public: + int maxLevelSum(TreeNode *root) { + queue<TreeNode *> q; + q.push(root); - int maxi = INT_MIN, index = -1; - for (int lvl = 1; !q.empty(); lvl++) { - int sum = 0; - for (int k = q.size(); k > 0; k--) { - TreeNode *root = q.front(); - q.pop(); - sum += root->val; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } - if (sum > maxi) { - maxi = sum; - index = lvl; - } + int maxi = INT_MIN, index = -1; + for (int lvl = 1; !q.empty(); lvl++) { + int sum = 0; + for (int k = q.size(); k > 0; k--) { + TreeNode *root = q.front(); + q.pop(); + sum += root->val; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + if (sum > maxi) { + maxi = sum; + index = lvl; + } + } + return index; } - return index; - } }; diff --git a/Problems/1162.cpp b/Problems/1162.cpp @@ -1,40 +1,40 @@ class Solution { - int n, m; + int n, m; - bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } + bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } -public: - int maxDistance(vector<vector<int>> &grid) { - n = grid.size(), m = grid[0].size(); - queue<pair<int, int>> q; + public: + int maxDistance(vector<vector<int>> &grid) { + n = grid.size(), m = grid[0].size(); + queue<pair<int, int>> q; - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - if (grid[i][j]) { - q.push({i, j}); - grid[i][j] = 0; - } else - grid[i][j] = -1; - } - } - if (q.empty() || q.size() == n * m) return -1; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (grid[i][j]) { + q.push({i, j}); + grid[i][j] = 0; + } else + grid[i][j] = -1; + } + } + if (q.empty() || q.size() == n * m) return -1; - vector<int> offset_x{0, 0, 1, -1}, offset_y{1, -1, 0, 0}; + vector<int> offset_x{0, 0, 1, -1}, offset_y{1, -1, 0, 0}; - int res = 0; - while (!q.empty()) { - auto [a, b] = q.front(); - q.pop(); - res = max(res, grid[a][b]); - for (int i = 0; i < 4; i++) { - int x = a + offset_x[i]; - int y = b + offset_y[i]; - if (!valid(x, y) || grid[x][y] >= 0) continue; - grid[x][y] = grid[a][b] + 1; - q.push({x, y}); - } - } + int res = 0; + while (!q.empty()) { + auto [a, b] = q.front(); + q.pop(); + res = max(res, grid[a][b]); + for (int i = 0; i < 4; i++) { + int x = a + offset_x[i]; + int y = b + offset_y[i]; + if (!valid(x, y) || grid[x][y] >= 0) continue; + grid[x][y] = grid[a][b] + 1; + q.push({x, y}); + } + } - return res; - } + return res; + } }; diff --git a/Problems/1187.cpp b/Problems/1187.cpp @@ -1,33 +1,32 @@ class Solution { - int dp[2001][2001][2]; + int dp[2001][2001][2]; - void norm(vector<int> &arr) { - sort(arr.begin(), arr.end()); - int i = 1, j = 1; - while (i < arr.size()) { - if (arr[i] != arr[i - 1]) arr[j++] = arr[i]; - i++; + void norm(vector<int> &arr) { + sort(arr.begin(), arr.end()); + int i = 1, j = 1; + while (i < arr.size()) { + if (arr[i] != arr[i - 1]) arr[j++] = arr[i]; + i++; + } + arr.resize(j); } - arr.resize(j); - } - int rec(const vector<int> &arr1, const vector<int> &arr2, int i, int j, - bool other) { - if (i >= arr1.size()) return 0; - int prev = !other ? i == 0 ? INT_MIN : arr1[i - 1] : arr2[j]; - j = upper_bound(arr2.begin() + j, arr2.end(), prev) - arr2.begin(); - if (dp[i][j][other]) return dp[i][j][other]; + int rec(const vector<int> &arr1, const vector<int> &arr2, int i, int j, bool other) { + if (i >= arr1.size()) return 0; + int prev = !other ? i == 0 ? INT_MIN : arr1[i - 1] : arr2[j]; + j = upper_bound(arr2.begin() + j, arr2.end(), prev) - arr2.begin(); + if (dp[i][j][other]) return dp[i][j][other]; - int res = 2002; - if (j < arr2.size()) res = rec(arr1, arr2, i + 1, j, true) + 1; - if (prev < arr1[i]) res = min(res, rec(arr1, arr2, i + 1, j, false)); - return dp[i][j][other] = res; - } + int res = 2002; + if (j < arr2.size()) res = rec(arr1, arr2, i + 1, j, true) + 1; + if (prev < arr1[i]) res = min(res, rec(arr1, arr2, i + 1, j, false)); + return dp[i][j][other] = res; + } -public: - int makeArrayIncreasing(vector<int> &arr1, vector<int> &arr2) { - norm(arr2); - int res = rec(arr1, arr2, 0, 0, false); - return res >= 2002 ? -1 : res; - } + public: + int makeArrayIncreasing(vector<int> &arr1, vector<int> &arr2) { + norm(arr2); + int res = rec(arr1, arr2, 0, 0, false); + return res >= 2002 ? -1 : res; + } }; diff --git a/Problems/1202.cpp b/Problems/1202.cpp @@ -1,42 +1,45 @@ class UnionFind { - vector<int> root, rank; + vector<int> root, rank; -public: - UnionFind(int n) : root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } + public: + UnionFind(int n) : root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } - int find(int x) { - if (x == root[x]) return x; - return root[x] = find(root[x]); - } + int find(int x) { + if (x == root[x]) return x; + return root[x] = find(root[x]); + } - void join(int x, int y) { - x = find(x), y = find(y); + void join(int x, int y) { + x = find(x), y = find(y); - if (x != y) { - if (rank[x] > rank[y]) swap(x, y); - root[y] = x; - rank[x] += x == y; + if (x != y) { + if (rank[x] > rank[y]) swap(x, y); + root[y] = x; + rank[x] += x == y; + } } - } }; class Solution { -public: - string smallestStringWithSwaps(string s, vector<vector<int>> &pairs) { - UnionFind uf(s.size()); - vector<vector<char>> vs(s.size()); - - for (auto &p : pairs) uf.join(p[0], p[1]); - - for (int i = 0; i < s.size(); i++) vs[uf.find(i)].push_back(s[i]); - - for (auto &s : vs) sort(s.rbegin(), s.rend()); - - for (int i = 0; i < s.size(); i++) { - int index = uf.find(i); - s[i] = vs[index].back(); - vs[index].pop_back(); + public: + string smallestStringWithSwaps(string s, vector<vector<int>> &pairs) { + UnionFind uf(s.size()); + vector<vector<char>> vs(s.size()); + + for (auto &p : pairs) + uf.join(p[0], p[1]); + + for (int i = 0; i < s.size(); i++) + vs[uf.find(i)].push_back(s[i]); + + for (auto &s : vs) + sort(s.rbegin(), s.rend()); + + for (int i = 0; i < s.size(); i++) { + int index = uf.find(i); + s[i] = vs[index].back(); + vs[index].pop_back(); + } + return s; } - return s; - } }; diff --git a/Problems/1203.cpp b/Problems/1203.cpp @@ -1,53 +1,52 @@ class Solution { -public: - vector<int> sortItems(int n, int m, vector<int> &group, - const vector<vector<int>> &beforeItems) { - for (int &g : group) - if (g == -1) g = m++; + public: + vector<int> sortItems(int n, int m, vector<int> &group, const vector<vector<int>> &beforeItems) { + for (int &g : group) + if (g == -1) g = m++; - vector<unordered_set<int>> gadj(m); - vector<vector<int>> adj(n), ordered(m); - vector<int> gcount(m, 0), count(n, 0); - queue<int> q; + vector<unordered_set<int>> gadj(m); + vector<vector<int>> adj(n), ordered(m); + vector<int> gcount(m, 0), count(n, 0); + queue<int> q; - for (int i = 0; i < n; i++) { - count[i] = beforeItems[i].size(); - for (int elem : beforeItems[i]) { - adj[elem].push_back(i); - if (group[elem] == group[i]) continue; - if (gadj[group[elem]].count(group[i])) continue; - gadj[group[elem]].insert(group[i]); - gcount[group[i]]++; - } - } + for (int i = 0; i < n; i++) { + count[i] = beforeItems[i].size(); + for (int elem : beforeItems[i]) { + adj[elem].push_back(i); + if (group[elem] == group[i]) continue; + if (gadj[group[elem]].count(group[i])) continue; + gadj[group[elem]].insert(group[i]); + gcount[group[i]]++; + } + } - int cnt = 0; - for (int i = 0; i < n; i++) - if (!count[i]) q.push(i); - while (!q.empty()) { - const int root = q.front(); - ordered[group[root]].push_back(root); - for (int next : adj[q.front()]) { - if (!--count[next]) q.push(next); - } - q.pop(); - cnt++; - } + int cnt = 0; + for (int i = 0; i < n; i++) + if (!count[i]) q.push(i); + while (!q.empty()) { + const int root = q.front(); + ordered[group[root]].push_back(root); + for (int next : adj[q.front()]) { + if (!--count[next]) q.push(next); + } + q.pop(); + cnt++; + } - if (cnt != n) return {}; + if (cnt != n) return {}; - vector<int> res; - for (int i = 0; i < m; i++) - if (!gcount[i]) q.push(i); - while (!q.empty()) { - const int root = q.front(); - res.insert(res.end(), ordered[root].begin(), ordered[root].end()); - for (int next : gadj[q.front()]) { - if (!--gcount[next]) q.push(next); - } - q.pop(); - } + vector<int> res; + for (int i = 0; i < m; i++) + if (!gcount[i]) q.push(i); + while (!q.empty()) { + const int root = q.front(); + res.insert(res.end(), ordered[root].begin(), ordered[root].end()); + for (int next : gadj[q.front()]) { + if (!--gcount[next]) q.push(next); + } + q.pop(); + } - return res.size() == n ? res : vector<int>(); - } + return res.size() == n ? res : vector<int>(); + } }; diff --git a/Problems/1209.cpp b/Problems/1209.cpp @@ -1,19 +1,19 @@ class Solution { -public: - string removeDuplicates(string s, int k) { - stack<pair<char, int>> st; - for (char c : s) - if (!st.empty() && st.top().first == c) { - if (++st.top().second == k) st.pop(); - } else - st.push(make_pair(c, 1)); + public: + string removeDuplicates(string s, int k) { + stack<pair<char, int>> st; + for (char c : s) + if (!st.empty() && st.top().first == c) { + if (++st.top().second == k) st.pop(); + } else + st.push(make_pair(c, 1)); - string res = ""; - while (!st.empty()) { - res += string(st.top().second, st.top().first); - st.pop(); + string res = ""; + while (!st.empty()) { + res += string(st.top().second, st.top().first); + st.pop(); + } + reverse(res.begin(), res.end()); + return res; } - reverse(res.begin(), res.end()); - return res; - } }; diff --git a/Problems/1218.cpp b/Problems/1218.cpp @@ -1,14 +1,14 @@ class Solution { -public: - int longestSubsequence(const vector<int> &arr, int diff) { - unordered_map<int, int> dp; + public: + int longestSubsequence(const vector<int> &arr, int diff) { + unordered_map<int, int> dp; - int res = 1; - for (int n : arr) { - int before = dp.count(n - diff) ? dp[n - diff] : 0; - res = max(res, dp[n] = before + 1); - } + int res = 1; + for (int n : arr) { + int before = dp.count(n - diff) ? dp[n - diff] : 0; + res = max(res, dp[n] = before + 1); + } - return res; - } + return res; + } }; diff --git a/Problems/1232.cpp b/Problems/1232.cpp @@ -1,15 +1,15 @@ class Solution { -public: - bool checkStraightLine(vector<vector<int>> &coordinates) { - int n = coordinates.size(); - if (n == 2) return true; - int x0 = coordinates[0][0], y0 = coordinates[0][1]; - int dx = coordinates[1][0] - x0, dy = coordinates[1][1] - y0; + public: + bool checkStraightLine(vector<vector<int>> &coordinates) { + int n = coordinates.size(); + if (n == 2) return true; + int x0 = coordinates[0][0], y0 = coordinates[0][1]; + int dx = coordinates[1][0] - x0, dy = coordinates[1][1] - y0; - for (int i = 1; i < n; i++) { - int x = coordinates[i][0], y = coordinates[i][1]; - if (dx * (y - y0) != dy * (x - x0)) return false; + for (int i = 1; i < n; i++) { + int x = coordinates[i][0], y = coordinates[i][1]; + if (dx * (y - y0) != dy * (x - x0)) return false; + } + return true; } - return true; - } }; diff --git a/Problems/1249.cpp b/Problems/1249.cpp @@ -1,19 +1,20 @@ class Solution { -public: - string minRemoveToMakeValid(string s) { - stack<int> st; - for (auto i = 0; i < s.size(); i++) { - if (s[i] == '(') - st.push(i); - else if (s[i] == ')') { - if (!st.empty()) - st.pop(); - else - s[i] = '*'; - } + public: + string minRemoveToMakeValid(string s) { + stack<int> st; + for (auto i = 0; i < s.size(); i++) { + if (s[i] == '(') + st.push(i); + else if (s[i] == ')') { + if (!st.empty()) + st.pop(); + else + s[i] = '*'; + } + } + while (!st.empty()) + s[st.top()] = '*', st.pop(); + s.erase(remove(s.begin(), s.end(), '*'), s.end()); + return s; } - while (!st.empty()) s[st.top()] = '*', st.pop(); - s.erase(remove(s.begin(), s.end(), '*'), s.end()); - return s; - } }; diff --git a/Problems/1254.cpp b/Problems/1254.cpp @@ -1,36 +1,36 @@ class Solution { - int n, m; - bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } + int n, m; + bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } - void flood_fill(vector<vector<int>> &grid, int x, int y) { - grid[x][y] = 1; - if (valid(x + 1, y) && !grid[x + 1][y]) flood_fill(grid, x + 1, y); - if (valid(x - 1, y) && !grid[x - 1][y]) flood_fill(grid, x - 1, y); - if (valid(x, y + 1) && !grid[x][y + 1]) flood_fill(grid, x, y + 1); - if (valid(x, y - 1) && !grid[x][y - 1]) flood_fill(grid, x, y - 1); - } - -public: - int closedIsland(vector<vector<int>> &grid) { - n = grid.size(), m = grid[0].size(); - for (int i = 0; i < n; i++) { - if (!grid[i][0]) flood_fill(grid, i, 0); - if (!grid[i][m - 1]) flood_fill(grid, i, m - 1); - } - for (int i = 0; i < m; i++) { - if (!grid[0][i]) flood_fill(grid, 0, i); - if (!grid[n - 1][i]) flood_fill(grid, n - 1, i); + void flood_fill(vector<vector<int>> &grid, int x, int y) { + grid[x][y] = 1; + if (valid(x + 1, y) && !grid[x + 1][y]) flood_fill(grid, x + 1, y); + if (valid(x - 1, y) && !grid[x - 1][y]) flood_fill(grid, x - 1, y); + if (valid(x, y + 1) && !grid[x][y + 1]) flood_fill(grid, x, y + 1); + if (valid(x, y - 1) && !grid[x][y - 1]) flood_fill(grid, x, y - 1); } - int res = 0; - for (int i = 1; i < n - 1; i++) { - for (int j = 1; j < m - 1; j++) { - if (grid[i][j]) continue; - flood_fill(grid, i, j); - res++; - } - } + public: + int closedIsland(vector<vector<int>> &grid) { + n = grid.size(), m = grid[0].size(); + for (int i = 0; i < n; i++) { + if (!grid[i][0]) flood_fill(grid, i, 0); + if (!grid[i][m - 1]) flood_fill(grid, i, m - 1); + } + for (int i = 0; i < m; i++) { + if (!grid[0][i]) flood_fill(grid, 0, i); + if (!grid[n - 1][i]) flood_fill(grid, n - 1, i); + } - return res; - } + int res = 0; + for (int i = 1; i < n - 1; i++) { + for (int j = 1; j < m - 1; j++) { + if (grid[i][j]) continue; + flood_fill(grid, i, j); + res++; + } + } + + return res; + } }; diff --git a/Problems/1261.cpp b/Problems/1261.cpp @@ -1,25 +1,25 @@ class FindElements { - TreeNode *root; - unordered_set<int> all; + TreeNode *root; + unordered_set<int> all; -public: - FindElements(TreeNode *root) : root(root) { - queue<TreeNode *> q({root}); - root->val = 0; - while (!q.empty()) { - TreeNode *root = q.front(); - q.pop(); - all.insert(root->val); - if (root->left) { - root->left->val = 2 * root->val + 1; - q.push(root->left); - } - if (root->right) { - root->right->val = 2 * root->val + 2; - q.push(root->right); - } + public: + FindElements(TreeNode *root) : root(root) { + queue<TreeNode *> q({root}); + root->val = 0; + while (!q.empty()) { + TreeNode *root = q.front(); + q.pop(); + all.insert(root->val); + if (root->left) { + root->left->val = 2 * root->val + 1; + q.push(root->left); + } + if (root->right) { + root->right->val = 2 * root->val + 2; + q.push(root->right); + } + } } - } - bool find(int target) { return all.count(target); } + bool find(int target) { return all.count(target); } }; diff --git a/Problems/1277.cpp b/Problems/1277.cpp @@ -1,29 +1,27 @@ class Solution { -public: - int countSquares(const vector<vector<int>> &matrix) { - int n = matrix.size(), m = matrix[0].size(); - vector<vector<int>> count(n + 1, vector<int>(m + 1)); + public: + int countSquares(const vector<vector<int>> &matrix) { + int n = matrix.size(), m = matrix[0].size(); + vector<vector<int>> count(n + 1, vector<int>(m + 1)); - for (int i = 1; i <= n; i++) { - for (int j = 1; j <= m; j++) { - count[i][j] = matrix[i - 1][j - 1] + count[i - 1][j] + count[i][j - 1] - - count[i - 1][j - 1]; - } - } + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + count[i][j] = matrix[i - 1][j - 1] + count[i - 1][j] + count[i][j - 1] - count[i - 1][j - 1]; + } + } - int res = 0; - for (int i = 1; i <= n; i++) { - for (int j = 1; j <= m; j++) { - int x = i, y = j; - for (int k = 1, x = i, y = j; x <= n && y <= m; x++, y++, k++) { - int sum = count[x][y] - count[i - 1][y] - count[x][j - 1] + - count[i - 1][j - 1]; - if (sum != k * k) break; - res++; + int res = 0; + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + int x = i, y = j; + for (int k = 1, x = i, y = j; x <= n && y <= m; x++, y++, k++) { + int sum = count[x][y] - count[i - 1][y] - count[x][j - 1] + count[i - 1][j - 1]; + if (sum != k * k) break; + res++; + } + } } - } - } - return res; - } + return res; + } }; diff --git a/Problems/1282.cpp b/Problems/1282.cpp @@ -1,22 +1,22 @@ class Solution { -public: - vector<vector<int>> groupThePeople(const vector<int> &groupSizes) { - unordered_map<int, vector<int>> um; - vector<vector<int>> res; + public: + vector<vector<int>> groupThePeople(const vector<int> &groupSizes) { + unordered_map<int, vector<int>> um; + vector<vector<int>> res; - for (int i = 0; i < groupSizes.size(); i++) { - if (groupSizes[i] == 1) - res.push_back({i}); - else { - int size = groupSizes[i]; - um[size].push_back(i); - if (um[size].size() == size) { - res.push_back({}); - swap(res.back(), um[size]); + for (int i = 0; i < groupSizes.size(); i++) { + if (groupSizes[i] == 1) + res.push_back({i}); + else { + int size = groupSizes[i]; + um[size].push_back(i); + if (um[size].size() == size) { + res.push_back({}); + swap(res.back(), um[size]); + } + } } - } - } - return res; - } + return res; + } }; diff --git a/Problems/1286.cpp b/Problems/1286.cpp @@ -1,28 +1,29 @@ class Solution { - vector<int> vec; - const string chars; - string res; + vector<int> vec; + const string chars; + string res; - bool has_next = true; - void shuffle() { - int goal = chars.size() - 1, idx = vec.size() - 1; - while (idx > 0 && vec[idx] == goal) goal--, idx--; - for (int i = idx, acc = vec[idx]; i < vec.size(); i++) - res[i] = chars[vec[i] = ++acc]; - if (idx == 0 && vec[0] == goal) has_next = false; - } + bool has_next = true; + void shuffle() { + int goal = chars.size() - 1, idx = vec.size() - 1; + while (idx > 0 && vec[idx] == goal) + goal--, idx--; + for (int i = idx, acc = vec[idx]; i < vec.size(); i++) + res[i] = chars[vec[i] = ++acc]; + if (idx == 0 && vec[0] == goal) has_next = false; + } -public: - CombinationIterator(string chars, int len) - : chars(chars), vec(len), res(len, ' ') { - for (int i = 0; i < len; i++) res[i] = chars[vec[i] = i]; - vec.back()--; - } + public: + CombinationIterator(string chars, int len) : chars(chars), vec(len), res(len, ' ') { + for (int i = 0; i < len; i++) + res[i] = chars[vec[i] = i]; + vec.back()--; + } - string next() { - shuffle(); - return res; - } + string next() { + shuffle(); + return res; + } - bool hasNext() { return has_next; } + bool hasNext() { return has_next; } }; diff --git a/Problems/1290.cpp b/Problems/1290.cpp @@ -1,8 +1,9 @@ class Solution { -public: - int getDecimalValue(ListNode *head) { - int res = 0; - for (; head; head = head->next) res = res * 2 + head->val; - return res; - } + public: + int getDecimalValue(ListNode *head) { + int res = 0; + for (; head; head = head->next) + res = res * 2 + head->val; + return res; + } }; diff --git a/Problems/1302.cpp b/Problems/1302.cpp @@ -1,20 +1,20 @@ class Solution { -public: - int deepestLeavesSum(TreeNode *root) { - int sum = 0; + public: + int deepestLeavesSum(TreeNode *root) { + int sum = 0; - queue<TreeNode *> q; - q.push(root); - while (!q.empty()) { - sum = 0; - for (int k = q.size(); k > 0; k--) { - TreeNode *root = q.front(); - q.pop(); - sum += root->val; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } + queue<TreeNode *> q; + q.push(root); + while (!q.empty()) { + sum = 0; + for (int k = q.size(); k > 0; k--) { + TreeNode *root = q.front(); + q.pop(); + sum += root->val; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + } + return sum; } - return sum; - } }; diff --git a/Problems/1305.cpp b/Problems/1305.cpp @@ -1,58 +1,60 @@ // Not using BST property at all class Solution { - void travel(TreeNode *root, multiset<int> &s) { - stack<TreeNode *> st; - while (true) { - while (root) { - if (root->right) st.push(root->right); - s.insert(root->val); - root = root->left; - } - if (st.empty()) break; - root = st.top(), st.pop(); + void travel(TreeNode *root, multiset<int> &s) { + stack<TreeNode *> st; + while (true) { + while (root) { + if (root->right) st.push(root->right); + s.insert(root->val); + root = root->left; + } + if (st.empty()) break; + root = st.top(), st.pop(); + } } - } -public: - vector<int> getAllElements(TreeNode *root1, TreeNode *root2) { - vector<int> res; - multiset<int> s; - travel(root1, s), travel(root2, s); - for (int n : s) res.push_back(n); - return res; - } + public: + vector<int> getAllElements(TreeNode *root1, TreeNode *root2) { + vector<int> res; + multiset<int> s; + travel(root1, s), travel(root2, s); + for (int n : s) + res.push_back(n); + return res; + } }; // Using BST property to travel both trees in-order class Solution { - void advance(TreeNode *root, stack<TreeNode *> &st) { - while (root) { - st.push(root); - root = root->left; + void advance(TreeNode *root, stack<TreeNode *> &st) { + while (root) { + st.push(root); + root = root->left; + } } - } - void append(vector<int> &res, stack<TreeNode *> &st) { - res.push_back(st.top()->val); - TreeNode *tmp = st.top(); - st.pop(); - advance(tmp->right, st); - } + void append(vector<int> &res, stack<TreeNode *> &st) { + res.push_back(st.top()->val); + TreeNode *tmp = st.top(); + st.pop(); + advance(tmp->right, st); + } -public: - vector<int> getAllElements(TreeNode *root1, TreeNode *root2) { - stack<TreeNode *> st1, st2; - vector<int> res; - advance(root1, st1), advance(root2, st2); + public: + vector<int> getAllElements(TreeNode *root1, TreeNode *root2) { + stack<TreeNode *> st1, st2; + vector<int> res; + advance(root1, st1), advance(root2, st2); - while (!st1.empty() && !st2.empty()) { - if (st1.top()->val > st2.top()->val) - append(res, st2); - else - append(res, st1); + while (!st1.empty() && !st2.empty()) { + if (st1.top()->val > st2.top()->val) + append(res, st2); + else + append(res, st1); + } + if (st1.empty()) std::swap(st1, st2); + while (!st1.empty()) + append(res, st1); + return res; } - if (st1.empty()) std::swap(st1, st2); - while (!st1.empty()) append(res, st1); - return res; - } }; diff --git a/Problems/1311.cpp b/Problems/1311.cpp @@ -1,37 +1,39 @@ class Solution { -public: - vector<string> watchedVideosByFriends(vector<vector<string>> &watchedVideos, - vector<vector<int>> &adj, int id, - int level) { - int n = adj.size(); - vector<bool> visited(n, false); - queue<int> q; + public: + vector<string> watchedVideosByFriends(vector<vector<string>> &watchedVideos, vector<vector<int>> &adj, + int id, int level) { + int n = adj.size(); + vector<bool> visited(n, false); + queue<int> q; - q.push(id); - visited[id] = true; - for (int lvl = 0; lvl != level; lvl++) { - for (int k = q.size(); k > 0; k--) { - int id = q.front(); - q.pop(); - for (int c : adj[id]) { - if (!visited[c]) { - visited[c] = true; - q.push(c); - } + q.push(id); + visited[id] = true; + for (int lvl = 0; lvl != level; lvl++) { + for (int k = q.size(); k > 0; k--) { + int id = q.front(); + q.pop(); + for (int c : adj[id]) { + if (!visited[c]) { + visited[c] = true; + q.push(c); + } + } + } } - } - } - unordered_map<string, int> freq; - vector<pair<int, string>> vec; - vector<string> res; + unordered_map<string, int> freq; + vector<pair<int, string>> vec; + vector<string> res; - for (; !q.empty(); q.pop()) - for (auto &st : watchedVideos[q.front()]) freq[st]++; + for (; !q.empty(); q.pop()) + for (auto &st : watchedVideos[q.front()]) + freq[st]++; - for (auto &[k, v] : freq) vec.push_back({v, k}); - sort(vec.begin(), vec.end()); - for (auto &[_, title] : vec) res.push_back(title); - return res; - } + for (auto &[k, v] : freq) + vec.push_back({v, k}); + sort(vec.begin(), vec.end()); + for (auto &[_, title] : vec) + res.push_back(title); + return res; + } }; diff --git a/Problems/1312.cpp b/Problems/1312.cpp @@ -1,13 +1,13 @@ class Solution { -public: - int minInsertions(string s) { - int dp[501][501] = {0}, n = s.size(); - for (int i = 0; i < n; i++) - for (int j = 0; j < n; j++) - if (s[i] == s[n - 1 - j]) - dp[i + 1][j + 1] = dp[i][j] + 1; - else - dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]); - return n - dp[n][n]; - } + public: + int minInsertions(string s) { + int dp[501][501] = {0}, n = s.size(); + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + if (s[i] == s[n - 1 - j]) + dp[i + 1][j + 1] = dp[i][j] + 1; + else + dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]); + return n - dp[n][n]; + } }; diff --git a/Problems/1314.cpp b/Problems/1314.cpp @@ -1,32 +1,32 @@ class Solution { - inline int clamp(const int a, const int x, const int y) { - return min(max(a, x), y); - } + inline int clamp(const int a, const int x, const int y) { return min(max(a, x), y); } -public: - vector<vector<int>> matrixBlockSum(vector<vector<int>> &mat, int k) { - int n = mat.size(), m = mat[0].size(); - vector<vector<int>> dp(n, vector<int>(m, 0)), res(n, vector<int>(m, 0)); + public: + vector<vector<int>> matrixBlockSum(vector<vector<int>> &mat, int k) { + int n = mat.size(), m = mat[0].size(); + vector<vector<int>> dp(n, vector<int>(m, 0)), res(n, vector<int>(m, 0)); - for (int i = 0, sum = 0; i < n; i++) sum = dp[i][0] = mat[i][0] + sum; - for (int i = 0, sum = 0; i < m; i++) sum = dp[0][i] = mat[0][i] + sum; - for (int i = 1; i < n; i++) { - for (int j = 1; j < m; j++) { - dp[i][j] = mat[i][j] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]; - } - } + for (int i = 0, sum = 0; i < n; i++) + sum = dp[i][0] = mat[i][0] + sum; + for (int i = 0, sum = 0; i < m; i++) + sum = dp[0][i] = mat[0][i] + sum; + for (int i = 1; i < n; i++) { + for (int j = 1; j < m; j++) { + dp[i][j] = mat[i][j] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]; + } + } - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - int x1 = clamp(i - k, 0, n - 1), y1 = clamp(j - k, 0, m - 1); - int x2 = clamp(i + k, 0, n - 1), y2 = clamp(j + k, 0, m - 1); - res[i][j] = dp[x2][y2]; - if (x1 > 0) res[i][j] -= dp[x1 - 1][y2]; - if (y1 > 0) res[i][j] -= dp[x2][y1 - 1]; - if (x1 > 0 && y1 > 0) res[i][j] += dp[x1 - 1][y1 - 1]; - } - } + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + int x1 = clamp(i - k, 0, n - 1), y1 = clamp(j - k, 0, m - 1); + int x2 = clamp(i + k, 0, n - 1), y2 = clamp(j + k, 0, m - 1); + res[i][j] = dp[x2][y2]; + if (x1 > 0) res[i][j] -= dp[x1 - 1][y2]; + if (y1 > 0) res[i][j] -= dp[x2][y1 - 1]; + if (x1 > 0 && y1 > 0) res[i][j] += dp[x1 - 1][y1 - 1]; + } + } - return res; - } + return res; + } }; diff --git a/Problems/1315.cpp b/Problems/1315.cpp @@ -1,31 +1,31 @@ class Solution { -public: - int sumEvenGrandparent(TreeNode *root) { - stack<TreeNode *> st; - int sum = 0; + public: + int sumEvenGrandparent(TreeNode *root) { + stack<TreeNode *> st; + int sum = 0; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); - if (root->left) { - st.push(root->left); - if (root->val % 2 == 0) { - if (root->left->left) sum += root->left->left->val; - if (root->left->right) sum += root->left->right->val; - } - } + if (root->left) { + st.push(root->left); + if (root->val % 2 == 0) { + if (root->left->left) sum += root->left->left->val; + if (root->left->right) sum += root->left->right->val; + } + } - if (root->right) { - st.push(root->right); - if (root->val % 2 == 0) { - if (root->right->left) sum += root->right->left->val; - if (root->right->right) sum += root->right->right->val; + if (root->right) { + st.push(root->right); + if (root->val % 2 == 0) { + if (root->right->left) sum += root->right->left->val; + if (root->right->right) sum += root->right->right->val; + } + } } - } - } - return sum; - } + return sum; + } }; diff --git a/Problems/1318.cpp b/Problems/1318.cpp @@ -1,15 +1,15 @@ class Solution { -public: - int minFlips(int a, int b, int c) { - int res = 0; - do { - int ba = a & 1, bb = b & 1; - if (c & 1) - res += !(ba | bb); - else - res += ba + bb; - a >>= 1, b >>= 1, c >>= 1; - } while (a > 0 || b > 0 || c > 0); - return res; - } + public: + int minFlips(int a, int b, int c) { + int res = 0; + do { + int ba = a & 1, bb = b & 1; + if (c & 1) + res += !(ba | bb); + else + res += ba + bb; + a >>= 1, b >>= 1, c >>= 1; + } while (a > 0 || b > 0 || c > 0); + return res; + } }; diff --git a/Problems/1319.cpp b/Problems/1319.cpp @@ -1,45 +1,45 @@ class UnionFind { - int n; - vector<int> root, rank; + int n; + vector<int> root, rank; -public: - UnionFind(int n) : n(n), root(n), rank(n, 1) { - iota(root.begin(), root.end(), 0); - } + public: + UnionFind(int n) : n(n), root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } - void join(int x, int y) { - if (x != y) { - if (rank[x] > rank[y]) swap(x, y); + void join(int x, int y) { + if (x != y) { + if (rank[x] > rank[y]) swap(x, y); - root[x] = y; - rank[y] += rank[x]; + root[x] = y; + rank[y] += rank[x]; + } } - } - int count() { - int cnt = 0; - for (int i = 0; i < n; i++) cnt += root[i] == i; - return cnt; - } + int count() { + int cnt = 0; + for (int i = 0; i < n; i++) + cnt += root[i] == i; + return cnt; + } }; class Solution { -public: - int makeConnected(int n, vector<vector<int>> &connections) { - int count = 0; - UnionFind uf(n); - for (auto &edge : connections) { - int x = uf.find(edge[0]), y = uf.find(edge[1]); - if (x == y) - count++; - else - uf.join(x, y); + public: + int makeConnected(int n, vector<vector<int>> &connections) { + int count = 0; + UnionFind uf(n); + for (auto &edge : connections) { + int x = uf.find(edge[0]), y = uf.find(edge[1]); + if (x == y) + count++; + else + uf.join(x, y); + } + return count < uf.count() - 1 ? -1 : uf.count() - 1; } - return count < uf.count() - 1 ? -1 : uf.count() - 1; - } }; diff --git a/Problems/1323.cpp b/Problems/1323.cpp @@ -1,12 +1,12 @@ class Solution { -public: - int maximum69Number(int num) { - string s = to_string(num); - for (int i = 0; i < size(s); i++) { - if (s[i] == '9') continue; - s[i] = '9'; - return stoi(s); + public: + int maximum69Number(int num) { + string s = to_string(num); + for (int i = 0; i < size(s); i++) { + if (s[i] == '9') continue; + s[i] = '9'; + return stoi(s); + } + return num; } - return num; - } }; diff --git a/Problems/1325.cpp b/Problems/1325.cpp @@ -1,32 +1,30 @@ class Solution { -public: - TreeNode *removeLeafNodes(TreeNode *root, int target) { - TreeNode dummy(-1, root, nullptr); - unordered_map<TreeNode *, TreeNode *> um = { - {root, &dummy} - }; - stack<TreeNode *> st({root}); - while (!st.empty()) { - TreeNode *root = st.top(); - if (root->val < 0) { - st.pop(); - root->val = -root->val; - if (!root->left && !root->right && root->val == target) { - TreeNode *parent = um[root]; - (parent->left == root ? parent->left : parent->right) = nullptr; + public: + TreeNode *removeLeafNodes(TreeNode *root, int target) { + TreeNode dummy(-1, root, nullptr); + unordered_map<TreeNode *, TreeNode *> um = {{root, &dummy}}; + stack<TreeNode *> st({root}); + while (!st.empty()) { + TreeNode *root = st.top(); + if (root->val < 0) { + st.pop(); + root->val = -root->val; + if (!root->left && !root->right && root->val == target) { + TreeNode *parent = um[root]; + (parent->left == root ? parent->left : parent->right) = nullptr; + } + continue; + } + root->val = -root->val; + if (root->left) { + um[root->left] = root; + st.push(root->left); + } + if (root->right) { + um[root->right] = root; + st.push(root->right); + } } - continue; - } - root->val = -root->val; - if (root->left) { - um[root->left] = root; - st.push(root->left); - } - if (root->right) { - um[root->right] = root; - st.push(root->right); - } + return dummy.left; } - return dummy.left; - } }; diff --git a/Problems/1329.cpp b/Problems/1329.cpp @@ -1,44 +1,46 @@ class Solution { -public: - vector<vector<int>> diagonalSort(vector<vector<int>> &mat) { - unordered_map<int, priority_queue<int, vector<int>, greater<int>>> um; - int n = mat.size(), m = mat[0].size(); - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { um[i - j].push(mat[i][j]); } - } + public: + vector<vector<int>> diagonalSort(vector<vector<int>> &mat) { + unordered_map<int, priority_queue<int, vector<int>, greater<int>>> um; + int n = mat.size(), m = mat[0].size(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + um[i - j].push(mat[i][j]); + } + } - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - mat[i][j] = um[i - j].top(); - um[i - j].pop(); - } - } + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + mat[i][j] = um[i - j].top(); + um[i - j].pop(); + } + } - return mat; - } + return mat; + } }; // No extra memory class Solution { -public: - vector<vector<int>> diagonalSort(vector<vector<int>> &mat) { - int n = mat.size(), m = mat[0].size(); - for (int k = 0; k < m; k++) { - for (int i = 0, ik = k; i < n && ik < m; i++, ik++) { - for (int j = 0, jk = k; j < n && jk < m; j++, jk++) { - if (mat[i][ik] < mat[j][jk]) swap(mat[i][ik], mat[j][jk]); + public: + vector<vector<int>> diagonalSort(vector<vector<int>> &mat) { + int n = mat.size(), m = mat[0].size(); + for (int k = 0; k < m; k++) { + for (int i = 0, ik = k; i < n && ik < m; i++, ik++) { + for (int j = 0, jk = k; j < n && jk < m; j++, jk++) { + if (mat[i][ik] < mat[j][jk]) swap(mat[i][ik], mat[j][jk]); + } + } } - } - } - for (int k = 0; k < n; k++) { - for (int i = 0, ik = k; i < m && ik < n; i++, ik++) { - for (int j = 0, jk = k; j < m && jk < n; j++, jk++) { - if (mat[ik][i] < mat[jk][j]) swap(mat[ik][i], mat[jk][j]); + for (int k = 0; k < n; k++) { + for (int i = 0, ik = k; i < m && ik < n; i++, ik++) { + for (int j = 0, jk = k; j < m && jk < n; j++, jk++) { + if (mat[ik][i] < mat[jk][j]) swap(mat[ik][i], mat[jk][j]); + } + } } - } - } - return mat; - } + return mat; + } }; diff --git a/Problems/1334.cpp b/Problems/1334.cpp @@ -1,57 +1,57 @@ class Solution { - struct edge { - int index, weight; - edge(int i, int w) : index(i), weight(w) {} - friend bool operator<(const edge &e1, const edge &e2) { - return e1.weight > e2.weight; - } - }; - - int dijkstra(int n, vector<vector<edge>> &adj, int start, int threshold) { - vector<int> d(n, INT_MAX); - vector<bool> s(n, false); - priority_queue<edge> pq; + struct edge { + int index, weight; + edge(int i, int w) : index(i), weight(w) {} + friend bool operator<(const edge &e1, const edge &e2) { return e1.weight > e2.weight; } + }; - for (auto &p : adj[start]) { - d[p.index] = p.weight; - pq.push(p); - } + int dijkstra(int n, vector<vector<edge>> &adj, int start, int threshold) { + vector<int> d(n, INT_MAX); + vector<bool> s(n, false); + priority_queue<edge> pq; - s[start] = true; - for (int k = 1; k < n; k++) { - while (!pq.empty() && s[pq.top().index]) pq.pop(); - if (pq.empty()) break; - auto e = pq.top(); - pq.pop(); - s[e.index] = true; - for (auto &p : adj[e.index]) - if (!s[p.index] && d[e.index] + p.weight < d[p.index]) { - d[p.index] = d[e.index] + p.weight; - pq.push({p.index, d[p.index]}); + for (auto &p : adj[start]) { + d[p.index] = p.weight; + pq.push(p); } - } - int count = 0; - for (int i = 0; i < n; i++) count += d[i] <= threshold; - return count; - } + s[start] = true; + for (int k = 1; k < n; k++) { + while (!pq.empty() && s[pq.top().index]) + pq.pop(); + if (pq.empty()) break; + auto e = pq.top(); + pq.pop(); + s[e.index] = true; + for (auto &p : adj[e.index]) + if (!s[p.index] && d[e.index] + p.weight < d[p.index]) { + d[p.index] = d[e.index] + p.weight; + pq.push({p.index, d[p.index]}); + } + } -public: - int findTheCity(int n, vector<vector<int>> &edges, int distanceThreshold) { - vector<vector<edge>> adj(n, vector<edge>()); - for (auto &p : edges) { - adj[p[0]].push_back({p[1], p[2]}); - adj[p[1]].push_back({p[0], p[2]}); + int count = 0; + for (int i = 0; i < n; i++) + count += d[i] <= threshold; + return count; } - int res = -1; - for (int i = 0, mini = INT_MAX; i < n; i++) { - int tmp = dijkstra(n, adj, i, distanceThreshold); - if (tmp <= mini) { - mini = tmp; - res = i; - } + public: + int findTheCity(int n, vector<vector<int>> &edges, int distanceThreshold) { + vector<vector<edge>> adj(n, vector<edge>()); + for (auto &p : edges) { + adj[p[0]].push_back({p[1], p[2]}); + adj[p[1]].push_back({p[0], p[2]}); + } + + int res = -1; + for (int i = 0, mini = INT_MAX; i < n; i++) { + int tmp = dijkstra(n, adj, i, distanceThreshold); + if (tmp <= mini) { + mini = tmp; + res = i; + } + } + return res; } - return res; - } }; diff --git a/Problems/1337.cpp b/Problems/1337.cpp @@ -1,24 +1,24 @@ class Solution { -public: - typedef pair<int, int> ii; - vector<int> kWeakestRows(vector<vector<int>> &mat, int k) { - vector<ii> vp; + public: + typedef pair<int, int> ii; + vector<int> kWeakestRows(vector<vector<int>> &mat, int k) { + vector<ii> vp; - int i = 0; - for (auto &v : mat) - vp.push_back(make_pair(i++, accumulate(v.begin(), v.end(), 0))); + int i = 0; + for (auto &v : mat) + vp.push_back(make_pair(i++, accumulate(v.begin(), v.end(), 0))); - sort(vp.begin(), vp.end(), [](const ii &a, const ii &b) -> bool { - return a.second < b.second || (a.second == b.second && a.first < b.first); - }); + sort(vp.begin(), vp.end(), [](const ii &a, const ii &b) -> bool { + return a.second < b.second || (a.second == b.second && a.first < b.first); + }); - vector<int> res; - for (auto &p : vp) - if (k--) - res.push_back(p.first); - else - break; + vector<int> res; + for (auto &p : vp) + if (k--) + res.push_back(p.first); + else + break; - return res; - } + return res; + } }; diff --git a/Problems/1339.cpp b/Problems/1339.cpp @@ -1,41 +1,41 @@ class Solution { -public: - int maxProduct(TreeNode *root) { - if (!root) return 0; - const unsigned int M = 1000000007; - stack<TreeNode *> st; - st.push(root); - unordered_set<TreeNode *> visited; - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (visited.find(root) != visited.end()) { - if (root->left) root->val += root->left->val; - if (root->right) root->val += root->right->val; - root->val %= M; - continue; - } - st.push(root); - visited.insert(root); - if (root->left) st.push(root->left); - if (root->right) st.push(root->right); - } + public: + int maxProduct(TreeNode *root) { + if (!root) return 0; + const unsigned int M = 1000000007; + stack<TreeNode *> st; + st.push(root); + unordered_set<TreeNode *> visited; + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (visited.find(root) != visited.end()) { + if (root->left) root->val += root->left->val; + if (root->right) root->val += root->right->val; + root->val %= M; + continue; + } + st.push(root); + visited.insert(root); + if (root->left) st.push(root->left); + if (root->right) st.push(root->right); + } - long long res = 0ll; - int total = root->val; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (root->left) { - res = max(res, 1ll * root->left->val * (total - root->left->val)); - st.push(root->left); - } - if (root->right) { - res = max(res, 1ll * root->right->val * (total - root->right->val)); - st.push(root->right); - } + long long res = 0ll; + int total = root->val; + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (root->left) { + res = max(res, 1ll * root->left->val * (total - root->left->val)); + st.push(root->left); + } + if (root->right) { + res = max(res, 1ll * root->right->val * (total - root->right->val)); + st.push(root->right); + } + } + return res % M; } - return res % M; - } }; diff --git a/Problems/1342.cpp b/Problems/1342.cpp @@ -1,14 +1,14 @@ class Solution { -public: - int numberOfSteps(int num) { - int res = 0; - while (num) { - res++; - if (num % 2 == 0) - num /= 2; - else - num--; + public: + int numberOfSteps(int num) { + int res = 0; + while (num) { + res++; + if (num % 2 == 0) + num /= 2; + else + num--; + } + return res; } - return res; - } }; diff --git a/Problems/1345.cpp b/Problems/1345.cpp @@ -1,45 +1,46 @@ class Solution { -public: - int minJumps(vector<int> &arr) { - if (arr.size() < 2) return 0; - if (arr.front() == arr.back()) return 1; - - unordered_map<int, vector<int>> um; - unordered_set<int> visited; - int n = arr.size(); - - for (int i = 0; i < n; i++) um[arr[i]].push_back(i); - - queue<int> q; - q.push(0); - visited.insert(0); - for (int lvl = 0; !q.empty(); lvl++) { - for (int k = q.size(); k > 0; k--) { - int crnt = q.front(); - q.pop(); - - if (crnt == n - 1) return lvl; - - if (crnt + 1 < n && !visited.count(crnt + 1)) { - visited.insert(crnt + 1); - q.push(crnt + 1); + public: + int minJumps(vector<int> &arr) { + if (arr.size() < 2) return 0; + if (arr.front() == arr.back()) return 1; + + unordered_map<int, vector<int>> um; + unordered_set<int> visited; + int n = arr.size(); + + for (int i = 0; i < n; i++) + um[arr[i]].push_back(i); + + queue<int> q; + q.push(0); + visited.insert(0); + for (int lvl = 0; !q.empty(); lvl++) { + for (int k = q.size(); k > 0; k--) { + int crnt = q.front(); + q.pop(); + + if (crnt == n - 1) return lvl; + + if (crnt + 1 < n && !visited.count(crnt + 1)) { + visited.insert(crnt + 1); + q.push(crnt + 1); + } + + if (crnt - 1 >= 0 && !visited.count(crnt - 1)) { + visited.insert(crnt - 1); + q.push(crnt - 1); + } + + for (int index : um[arr[crnt]]) { + if (!visited.count(index)) { + visited.insert(index); + q.push(index); + } + } + + um[arr[crnt]].clear(); + } } - - if (crnt - 1 >= 0 && !visited.count(crnt - 1)) { - visited.insert(crnt - 1); - q.push(crnt - 1); - } - - for (int index : um[arr[crnt]]) { - if (!visited.count(index)) { - visited.insert(index); - q.push(index); - } - } - - um[arr[crnt]].clear(); - } + return -1; } - return -1; - } }; diff --git a/Problems/1346.cpp b/Problems/1346.cpp @@ -1,14 +1,13 @@ class Solution { -public: - bool checkIfExist(vector<int> &arr) { - unordered_set<int> us; - for (int i : arr) - if ((i % 2 == 0 && us.find(i / 2) != us.end()) || - us.find(i * 2) != us.end()) - return true; - else - us.insert(i); + public: + bool checkIfExist(vector<int> &arr) { + unordered_set<int> us; + for (int i : arr) + if ((i % 2 == 0 && us.find(i / 2) != us.end()) || us.find(i * 2) != us.end()) + return true; + else + us.insert(i); - return false; - } + return false; + } }; diff --git a/Problems/1347.cpp b/Problems/1347.cpp @@ -1,14 +1,14 @@ class Solution { -public: - int minSteps(const string &s, const string &t) { - int res = 0, count[27] = {0}; - for (int i = 0; i < s.size(); i++) { - count[s[i] & 0x1F]++; - count[t[i] & 0x1F]--; + public: + int minSteps(const string &s, const string &t) { + int res = 0, count[27] = {0}; + for (int i = 0; i < s.size(); i++) { + count[s[i] & 0x1F]++; + count[t[i] & 0x1F]--; + } + for (int i = 1; i < 27; i++) { + if (count[i] > 0) res += count[i]; + } + return res; } - for (int i = 1; i < 27; i++) { - if (count[i] > 0) res += count[i]; - } - return res; - } }; diff --git a/Problems/1351.cpp b/Problems/1351.cpp @@ -1,16 +1,16 @@ class Solution { -public: - int countNegatives(vector<vector<int>> &grid) { - int n = grid.size(), m = grid[0].size(), res = 0; - int i = n - 1, j = 0, cnt = 0; - while (i >= 0 && j < m) { - if (grid[i][j] < 0) { - res += m - j; - i--; - } else { - j++; - } + public: + int countNegatives(vector<vector<int>> &grid) { + int n = grid.size(), m = grid[0].size(), res = 0; + int i = n - 1, j = 0, cnt = 0; + while (i >= 0 && j < m) { + if (grid[i][j] < 0) { + res += m - j; + i--; + } else { + j++; + } + } + return res; } - return res; - } }; diff --git a/Problems/1361.cpp b/Problems/1361.cpp @@ -1,51 +1,47 @@ class UnionFind { - int n; - vector<int> root, rank; - -public: - UnionFind(int n) : n(n), root(n), rank(n, 1) { - iota(root.begin(), root.end(), 0); - } - - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } - - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (rank[x] > rank[y]) swap(x, y); - root[x] = y; - rank[y] += rank[x]; - n--; + int n; + vector<int> root, rank; + + public: + UnionFind(int n) : n(n), root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } + + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; } - } - int count() { return n; } + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (rank[x] > rank[y]) swap(x, y); + root[x] = y; + rank[y] += rank[x]; + n--; + } + } + + int count() { return n; } }; class Solution { - bool process(UnionFind &uf, vector<int> &parent, int start, int end) { - if (end == -1) return true; - if (parent[end] != -1) return false; - if (uf.find(start) == uf.find(end)) return false; - uf.join(start, end); - parent[end] = start; - return true; - } - -public: - bool validateBinaryTreeNodes(int n, vector<int> &leftChild, - vector<int> &rightChild) { - UnionFind uf(n); - vector<int> parent(n, -1); - - for (int i = 0; i < n; i++) - if (!process(uf, parent, i, leftChild[i]) || - !process(uf, parent, i, rightChild[i])) - return false; - - return uf.count() == 1; - } + bool process(UnionFind &uf, vector<int> &parent, int start, int end) { + if (end == -1) return true; + if (parent[end] != -1) return false; + if (uf.find(start) == uf.find(end)) return false; + uf.join(start, end); + parent[end] = start; + return true; + } + + public: + bool validateBinaryTreeNodes(int n, vector<int> &leftChild, vector<int> &rightChild) { + UnionFind uf(n); + vector<int> parent(n, -1); + + for (int i = 0; i < n; i++) + if (!process(uf, parent, i, leftChild[i]) || !process(uf, parent, i, rightChild[i])) return false; + + return uf.count() == 1; + } }; diff --git a/Problems/1367.cpp b/Problems/1367.cpp @@ -1,35 +1,37 @@ class Solution { - vector<int> needle, lps; + vector<int> needle, lps; - void computeKMPTable(vector<int> needle) { - lps.resize(needle.size(), 0); + void computeKMPTable(vector<int> needle) { + lps.resize(needle.size(), 0); - for (int len = 0, j = 1; j < size(needle);) { - if (needle[j] == needle[len]) - lps[j++] = ++len; - else if (len) - len = lps[len - 1]; - else - lps[j++] = 0; + for (int len = 0, j = 1; j < size(needle);) { + if (needle[j] == needle[len]) + lps[j++] = ++len; + else if (len) + len = lps[len - 1]; + else + lps[j++] = 0; + } } - } - bool kmpSearch(TreeNode *root, int j) { - if (j == size(needle)) return true; - if (!root) return false; - while (j > 0 && root->val != needle[j]) j = lps[j - 1]; - if (root->val == needle[j]) j++; - return kmpSearch(root->left, j) || kmpSearch(root->right, j); - } + bool kmpSearch(TreeNode *root, int j) { + if (j == size(needle)) return true; + if (!root) return false; + while (j > 0 && root->val != needle[j]) + j = lps[j - 1]; + if (root->val == needle[j]) j++; + return kmpSearch(root->left, j) || kmpSearch(root->right, j); + } -public: - bool isSubPath(ListNode *head, TreeNode *root) { - if (!head || !root) return false; + public: + bool isSubPath(ListNode *head, TreeNode *root) { + if (!head || !root) return false; - needle.resize(0); - for (ListNode *t = head; t; t = t->next) needle.push_back(t->val); + needle.resize(0); + for (ListNode *t = head; t; t = t->next) + needle.push_back(t->val); - computeKMPTable(needle); - return kmpSearch(root, 0); - } + computeKMPTable(needle); + return kmpSearch(root, 0); + } }; diff --git a/Problems/1372.cpp b/Problems/1372.cpp @@ -1,19 +1,19 @@ class Solution { - int res = 0; + int res = 0; - int dfs(TreeNode *root, bool zig) { - if (!root) return -1; + int dfs(TreeNode *root, bool zig) { + if (!root) return -1; - int left = dfs(root->left, false); - int right = dfs(root->right, true); - res = max(res, max(left + 1, right + 1)); + int left = dfs(root->left, false); + int right = dfs(root->right, true); + res = max(res, max(left + 1, right + 1)); - return zig ? left + 1 : right + 1; - } + return zig ? left + 1 : right + 1; + } -public: - int longestZigZag(TreeNode *root) { - dfs(root, false); - return res; - } + public: + int longestZigZag(TreeNode *root) { + dfs(root, false); + return res; + } }; diff --git a/Problems/1373.cpp b/Problems/1373.cpp @@ -1,48 +1,47 @@ class Solution { - struct record { - int sum, mini, maxi; - record(int su = 0, int mi = INT_MAX, int ma = INT_MIN) - : sum(su), mini(mi), maxi(ma) {} - }; + struct record { + int sum, mini, maxi; + record(int su = 0, int mi = INT_MAX, int ma = INT_MIN) : sum(su), mini(mi), maxi(ma) {} + }; -public: - int maxSumBST(TreeNode *root) { - unordered_map<TreeNode *, record> um; - stack<TreeNode *> st; + public: + int maxSumBST(TreeNode *root) { + unordered_map<TreeNode *, record> um; + stack<TreeNode *> st; - int res = 0; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - st.pop(); - if (um.count(root)) { - record &r = um[root]; - if (root->left) { - if (root->val <= um[root->left].maxi) { - r.mini = INT_MIN, r.maxi = INT_MAX; - continue; - } else - r.sum += um[root->left].sum; - } + int res = 0; + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + st.pop(); + if (um.count(root)) { + record &r = um[root]; + if (root->left) { + if (root->val <= um[root->left].maxi) { + r.mini = INT_MIN, r.maxi = INT_MAX; + continue; + } else + r.sum += um[root->left].sum; + } - if (root->right) { - if (root->val >= um[root->right].mini) { - r.mini = INT_MIN, r.maxi = INT_MAX; - continue; - } else - r.sum += um[root->right].sum; - } + if (root->right) { + if (root->val >= um[root->right].mini) { + r.mini = INT_MIN, r.maxi = INT_MAX; + continue; + } else + r.sum += um[root->right].sum; + } - res = max(res, r.sum); - r.mini = root->left ? um[root->left].mini : root->val; - r.maxi = root->right ? um[root->right].maxi : root->val; - continue; - } - um.insert({root, root->val}); - st.push(root); - if (root->left) st.push(root->left); - if (root->right) st.push(root->right); + res = max(res, r.sum); + r.mini = root->left ? um[root->left].mini : root->val; + r.maxi = root->right ? um[root->right].maxi : root->val; + continue; + } + um.insert({root, root->val}); + st.push(root); + if (root->left) st.push(root->left); + if (root->right) st.push(root->right); + } + return res; } - return res; - } }; diff --git a/Problems/1376.cpp b/Problems/1376.cpp @@ -1,26 +1,25 @@ class Solution { -public: - int numOfMinutes(int n, int headID, const vector<int> &manager, - const vector<int> &informTime) { - vector<int> time(n, -1); - time[headID] = 0; - int res = 0, crnt, sum1, sum2; - for (int i = 0; i < n; i++) { - if (informTime[i] != 0) continue; - crnt = i, sum1 = 0; - while (time[crnt] == -1) { - sum1 += informTime[crnt]; - crnt = manager[crnt]; - } - res = max(res, sum1 += time[crnt]); - crnt = i, sum2 = 0; - while (time[crnt] == -1) { - time[crnt] = sum1 - sum2; - sum2 += informTime[crnt]; - crnt = manager[crnt]; - } - } + public: + int numOfMinutes(int n, int headID, const vector<int> &manager, const vector<int> &informTime) { + vector<int> time(n, -1); + time[headID] = 0; + int res = 0, crnt, sum1, sum2; + for (int i = 0; i < n; i++) { + if (informTime[i] != 0) continue; + crnt = i, sum1 = 0; + while (time[crnt] == -1) { + sum1 += informTime[crnt]; + crnt = manager[crnt]; + } + res = max(res, sum1 += time[crnt]); + crnt = i, sum2 = 0; + while (time[crnt] == -1) { + time[crnt] = sum1 - sum2; + sum2 += informTime[crnt]; + crnt = manager[crnt]; + } + } - return res + informTime[headID]; - } + return res + informTime[headID]; + } }; diff --git a/Problems/1379.cpp b/Problems/1379.cpp @@ -1,23 +1,22 @@ class Solution { -public: - TreeNode *getTargetCopy(TreeNode *original, TreeNode *cloned, - TreeNode *target) { - if (!original || !cloned || !target) return nullptr; + public: + TreeNode *getTargetCopy(TreeNode *original, TreeNode *cloned, TreeNode *target) { + if (!original || !cloned || !target) return nullptr; - stack<pair<TreeNode *, TreeNode *>> st; + stack<pair<TreeNode *, TreeNode *>> st; - st.push({original, cloned}); - while (!st.empty()) { - TreeNode *original = st.top().first; - TreeNode *cloned = st.top().second; - st.pop(); + st.push({original, cloned}); + while (!st.empty()) { + TreeNode *original = st.top().first; + TreeNode *cloned = st.top().second; + st.pop(); - if (original == target) return cloned; + if (original == target) return cloned; - if (original->left) st.push({original->left, cloned->left}); - if (original->right) st.push({original->right, cloned->right}); - } + if (original->left) st.push({original->left, cloned->left}); + if (original->right) st.push({original->right, cloned->right}); + } - return nullptr; - } + return nullptr; + } }; diff --git a/Problems/1381.cpp b/Problems/1381.cpp @@ -1,21 +1,22 @@ class CustomStack { - vector<int> st; - int size = 0; + vector<int> st; + int size = 0; -public: - CustomStack(int maxSize) : st(maxSize) {} + public: + CustomStack(int maxSize) : st(maxSize) {} - void push(int x) { - if (size == st.size()) return; - st[size++] = x; - } + void push(int x) { + if (size == st.size()) return; + st[size++] = x; + } - int pop() { - if (size == 0) return -1; - return st[--size]; - } + int pop() { + if (size == 0) return -1; + return st[--size]; + } - void increment(int k, int val) { - for (int i = 0; i < min(k, size); i++) st[i] += val; - } + void increment(int k, int val) { + for (int i = 0; i < min(k, size); i++) + st[i] += val; + } }; diff --git a/Problems/1382.cpp b/Problems/1382.cpp @@ -1,44 +1,42 @@ class Solution { - struct record { - TreeNode *root; - int low, high; - record(TreeNode *root, int low, int high) - : root(root), low(low), high(high) {} - }; + struct record { + TreeNode *root; + int low, high; + record(TreeNode *root, int low, int high) : root(root), low(low), high(high) {} + }; -public: - TreeNode *balanceBST(TreeNode *root) { - vector<TreeNode *> nums; + public: + TreeNode *balanceBST(TreeNode *root) { + vector<TreeNode *> nums; - { - stack<TreeNode *> st; - while (true) { - while (root) { - st.push(root); - root = root->left; + { + stack<TreeNode *> st; + while (true) { + while (root) { + st.push(root); + root = root->left; + } + if (st.empty()) break; + root = st.top(), st.pop(); + nums.push_back(root); + root = root->right; + } } - if (st.empty()) break; - root = st.top(), st.pop(); - nums.push_back(root); - root = root->right; - } - } - stack<record> st; - TreeNode *head = new TreeNode(INT_MIN), *t; - st.push({head, 0, (int)nums.size() - 1}); - while (!st.empty()) { - record r = st.top(); - st.pop(); - while (r.low <= r.high) { - int mid = r.low + (r.high - r.low) / 2; - nums[mid]->left = nums[mid]->right = nullptr; - (nums[mid]->val >= r.root->val ? r.root->right : r.root->left) = t = - nums[mid]; - st.push({r.root = t, mid + 1, r.high}); - r.high = mid - 1; - } + stack<record> st; + TreeNode *head = new TreeNode(INT_MIN), *t; + st.push({head, 0, (int)nums.size() - 1}); + while (!st.empty()) { + record r = st.top(); + st.pop(); + while (r.low <= r.high) { + int mid = r.low + (r.high - r.low) / 2; + nums[mid]->left = nums[mid]->right = nullptr; + (nums[mid]->val >= r.root->val ? r.root->right : r.root->left) = t = nums[mid]; + st.push({r.root = t, mid + 1, r.high}); + r.high = mid - 1; + } + } + return head->right; } - return head->right; - } }; diff --git a/Problems/1396.cpp b/Problems/1396.cpp @@ -1,23 +1,21 @@ class UndergroundSystem { - unordered_map<int, pair<string, int>> check_in; - unordered_map<string, pair<int, int>> average; + unordered_map<int, pair<string, int>> check_in; + unordered_map<string, pair<int, int>> average; -public: - UndergroundSystem() {} + public: + UndergroundSystem() {} - void checkIn(int id, const string &stationName, int t) { - check_in[id] = {stationName, t}; - } + void checkIn(int id, const string &stationName, int t) { check_in[id] = {stationName, t}; } - void checkOut(int id, const string &stationName, int t) { - auto &[name, time] = check_in[id]; - auto &p = average[name + "-" + stationName]; - p.second += t - time; - p.first++; - } + void checkOut(int id, const string &stationName, int t) { + auto &[name, time] = check_in[id]; + auto &p = average[name + "-" + stationName]; + p.second += t - time; + p.first++; + } - double getAverageTime(const string &startStation, const string &endStation) { - auto &p = average[startStation + "-" + endStation]; - return (double)p.second / p.first; - } + double getAverageTime(const string &startStation, const string &endStation) { + auto &p = average[startStation + "-" + endStation]; + return (double)p.second / p.first; + } }; diff --git a/Problems/1402.cpp b/Problems/1402.cpp @@ -1,12 +1,13 @@ class Solution { -public: - int maxSatisfaction(vector<int> &satisf) { - sort(satisf.begin(), satisf.end()); - if (satisf.back() <= 0) return 0; + public: + int maxSatisfaction(vector<int> &satisf) { + sort(satisf.begin(), satisf.end()); + if (satisf.back() <= 0) return 0; - int j = satisf.size() - 1, crnt = 0, sum = 0, res = 0; - for (; j >= 0; j--) res = max(res, crnt += sum += satisf[j]); + int j = satisf.size() - 1, crnt = 0, sum = 0, res = 0; + for (; j >= 0; j--) + res = max(res, crnt += sum += satisf[j]); - return res; - } + return res; + } }; diff --git a/Problems/1406.cpp b/Problems/1406.cpp @@ -1,18 +1,19 @@ class Solution { -public: - string stoneGameIII(const vector<int> &stoneValue) { - int n = stoneValue.size(); - vector<int> sum(n + 1, 0), dp(n + 1, 0); + public: + string stoneGameIII(const vector<int> &stoneValue) { + int n = stoneValue.size(); + vector<int> sum(n + 1, 0), dp(n + 1, 0); - for (int i = n - 1; i >= 0; i--) sum[i] = sum[i + 1] + stoneValue[i]; + for (int i = n - 1; i >= 0; i--) + sum[i] = sum[i + 1] + stoneValue[i]; - for (int i = n - 1; i >= 0; i--) { - dp[i] = stoneValue[i] + sum[i + 1] - dp[i + 1]; - for (int k = i + 1; k < i + 3 && k < n; k++) { - dp[i] = max(dp[i], sum[i] - dp[k + 1]); - } + for (int i = n - 1; i >= 0; i--) { + dp[i] = stoneValue[i] + sum[i + 1] - dp[i + 1]; + for (int k = i + 1; k < i + 3 && k < n; k++) { + dp[i] = max(dp[i], sum[i] - dp[k + 1]); + } + } + dp[0] = dp[0] * 2 - sum[0]; + return dp[0] == 0 ? "Tie" : (dp[0] > 0 ? "Alice" : "Bob"); } - dp[0] = dp[0] * 2 - sum[0]; - return dp[0] == 0 ? "Tie" : (dp[0] > 0 ? "Alice" : "Bob"); - } }; diff --git a/Problems/1409.cpp b/Problems/1409.cpp @@ -1,15 +1,16 @@ class Solution { -public: - vector<int> processQueries(const vector<int> &queries, int m) { - vector<int> vec(m), res; - res.reserve(queries.size()); - iota(vec.begin(), vec.end(), 1); - for (const int query : queries) { - int i = 0, tmp = query; - while (vec[i] != query) swap(tmp, vec[i++]); - vec[i] = tmp; - res.push_back(i); + public: + vector<int> processQueries(const vector<int> &queries, int m) { + vector<int> vec(m), res; + res.reserve(queries.size()); + iota(vec.begin(), vec.end(), 1); + for (const int query : queries) { + int i = 0, tmp = query; + while (vec[i] != query) + swap(tmp, vec[i++]); + vec[i] = tmp; + res.push_back(i); + } + return res; } - return res; - } }; diff --git a/Problems/1415.cpp b/Problems/1415.cpp @@ -1,26 +1,26 @@ class Solution { - vector<string> res; - string crnt; + vector<string> res; + string crnt; - void rec(int n, int k, char last = 'x') { - if (res.size() == k) return; - if (crnt.size() == n) { - res.push_back(crnt); - return; + void rec(int n, int k, char last = 'x') { + if (res.size() == k) return; + if (crnt.size() == n) { + res.push_back(crnt); + return; + } + crnt.push_back(' '); + for (char c = 'a'; c <= 'c'; c++) { + if (c == last) continue; + crnt.back() = c; + rec(n, k, c); + } + crnt.pop_back(); } - crnt.push_back(' '); - for (char c = 'a'; c <= 'c'; c++) { - if (c == last) continue; - crnt.back() = c; - rec(n, k, c); - } - crnt.pop_back(); - } -public: - string getHappyString(int n, int k) { - if (k > 3 * (1 << n - 1)) return ""; - rec(n, k); - return res.back(); - } + public: + string getHappyString(int n, int k) { + if (k > 3 * (1 << n - 1)) return ""; + rec(n, k); + return res.back(); + } }; diff --git a/Problems/1416.cpp b/Problems/1416.cpp @@ -1,23 +1,23 @@ class Solution { - static const int mod = 1E9 + 7; - static const int size = 1E5 + 1; - int dp[size]; + static const int mod = 1E9 + 7; + static const int size = 1E5 + 1; + int dp[size]; -public: - Solution() { memset(dp, 0xFF, sizeof(dp)); } + public: + Solution() { memset(dp, 0xFF, sizeof(dp)); } - int numberOfArrays(const string &s, int k, int crnt = 0) { - if (crnt >= s.size()) return 1; - if (s[crnt] == '0') return 0; - if (dp[crnt] != -1) return dp[crnt]; + int numberOfArrays(const string &s, int k, int crnt = 0) { + if (crnt >= s.size()) return 1; + if (s[crnt] == '0') return 0; + if (dp[crnt] != -1) return dp[crnt]; - long long num = 0, res = 0; - for (int i = crnt; i < s.size(); i++) { - num = num * 10 + (s[i] - '0'); - if (num > k) break; - res = (res + numberOfArrays(s, k, i + 1)) % mod; - } + long long num = 0, res = 0; + for (int i = crnt; i < s.size(); i++) { + num = num * 10 + (s[i] - '0'); + if (num > k) break; + res = (res + numberOfArrays(s, k, i + 1)) % mod; + } - return dp[crnt] = res; - } + return dp[crnt] = res; + } }; diff --git a/Problems/1418.cpp b/Problems/1418.cpp @@ -1,34 +1,36 @@ class Solution { -public: - vector<vector<string>> displayTable(vector<vector<string>> &orders) { - map<int, vector<string>> tables; - vector<vector<string>> res; - set<string> foods; + public: + vector<vector<string>> displayTable(vector<vector<string>> &orders) { + map<int, vector<string>> tables; + vector<vector<string>> res; + set<string> foods; - for (const auto &order : orders) { - tables[stoi(order[1])].push_back(order[2]); - foods.insert(order[2]); - } + for (const auto &order : orders) { + tables[stoi(order[1])].push_back(order[2]); + foods.insert(order[2]); + } - unordered_map<string, int> pos; + unordered_map<string, int> pos; - int j = 1; - res.push_back({{"Table"}}); - for (auto &food : foods) { - res[0].push_back(food); - pos[food] = j++; - } + int j = 1; + res.push_back({{"Table"}}); + for (auto &food : foods) { + res[0].push_back(food); + pos[food] = j++; + } - for (auto &[table, foods] : tables) { - vector<int> row(res[0].size(), 0); - vector<string> rows; - rows.reserve(res[0].size()); - for (const auto &food : foods) row[pos[food]]++; - row[0] = table; - for (int r : row) rows.push_back(to_string(r)); - res.push_back(rows); - } + for (auto &[table, foods] : tables) { + vector<int> row(res[0].size(), 0); + vector<string> rows; + rows.reserve(res[0].size()); + for (const auto &food : foods) + row[pos[food]]++; + row[0] = table; + for (int r : row) + rows.push_back(to_string(r)); + res.push_back(rows); + } - return res; - } + return res; + } }; diff --git a/Problems/1425.cpp b/Problems/1425.cpp @@ -1,15 +1,16 @@ class Solution { -public: - int constrainedSubsetSum(vector<int> &nums, int k) { - deque<int> q; - int res = nums[0]; - for (int i = 0; i < nums.size(); ++i) { - nums[i] += !q.empty() ? q.front() : 0; - res = max(res, nums[i]); - while (!q.empty() && nums[i] > q.back()) q.pop_back(); - if (nums[i] > 0) q.push_back(nums[i]); - if (i >= k && !q.empty() && q.front() == nums[i - k]) q.pop_front(); + public: + int constrainedSubsetSum(vector<int> &nums, int k) { + deque<int> q; + int res = nums[0]; + for (int i = 0; i < nums.size(); ++i) { + nums[i] += !q.empty() ? q.front() : 0; + res = max(res, nums[i]); + while (!q.empty() && nums[i] > q.back()) + q.pop_back(); + if (nums[i] > 0) q.push_back(nums[i]); + if (i >= k && !q.empty() && q.front() == nums[i - k]) q.pop_front(); + } + return res; } - return res; - } }; diff --git a/Problems/1431.cpp b/Problems/1431.cpp @@ -1,10 +1,10 @@ class Solution { -public: - vector<bool> kidsWithCandies(vector<int> &candies, int extraCandies) { - int maxi = *max_element(candies.begin(), candies.end()); - vector<bool> res(candies.size()); - for (int i = 0; i < candies.size(); i++) - res[i] = (maxi - candies[i]) <= extraCandies; - return res; - } + public: + vector<bool> kidsWithCandies(vector<int> &candies, int extraCandies) { + int maxi = *max_element(candies.begin(), candies.end()); + vector<bool> res(candies.size()); + for (int i = 0; i < candies.size(); i++) + res[i] = (maxi - candies[i]) <= extraCandies; + return res; + } }; diff --git a/Problems/1436.cpp b/Problems/1436.cpp @@ -1,13 +1,13 @@ class Solution { -public: - string destCity(vector<vector<string>> &paths) { - unordered_map<string, int> um; - for (auto &path : paths) { - um[path[0]]--; - um[path[1]]++; + public: + string destCity(vector<vector<string>> &paths) { + unordered_map<string, int> um; + for (auto &path : paths) { + um[path[0]]--; + um[path[1]]++; + } + for (auto &[k, v] : um) + if (v == 1) return k; + return ""; } - for (auto &[k, v] : um) - if (v == 1) return k; - return ""; - } }; diff --git a/Problems/1438.cpp b/Problems/1438.cpp @@ -1,18 +1,20 @@ class Solution { -public: - int longestSubarray(vector<int> &nums, int limit) { - deque<int> maxd, mind; - int i = 0, j; - for (j = 0; j < nums.size(); ++j) { - while (!maxd.empty() && nums[j] > maxd.back()) maxd.pop_back(); - while (!mind.empty() && nums[j] < mind.back()) mind.pop_back(); - maxd.push_back(nums[j]), mind.push_back(nums[j]); - if (maxd.front() - mind.front() > limit) { - if (maxd.front() == nums[i]) maxd.pop_front(); - if (mind.front() == nums[i]) mind.pop_front(); - i++; - } + public: + int longestSubarray(vector<int> &nums, int limit) { + deque<int> maxd, mind; + int i = 0, j; + for (j = 0; j < nums.size(); ++j) { + while (!maxd.empty() && nums[j] > maxd.back()) + maxd.pop_back(); + while (!mind.empty() && nums[j] < mind.back()) + mind.pop_back(); + maxd.push_back(nums[j]), mind.push_back(nums[j]); + if (maxd.front() - mind.front() > limit) { + if (maxd.front() == nums[i]) maxd.pop_front(); + if (mind.front() == nums[i]) mind.pop_front(); + i++; + } + } + return j - i; } - return j - i; - } }; diff --git a/Problems/1441.cpp b/Problems/1441.cpp @@ -1,15 +1,15 @@ class Solution { -public: - vector<string> buildArray(vector<int> &target, int n) { - vector<string> res; - int stream = 1; - for (int t : target) { - while (stream++ != t) { - res.push_back("Push"); - res.push_back("Pop"); - } - res.push_back("Push"); + public: + vector<string> buildArray(vector<int> &target, int n) { + vector<string> res; + int stream = 1; + for (int t : target) { + while (stream++ != t) { + res.push_back("Push"); + res.push_back("Pop"); + } + res.push_back("Push"); + } + return res; } - return res; - } }; diff --git a/Problems/1442.cpp b/Problems/1442.cpp @@ -1,18 +1,19 @@ class Solution { -public: - int countTriplets(const vector<int> &arr) { - static int left[301]; - left[0] = 0; - int n = arr.size(), res = 0; + public: + int countTriplets(const vector<int> &arr) { + static int left[301]; + left[0] = 0; + int n = arr.size(), res = 0; - for (int i = 0, acc = 0; i < n; i++) left[i + 1] = acc ^= arr[i]; + for (int i = 0, acc = 0; i < n; i++) + left[i + 1] = acc ^= arr[i]; - for (int i = 0; i < n; i++) { - for (int j = i + 1; j < n; j++) { - if (left[i] == left[j + 1]) res += j - i; - } - } + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (left[i] == left[j + 1]) res += j - i; + } + } - return res; - } + return res; + } }; diff --git a/Problems/1443.cpp b/Problems/1443.cpp @@ -1,43 +1,43 @@ class Solution { -public: - int minTime(int n, vector<vector<int>> &edges, vector<bool> &hasApple) { - vector<vector<int>> adj(n, vector<int>()); - for (auto &e : edges) { - adj[e[0]].push_back(e[1]); - adj[e[1]].push_back(e[0]); - } + public: + int minTime(int n, vector<vector<int>> &edges, vector<bool> &hasApple) { + vector<vector<int>> adj(n, vector<int>()); + for (auto &e : edges) { + adj[e[0]].push_back(e[1]); + adj[e[1]].push_back(e[0]); + } - stack<pair<int, int>> st; - int res = 0; + stack<pair<int, int>> st; + int res = 0; - st.push({0, -1}); - while (!st.empty()) { - if (st.top().first == -1) { - st.pop(); + st.push({0, -1}); + while (!st.empty()) { + if (st.top().first == -1) { + st.pop(); - auto [crnt, par] = st.top(); - st.pop(); - int count = 0; + auto [crnt, par] = st.top(); + st.pop(); + int count = 0; - for (int c : adj[crnt]) { - if (c == par) continue; - count += hasApple[c]; - } + for (int c : adj[crnt]) { + if (c == par) continue; + count += hasApple[c]; + } - res += count; - hasApple[crnt] = hasApple[crnt] || count; - continue; - } + res += count; + hasApple[crnt] = hasApple[crnt] || count; + continue; + } - auto [crnt, par] = st.top(); - st.push({-1, -1}); + auto [crnt, par] = st.top(); + st.push({-1, -1}); - for (int c : adj[crnt]) { - if (c == par) continue; - st.push({c, crnt}); - } - } + for (int c : adj[crnt]) { + if (c == par) continue; + st.push({c, crnt}); + } + } - return res * 2; - } + return res * 2; + } }; diff --git a/Problems/1444.cpp b/Problems/1444.cpp @@ -1,37 +1,36 @@ class Solution { - int n, m, mod = 1e9 + 7; - vector<vector<int>> count; - vector<vector<vector<int>>> dp = vector(10, vector(50, vector(50, -1))); + int n, m, mod = 1e9 + 7; + vector<vector<int>> count; + vector<vector<vector<int>>> dp = vector(10, vector(50, vector(50, -1))); - int rec(int row, int col, int left) { - if (count[row][col] == 0) return 0; - if (left == 0) return 1; - if (dp[left][row][col] != -1) return dp[left][row][col]; + int rec(int row, int col, int left) { + if (count[row][col] == 0) return 0; + if (left == 0) return 1; + if (dp[left][row][col] != -1) return dp[left][row][col]; - int &res = dp[left][row][col] = 0; - for (int i = row; i < n - 1; i++) { - if (count[row][col] - count[i + 1][col] <= 0) continue; - res = (res + rec(i + 1, col, left - 1)) % mod; - } + int &res = dp[left][row][col] = 0; + for (int i = row; i < n - 1; i++) { + if (count[row][col] - count[i + 1][col] <= 0) continue; + res = (res + rec(i + 1, col, left - 1)) % mod; + } - for (int i = col; i < m - 1; i++) { - if (count[row][col] - count[row][i + 1] <= 0) continue; - res = (res + rec(row, i + 1, left - 1)) % mod; - } + for (int i = col; i < m - 1; i++) { + if (count[row][col] - count[row][i + 1] <= 0) continue; + res = (res + rec(row, i + 1, left - 1)) % mod; + } - return res; - } + return res; + } -public: - int ways(vector<string> &pizza, int k) { - n = pizza.size(), m = pizza[0].size(); - count = vector<vector<int>>(n + 1, vector<int>(m + 1, 0)); + public: + int ways(vector<string> &pizza, int k) { + n = pizza.size(), m = pizza[0].size(); + count = vector<vector<int>>(n + 1, vector<int>(m + 1, 0)); - for (int i = n - 1; i >= 0; i--) - for (int j = m - 1; j >= 0; j--) - count[i][j] = count[i + 1][j] + count[i][j + 1] - count[i + 1][j + 1] + - (pizza[i][j] == 'A'); + for (int i = n - 1; i >= 0; i--) + for (int j = m - 1; j >= 0; j--) + count[i][j] = count[i + 1][j] + count[i][j + 1] - count[i + 1][j + 1] + (pizza[i][j] == 'A'); - return rec(0, 0, k - 1); - } + return rec(0, 0, k - 1); + } }; diff --git a/Problems/1448.cpp b/Problems/1448.cpp @@ -1,22 +1,20 @@ class Solution { -public: - int goodNodes(TreeNode *root) { - queue<pair<TreeNode *, int>> q({ - {root, INT_MIN} - }); - int res = 0; + public: + int goodNodes(TreeNode *root) { + queue<pair<TreeNode *, int>> q({{root, INT_MIN}}); + int res = 0; - while (!q.empty()) { - const auto [root, maxi] = q.front(); - q.pop(); - if (root->val >= maxi) res++; - if (root->left) q.push({root->left, max(maxi, root->val)}); - if (root->right) q.push({root->right, max(maxi, root->val)}); + while (!q.empty()) { + const auto [root, maxi] = q.front(); + q.pop(); + if (root->val >= maxi) res++; + if (root->left) q.push({root->left, max(maxi, root->val)}); + if (root->right) q.push({root->right, max(maxi, root->val)}); - // For some reason it increases runtime and decreases memory usage - // Must be leetcode error... - root->left = root->right = nullptr; + // For some reason it increases runtime and decreases memory usage + // Must be leetcode error... + root->left = root->right = nullptr; + } + return res; } - return res; - } }; diff --git a/Problems/1456.cpp b/Problems/1456.cpp @@ -1,21 +1,19 @@ class Solution { - bool isVowel(char c) { - return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; - } + bool isVowel(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; } -public: - int maxVowels(string s, int k) { - int i, cnt = 0; - for (i = 0; i < k; i++) - if (isVowel(s[i])) cnt++; + public: + int maxVowels(string s, int k) { + int i, cnt = 0; + for (i = 0; i < k; i++) + if (isVowel(s[i])) cnt++; - int maxi = cnt; - for (; i < s.size(); i++) { - if (isVowel(s[i - k])) cnt--; - if (isVowel(s[i])) cnt++; - maxi = max(maxi, cnt); - } + int maxi = cnt; + for (; i < s.size(); i++) { + if (isVowel(s[i - k])) cnt--; + if (isVowel(s[i])) cnt++; + maxi = max(maxi, cnt); + } - return maxi; - } + return maxi; + } }; diff --git a/Problems/1462.cpp b/Problems/1462.cpp @@ -1,103 +1,104 @@ // DFS class Solution { -public: - vector<bool> checkIfPrerequisite(int numCourses, - vector<vector<int>> &prerequisites, - vector<vector<int>> &queries) { - vector<vector<int>> adj(numCourses); - vector<unordered_set<int>> pre(numCourses); + public: + vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>> &prerequisites, + vector<vector<int>> &queries) { + vector<vector<int>> adj(numCourses); + vector<unordered_set<int>> pre(numCourses); - for (auto &p : prerequisites) adj[p[0]].push_back(p[1]); + for (auto &p : prerequisites) + adj[p[0]].push_back(p[1]); - for (int i = 0; i < numCourses; i++) { - unordered_set<int> visited; - stack<int> st; - st.push(i); - visited.insert(i); - while (!st.empty()) { - int crnt = st.top(); - st.pop(); - for (int &c : adj[crnt]) { - if (visited.count(c)) continue; - visited.insert(c); - pre[c].insert(i); - st.push(c); + for (int i = 0; i < numCourses; i++) { + unordered_set<int> visited; + stack<int> st; + st.push(i); + visited.insert(i); + while (!st.empty()) { + int crnt = st.top(); + st.pop(); + for (int &c : adj[crnt]) { + if (visited.count(c)) continue; + visited.insert(c); + pre[c].insert(i); + st.push(c); + } + } } - } - } - vector<bool> res; - for (auto &p : queries) res.push_back(pre[p[1]].count(p[0])); - return res; - } + vector<bool> res; + for (auto &p : queries) + res.push_back(pre[p[1]].count(p[0])); + return res; + } }; // Topological sort with dependency propagation class Solution { + public: + vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>> &prerequisites, + vector<vector<int>> &queries) { + vector<unordered_set<int>> pre(numCourses); + vector<vector<int>> adj(numCourses); + vector<int> count(numCourses); + + for (auto &p : prerequisites) { + adj[p[0]].push_back(p[1]); + count[p[1]]++; + } + + queue<int> q; + for (int i = 0; i < numCourses; i++) + if (!count[i]) q.push(i); + + while (!q.empty()) { + int crnt = q.front(); + q.pop(); + for (int &c : adj[crnt]) { + pre[c].insert(crnt); + pre[c].insert(pre[crnt].begin(), pre[crnt].end()); + if (!--count[c]) q.push(c); + } + } + + vector<bool> res; + for (auto &p : queries) + res.push_back(pre[p[1]].count(p[0])); + return res; + } +}; + +// Topological sort using bitseclass Solution { public: - vector<bool> checkIfPrerequisite(int numCourses, - vector<vector<int>> &prerequisites, - vector<vector<int>> &queries) { - vector<unordered_set<int>> pre(numCourses); +vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>> &prerequisites, + vector<vector<int>> &queries) { + vector<bitset<100>> pre(numCourses); vector<vector<int>> adj(numCourses); vector<int> count(numCourses); for (auto &p : prerequisites) { - adj[p[0]].push_back(p[1]); - count[p[1]]++; + adj[p[0]].push_back(p[1]); + count[p[1]]++; } queue<int> q; for (int i = 0; i < numCourses; i++) - if (!count[i]) q.push(i); + if (!count[i]) q.push(i); while (!q.empty()) { - int crnt = q.front(); - q.pop(); - for (int &c : adj[crnt]) { - pre[c].insert(crnt); - pre[c].insert(pre[crnt].begin(), pre[crnt].end()); - if (!--count[c]) q.push(c); - } + int crnt = q.front(); + q.pop(); + for (int &c : adj[crnt]) { + pre[c].set(crnt); + pre[c] |= pre[crnt]; + if (!--count[c]) q.push(c); + } } vector<bool> res; - for (auto &p : queries) res.push_back(pre[p[1]].count(p[0])); + for (auto &p : queries) + res.push_back(pre[p[1]][p[0]]); return res; - } -}; - -// Topological sort using bitseclass Solution { -public: -vector<bool> checkIfPrerequisite(int numCourses, - vector<vector<int>> &prerequisites, - vector<vector<int>> &queries) { - vector<bitset<100>> pre(numCourses); - vector<vector<int>> adj(numCourses); - vector<int> count(numCourses); - - for (auto &p : prerequisites) { - adj[p[0]].push_back(p[1]); - count[p[1]]++; - } - - queue<int> q; - for (int i = 0; i < numCourses; i++) - if (!count[i]) q.push(i); - - while (!q.empty()) { - int crnt = q.front(); - q.pop(); - for (int &c : adj[crnt]) { - pre[c].set(crnt); - pre[c] |= pre[crnt]; - if (!--count[c]) q.push(c); - } - } - - vector<bool> res; - for (auto &p : queries) res.push_back(pre[p[1]][p[0]]); - return res; } } ; diff --git a/Problems/1466.cpp b/Problems/1466.cpp @@ -1,31 +1,31 @@ class Solution { -public: - int minReorder(int n, vector<vector<int>> &connections) { - unordered_set<string> us; - vector<bool> visited(n, false); - vector<vector<int>> adj(n, vector<int>()); + public: + int minReorder(int n, vector<vector<int>> &connections) { + unordered_set<string> us; + vector<bool> visited(n, false); + vector<vector<int>> adj(n, vector<int>()); - for (auto &e : connections) { - us.insert(to_string(e[0]) + " " + to_string(e[1])); - adj[e[0]].push_back(e[1]); - adj[e[1]].push_back(e[0]); - } + for (auto &e : connections) { + us.insert(to_string(e[0]) + " " + to_string(e[1])); + adj[e[0]].push_back(e[1]); + adj[e[1]].push_back(e[0]); + } - int res = 0; + int res = 0; - stack<int> st; - st.push(0); - visited[0] = true; - while (!st.empty()) { - int root = st.top(); - st.pop(); - for (auto c : adj[root]) - if (!visited[c]) { - if (!us.count(to_string(c) + " " + to_string(root))) res++; - visited[c] = true; - st.push(c); + stack<int> st; + st.push(0); + visited[0] = true; + while (!st.empty()) { + int root = st.top(); + st.pop(); + for (auto c : adj[root]) + if (!visited[c]) { + if (!us.count(to_string(c) + " " + to_string(root))) res++; + visited[c] = true; + st.push(c); + } } + return res; } - return res; - } }; diff --git a/Problems/1470.cpp b/Problems/1470.cpp @@ -1,10 +1,10 @@ class Solution { -public: - vector<int> shuffle(vector<int>& nums, int n) { - vector<int> res(n*2); - for(int i=0; i<n; i++) { - res[2*i] = nums[i]; - res[2*i+1] = nums[n+i]; + public: + vector<int> shuffle(vector<int> &nums, int n) { + vector<int> res(n * 2); + for (int i = 0; i < n; i++) { + res[2 * i] = nums[i]; + res[2 * i + 1] = nums[n + i]; } return res; } diff --git a/Problems/1472.cpp b/Problems/1472.cpp @@ -1,31 +1,33 @@ class BrowserHistory { - struct Node { - Node *next, *prev; - string val; - Node(string val = "#", Node *prev = nullptr, Node *next = nullptr) - : val(val), prev(prev), next(next) {} - }; - Node *head = nullptr, *tail = nullptr, *crnt = nullptr; + struct Node { + Node *next, *prev; + string val; + Node(string val = "#", Node *prev = nullptr, Node *next = nullptr) + : val(val), prev(prev), next(next) {} + }; + Node *head = nullptr, *tail = nullptr, *crnt = nullptr; -public: - BrowserHistory(string homepage) { crnt = head = tail = new Node(homepage); } + public: + BrowserHistory(string homepage) { crnt = head = tail = new Node(homepage); } - void visit(string url) { - for (Node *t = tail->next; t;) { - Node *tmp = t; - t = t->next; - delete tmp; + void visit(string url) { + for (Node *t = tail->next; t;) { + Node *tmp = t; + t = t->next; + delete tmp; + } + crnt = tail = tail->next = new Node(url, tail, nullptr); } - crnt = tail = tail->next = new Node(url, tail, nullptr); - } - string back(int steps) { - while (steps-- && crnt->prev) tail = crnt = crnt->prev; - return crnt->val; - } + string back(int steps) { + while (steps-- && crnt->prev) + tail = crnt = crnt->prev; + return crnt->val; + } - string forward(int steps) { - while (steps-- && crnt->next) tail = crnt = crnt->next; - return crnt->val; - } + string forward(int steps) { + while (steps-- && crnt->next) + tail = crnt = crnt->next; + return crnt->val; + } }; diff --git a/Problems/1476.cpp b/Problems/1476.cpp @@ -1,14 +1,13 @@ class SubrectangleQueries { - vector<vector<int>>& rectangle; -public: - SubrectangleQueries(vector<vector<int>>& rectangle): rectangle(rectangle) {} + vector<vector<int>> &rectangle; + + public: + SubrectangleQueries(vector<vector<int>> &rectangle) : rectangle(rectangle) {} void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) { - for(int i=row1; i<=row2; i++) - for(int j=col1; j<=col2; j++) + for (int i = row1; i <= row2; i++) + for (int j = col1; j <= col2; j++) rectangle[i][j] = newValue; } - int getValue(int row, int col) { - return rectangle[row][col]; - } + int getValue(int row, int col) { return rectangle[row][col]; } }; diff --git a/Problems/1480.cpp b/Problems/1480.cpp @@ -1,19 +1,20 @@ class Solution { -public: - vector<int> runningSum(vector<int> &nums) { - vector<int> res; - int acc = 0; - for (auto i : nums) res.push_back(acc += i); - return res; - } + public: + vector<int> runningSum(vector<int> &nums) { + vector<int> res; + int acc = 0; + for (auto i : nums) + res.push_back(acc += i); + return res; + } }; // using lambda function class Solution { -public: - vector<int> runningSum(vector<int> &nums) { - int acc = 0; - for_each(nums.begin(), nums.end(), [&acc](int &a) { a = acc += a; }); - return nums; - } + public: + vector<int> runningSum(vector<int> &nums) { + int acc = 0; + for_each(nums.begin(), nums.end(), [&acc](int &a) { a = acc += a; }); + return nums; + } }; diff --git a/Problems/1489.cpp b/Problems/1489.cpp @@ -1,66 +1,64 @@ class UnionFind { - int n; - vector<int> root, rank; + int n; + vector<int> root, rank; -public: - UnionFind(int n) : n(n), root(n), rank(n, 1) { - iota(root.begin(), root.end(), 0); - } + public: + UnionFind(int n) : n(n), root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (rank[x] > rank[y]) swap(x, y); - root[x] = y; - rank[y] += 1; - n--; + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (rank[x] > rank[y]) swap(x, y); + root[x] = y; + rank[y] += 1; + n--; + } } - } - int count() { return n; } - bool connected(int x, int y) { return find(x) == find(y); } + int count() { return n; } + bool connected(int x, int y) { return find(x) == find(y); } }; class Solution { - typedef vector<int> edge; + typedef vector<int> edge; - int get_mst(int n, const vector<edge> &edges, int blockedge, - int pre_edge = -1) { - UnionFind uf(n); - int weight = 0; - if (pre_edge != -1) { - weight += edges[pre_edge][2]; - uf.join(edges[pre_edge][0], edges[pre_edge][1]); + int get_mst(int n, const vector<edge> &edges, int blockedge, int pre_edge = -1) { + UnionFind uf(n); + int weight = 0; + if (pre_edge != -1) { + weight += edges[pre_edge][2]; + uf.join(edges[pre_edge][0], edges[pre_edge][1]); + } + for (int i = 0; i < edges.size() && uf.count() != 1; ++i) { + } + if (i == blockedge) continue; + const auto &e = edges[i]; + if (uf.connected(e[0], e[1])) continue; + uf.join(e[0], e[1]); + weight += e[2]; } - for (int i = 0; i < edges.size() && uf.count() != 1; ++i) {} - if (i == blockedge) continue; - const auto &e = edges[i]; - if (uf.connected(e[0], e[1])) continue; - uf.join(e[0], e[1]); - weight += e[2]; - } - return uf.count() == 1 ? weight : 1e9 + 7; -} public : vector<vector<int>> - findCriticalAndPseudoCriticalEdges(int n, vector<edge> &edges) { - for (int i = 0; i < edges.size(); i++) edges[i].push_back(i); - sort(edges.begin(), edges.end(), - [](const edge &a, const edge &b) { return a[2] < b[2]; }); - int origin_mst = get_mst(n, edges, -1); + return uf.count() == 1 ? weight : 1e9 + 7; +} public : vector<vector<int>> findCriticalAndPseudoCriticalEdges(int n, vector<edge> &edges) { + for (int i = 0; i < edges.size(); i++) + edges[i].push_back(i); + sort(edges.begin(), edges.end(), [](const edge &a, const edge &b) { return a[2] < b[2]; }); + int origin_mst = get_mst(n, edges, -1); - vector<int> critical, non_critical; - for (int i = 0; i < edges.size(); i++) { - if (origin_mst < get_mst(n, edges, i)) - critical.push_back(edges[i][3]); - else if (origin_mst == get_mst(n, edges, -1, i)) - non_critical.push_back(edges[i][3]); - } - return {critical, non_critical}; + vector<int> critical, non_critical; + for (int i = 0; i < edges.size(); i++) { + if (origin_mst < get_mst(n, edges, i)) + critical.push_back(edges[i][3]); + else if (origin_mst == get_mst(n, edges, -1, i)) + non_critical.push_back(edges[i][3]); + } + return {critical, non_critical}; } } ; diff --git a/Problems/1491.cpp b/Problems/1491.cpp @@ -1,12 +1,12 @@ class Solution { -public: - double average(vector<int> &salary) { - int mini = *min_element(salary.begin(), salary.end()); - int maxi = *max_element(salary.begin(), salary.end()); - int sum = 0, count = 0; - for (int i = 0; i < salary.size(); i++) - if (salary[i] != mini && salary[i] != maxi) sum += salary[i], count++; + public: + double average(vector<int> &salary) { + int mini = *min_element(salary.begin(), salary.end()); + int maxi = *max_element(salary.begin(), salary.end()); + int sum = 0, count = 0; + for (int i = 0; i < salary.size(); i++) + if (salary[i] != mini && salary[i] != maxi) sum += salary[i], count++; - return (double)sum / count; - } + return (double)sum / count; + } }; diff --git a/Problems/1493.cpp b/Problems/1493.cpp @@ -1,13 +1,13 @@ class Solution { -public: - int longestSubarray(const vector<int> &nums) { - int res = 0, left = 0, zero = -1, i; - for (i = 0; i < nums.size(); i++) { - if (nums[i]) continue; - res = max(res, i - left); - left = zero + 1; - zero = i; + public: + int longestSubarray(const vector<int> &nums) { + int res = 0, left = 0, zero = -1, i; + for (i = 0; i < nums.size(); i++) { + if (nums[i]) continue; + res = max(res, i - left); + left = zero + 1; + zero = i; + } + return max(res, i - left) - 1; } - return max(res, i - left) - 1; - } }; diff --git a/Problems/1498.cpp b/Problems/1498.cpp @@ -1,25 +1,26 @@ -#define MOD (int)(1E9 + 7) +#define MOD (int)(1E9 + 7) #define SIZE (int)(1E5 + 1) int pows[SIZE] = {1}; static const auto Initialize = [] { - ios_base::sync_with_stdio(false), cin.tie(nullptr); - for (int i = 1; i < SIZE; ++i) pows[i] = (pows[i - 1] << 1) % MOD; - return nullptr; + ios_base::sync_with_stdio(false), cin.tie(nullptr); + for (int i = 1; i < SIZE; ++i) + pows[i] = (pows[i - 1] << 1) % MOD; + return nullptr; }(); class Solution { -public: - int numSubseq(vector<int> &nums, int target) { - sort(nums.begin(), nums.end()); - int n = nums.size(), l = 0, r = n - 1; + public: + int numSubseq(vector<int> &nums, int target) { + sort(nums.begin(), nums.end()); + int n = nums.size(), l = 0, r = n - 1; - int res = 0; - while (l <= r) { - if (nums[l] + nums[r] > target) - r--; - else - res = (res + pows[r - l++]) % MOD; + int res = 0; + while (l <= r) { + if (nums[l] + nums[r] > target) + r--; + else + res = (res + pows[r - l++]) % MOD; + } + return res; } - return res; - } }; diff --git a/Problems/1502.cpp b/Problems/1502.cpp @@ -1,13 +1,13 @@ class Solution { -public: - bool canMakeArithmeticProgression(vector<int> &arr) { - int n = arr.size(); - if (n <= 2) return true; - sort(arr.begin(), arr.end()); - int delta = arr[1] - arr[0]; - for (int i = 2; i < n; i++) { - if (arr[i] - arr[i - 1] != delta) return false; + public: + bool canMakeArithmeticProgression(vector<int> &arr) { + int n = arr.size(); + if (n <= 2) return true; + sort(arr.begin(), arr.end()); + int delta = arr[1] - arr[0]; + for (int i = 2; i < n; i++) { + if (arr[i] - arr[i - 1] != delta) return false; + } + return true; } - return true; - } }; diff --git a/Problems/1514.cpp b/Problems/1514.cpp @@ -1,35 +1,35 @@ class Solution { - typedef tuple<double, int> edge; + typedef tuple<double, int> edge; -public: - double maxProbability(int n, const vector<vector<int>> &edges, - const vector<double> &succProb, int start, int end) { - vector<vector<edge>> adj(n); - vector<bool> visited(n, false); - vector<double> dist(n, 0); - priority_queue<edge> pq; + public: + double maxProbability(int n, const vector<vector<int>> &edges, const vector<double> &succProb, int start, + int end) { + vector<vector<edge>> adj(n); + vector<bool> visited(n, false); + vector<double> dist(n, 0); + priority_queue<edge> pq; - for (int i = 0; i < succProb.size(); i++) { - adj[edges[i][0]].push_back({succProb[i], edges[i][1]}); - adj[edges[i][1]].push_back({succProb[i], edges[i][0]}); - } + for (int i = 0; i < succProb.size(); i++) { + adj[edges[i][0]].push_back({succProb[i], edges[i][1]}); + adj[edges[i][1]].push_back({succProb[i], edges[i][0]}); + } - pq.push({dist[start] = 1.0, start}); - while (n && !pq.empty()) { - auto [w, dest] = pq.top(); - pq.pop(); - if (visited[dest]) continue; - if (dest == end) return w; - visited[dest] = true; - for (const auto &[pw, pd] : adj[dest]) { - if (!visited[pd] && dist[dest] * pw > dist[pd]) { - dist[pd] = dist[dest] * pw; - pq.push({dist[pd], pd}); + pq.push({dist[start] = 1.0, start}); + while (n && !pq.empty()) { + auto [w, dest] = pq.top(); + pq.pop(); + if (visited[dest]) continue; + if (dest == end) return w; + visited[dest] = true; + for (const auto &[pw, pd] : adj[dest]) { + if (!visited[pd] && dist[dest] * pw > dist[pd]) { + dist[pd] = dist[dest] * pw; + pq.push({dist[pd], pd}); + } + } + n--; } - } - n--; - } - return 0; - } + return 0; + } }; diff --git a/Problems/1519.cpp b/Problems/1519.cpp @@ -1,38 +1,39 @@ class Solution { -public: - vector<int> countSubTrees(int n, vector<vector<int>> &edges, string labels) { - vector<vector<int>> adj(n, vector<int>()), count(n, vector<int>(26, 0)); - vector<bool> visited(n, false); - vector<int> res(n); + public: + vector<int> countSubTrees(int n, vector<vector<int>> &edges, string labels) { + vector<vector<int>> adj(n, vector<int>()), count(n, vector<int>(26, 0)); + vector<bool> visited(n, false); + vector<int> res(n); - for (auto &e : edges) { - adj[e[0]].push_back(e[1]); - adj[e[1]].push_back(e[0]); - } + for (auto &e : edges) { + adj[e[0]].push_back(e[1]); + adj[e[1]].push_back(e[0]); + } - stack<int> st; - st.push(0); - while (!st.empty()) { - int crnt = st.top(); - if (visited[crnt]) { - st.pop(); + stack<int> st; + st.push(0); + while (!st.empty()) { + int crnt = st.top(); + if (visited[crnt]) { + st.pop(); - for (int c : adj[crnt]) { - if (visited[c]) continue; - for (int i = 0; i < 26; i++) count[crnt][i] += count[c][i]; + for (int c : adj[crnt]) { + if (visited[c]) continue; + for (int i = 0; i < 26; i++) + count[crnt][i] += count[c][i]; + } + res[crnt] = ++count[crnt][labels[crnt] - 'a']; + visited[crnt] = false; + continue; + } + + visited[crnt] = true; + for (int c : adj[crnt]) { + if (visited[c]) continue; + st.push(c); + } } - res[crnt] = ++count[crnt][labels[crnt] - 'a']; - visited[crnt] = false; - continue; - } - visited[crnt] = true; - for (int c : adj[crnt]) { - if (visited[c]) continue; - st.push(c); - } + return res; } - - return res; - } }; diff --git a/Problems/1523.cpp b/Problems/1523.cpp @@ -1,6 +1,4 @@ class Solution { -public: - int countOdds(int low, int high) { - return (high - low) / 2 + ((low % 2) | (high % 2)); - } + public: + int countOdds(int low, int high) { return (high - low) / 2 + ((low % 2) | (high % 2)); } }; diff --git a/Problems/1529.cpp b/Problems/1529.cpp @@ -1,12 +1,12 @@ class Solution { -public: - int minFlips(const string &target) { - int res = 0, looking = 1; - for (const char c : target) { - if ((c & 1) != looking) continue; - looking = !looking; - res++; + public: + int minFlips(const string &target) { + int res = 0, looking = 1; + for (const char c : target) { + if ((c & 1) != looking) continue; + looking = !looking; + res++; + } + return res; } - return res; - } }; diff --git a/Problems/1539.cpp b/Problems/1539.cpp @@ -1,8 +1,8 @@ class Solution { -public: - int findKthPositive(vector<int> &arr, int k) { - for (int n : arr) - if (n <= k) k++; - return k; - } + public: + int findKthPositive(vector<int> &arr, int k) { + for (int n : arr) + if (n <= k) k++; + return k; + } }; diff --git a/Problems/1544.cpp b/Problems/1544.cpp @@ -1,14 +1,14 @@ class Solution { -public: - string makeGood(string s) { - int i = 0; - while (i < s.size()) - if (s[i] != s[i + 1] && toupper(s[i]) == toupper(s[i + 1])) { - s.erase(i, 2); - i = max(0, i - 1); - } else { - i++; - } - return s; - } + public: + string makeGood(string s) { + int i = 0; + while (i < s.size()) + if (s[i] != s[i + 1] && toupper(s[i]) == toupper(s[i + 1])) { + s.erase(i, 2); + i = max(0, i - 1); + } else { + i++; + } + return s; + } }; diff --git a/Problems/1547.cpp b/Problems/1547.cpp @@ -1,21 +1,20 @@ class Solution { - int dp[102][102] = {}; + int dp[102][102] = {}; - int dfs(const vector<int> &cuts, int i, int j) { - if (j - i <= 1) return 0; - if (dp[i][j]) return dp[i][j]; - dp[i][j] = INT_MAX; - for (auto k = i + 1; k < j; ++k) - dp[i][j] = - min(dp[i][j], cuts[j] - cuts[i] + dfs(cuts, i, k) + dfs(cuts, k, j)); - return dp[i][j]; - } + int dfs(const vector<int> &cuts, int i, int j) { + if (j - i <= 1) return 0; + if (dp[i][j]) return dp[i][j]; + dp[i][j] = INT_MAX; + for (auto k = i + 1; k < j; ++k) + dp[i][j] = min(dp[i][j], cuts[j] - cuts[i] + dfs(cuts, i, k) + dfs(cuts, k, j)); + return dp[i][j]; + } -public: - int minCost(int n, vector<int> &cuts) { - cuts.push_back(0); - cuts.push_back(n); - sort(begin(cuts), end(cuts)); - return dfs(cuts, 0, cuts.size() - 1); - } + public: + int minCost(int n, vector<int> &cuts) { + cuts.push_back(0); + cuts.push_back(n); + sort(begin(cuts), end(cuts)); + return dfs(cuts, 0, cuts.size() - 1); + } }; diff --git a/Problems/1551.cpp b/Problems/1551.cpp @@ -1,8 +1,8 @@ // 1551. Minimum Operations to Make Array Equal class Solution { -public: - int minOperations(int n) { - int k = n / 2; - return n % 2 ? k * (k + 1) : k * k; - } + public: + int minOperations(int n) { + int k = n / 2; + return n % 2 ? k * (k + 1) : k * k; + } }; diff --git a/Problems/1557.cpp b/Problems/1557.cpp @@ -1,14 +1,15 @@ class Solution { -public: - vector<int> findSmallestSetOfVertices(int n, vector<vector<int>> &edges) { - vector<int> root(n), res; - iota(root.begin(), root.end(), 0); + public: + vector<int> findSmallestSetOfVertices(int n, vector<vector<int>> &edges) { + vector<int> root(n), res; + iota(root.begin(), root.end(), 0); - for (auto &p : edges) root[p[1]] = p[0]; + for (auto &p : edges) + root[p[1]] = p[0]; - for (int i = 0; i < n; i++) - if (i == root[i]) res.push_back(i); + for (int i = 0; i < n; i++) + if (i == root[i]) res.push_back(i); - return res; - } + return res; + } }; diff --git a/Problems/1561.cpp b/Problems/1561.cpp @@ -1,13 +1,13 @@ class Solution { -public: - int maxCoins(vector<int> &piles) { - sort(piles.begin(), piles.end()); + public: + int maxCoins(vector<int> &piles) { + sort(piles.begin(), piles.end()); - int res = 0; - for (int i = piles.size() / 3; i < piles.size(); i += 2) { - res += piles[i]; - } + int res = 0; + for (int i = piles.size() / 3; i < piles.size(); i += 2) { + res += piles[i]; + } - return res; - } + return res; + } }; diff --git a/Problems/1567.cpp b/Problems/1567.cpp @@ -1,3 +1 @@ -Formating: Problems/0152.cpp -Formating: Problems/0300.cpp -Formating: Problems/1567.cpp +Formating : Problems / 0152.cpp Formating : Problems / 0300.cpp Formating : Problems / 1567.cpp diff --git a/Problems/1569.cpp b/Problems/1569.cpp @@ -1,35 +1,35 @@ class Solution { - vector<vector<long long>> table; - const int MOD = 1E9 + 7; + vector<vector<long long>> table; + const int MOD = 1E9 + 7; - void generate(int numRows) { - table.resize(numRows); - table[0] = {1}; - for (int i = 1; i < numRows; i++) { - table[i] = vector<long long>(i + 1); - table[i][0] = table[i][i] = 1; - for (int j = 1; j < i; j++) { - table[i][j] = (table[i - 1][j - 1] + table[i - 1][j]) % MOD; - } + void generate(int numRows) { + table.resize(numRows); + table[0] = {1}; + for (int i = 1; i < numRows; i++) { + table[i] = vector<long long>(i + 1); + table[i][0] = table[i][i] = 1; + for (int j = 1; j < i; j++) { + table[i][j] = (table[i - 1][j - 1] + table[i - 1][j]) % MOD; + } + } } - } - long long rec(const vector<int> &nums) { - int n = nums.size(); - if (n <= 2) return 1; + long long rec(const vector<int> &nums) { + int n = nums.size(); + if (n <= 2) return 1; - vector<int> l, r; - for (int i = 1; i < n; i++) { - (nums[i] < nums.front() ? l : r).push_back(nums[i]); - } + vector<int> l, r; + for (int i = 1; i < n; i++) { + (nums[i] < nums.front() ? l : r).push_back(nums[i]); + } - long long lr = rec(l) % MOD, rr = rec(r) % MOD; - return (((table[n - 1][l.size()] * lr) % MOD) * rr) % MOD; - } + long long lr = rec(l) % MOD, rr = rec(r) % MOD; + return (((table[n - 1][l.size()] * lr) % MOD) * rr) % MOD; + } -public: - int numOfWays(vector<int> &nums) { - generate(nums.size() + 1); - return rec(nums) % MOD - 1; - } + public: + int numOfWays(vector<int> &nums) { + generate(nums.size() + 1); + return rec(nums) % MOD - 1; + } }; diff --git a/Problems/1572.cpp b/Problems/1572.cpp @@ -1,10 +1,11 @@ class Solution { -public: - int diagonalSum(vector<vector<int>> &mat) { - int n = mat.size(), sum = 0; - for (int i = 0; i < n; i++) sum += mat[i][i] + mat[i][n - i - 1]; + public: + int diagonalSum(vector<vector<int>> &mat) { + int n = mat.size(), sum = 0; + for (int i = 0; i < n; i++) + sum += mat[i][i] + mat[i][n - i - 1]; - if (n % 2) sum -= mat[n / 2][n / 2]; - return sum; - } + if (n % 2) sum -= mat[n / 2][n / 2]; + return sum; + } }; diff --git a/Problems/1575.cpp b/Problems/1575.cpp @@ -1,21 +1,20 @@ class Solution { - static const int MOD = 1E9 + 7; - int dp[101][201]; + static const int MOD = 1E9 + 7; + int dp[101][201]; -public: - Solution() { memset(dp, 0xFF, sizeof(dp)); } + public: + Solution() { memset(dp, 0xFF, sizeof(dp)); } - int countRoutes(const vector<int> &loc, int start, int finish, int fuel) { - if (fuel < 0) return 0; - if (dp[start][fuel] >= 0) return dp[start][fuel]; + int countRoutes(const vector<int> &loc, int start, int finish, int fuel) { + if (fuel < 0) return 0; + if (dp[start][fuel] >= 0) return dp[start][fuel]; - int res = (start == finish); - for (int i = 0; i < loc.size(); i++) { - if (i == start) continue; - int solution = - countRoutes(loc, i, finish, fuel - abs(loc[start] - loc[i])); - res = (res + solution) % MOD; + int res = (start == finish); + for (int i = 0; i < loc.size(); i++) { + if (i == start) continue; + int solution = countRoutes(loc, i, finish, fuel - abs(loc[start] - loc[i])); + res = (res + solution) % MOD; + } + return dp[start][fuel] = res; } - return dp[start][fuel] = res; - } }; diff --git a/Problems/1579.cpp b/Problems/1579.cpp @@ -1,56 +1,54 @@ class UnionFind { - int n, cnt = n; - vector<int> root, size; - -public: - UnionFind(int n) : n(n), root(n), size(n, 1) { - iota(root.begin(), root.end(), 0); - } - - UnionFind(const UnionFind &uf) - : n(uf.n), cnt(uf.cnt), root(uf.root), size(uf.size) {} - - static int redundant; - - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } - - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (size[x] > size[y]) swap(x, y); - root[x] = y; - size[y] += size[x]; - cnt--; - } else - redundant++; - } - - int count() { return cnt; } - bool connected(int x, int y) { return find(x) == find(y); } + int n, cnt = n; + vector<int> root, size; + + public: + UnionFind(int n) : n(n), root(n), size(n, 1) { iota(root.begin(), root.end(), 0); } + + UnionFind(const UnionFind &uf) : n(uf.n), cnt(uf.cnt), root(uf.root), size(uf.size) {} + + static int redundant; + + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } + + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (size[x] > size[y]) swap(x, y); + root[x] = y; + size[y] += size[x]; + cnt--; + } else + redundant++; + } + + int count() { return cnt; } + bool connected(int x, int y) { return find(x) == find(y); } }; int UnionFind::redundant = 0; class Solution { -public: - int maxNumEdgesToRemove(int n, vector<vector<int>> &e) { - UnionFind::redundant = 0; - - UnionFind a(n + 1); - for (int i = 0; i < e.size(); i++) - if (e[i][0] == 3) a.join(e[i][1], e[i][2]); - - UnionFind b = a; - for (int i = 0; i < e.size(); i++) - if (e[i][0] == 1) - a.join(e[i][1], e[i][2]); - else if (e[i][0] == 2) - b.join(e[i][1], e[i][2]); - - // count must be 2, since 0 is not used - return a.count() == 2 && b.count() == 2 ? UnionFind::redundant : -1; - } + public: + int maxNumEdgesToRemove(int n, vector<vector<int>> &e) { + UnionFind::redundant = 0; + + UnionFind a(n + 1); + for (int i = 0; i < e.size(); i++) + if (e[i][0] == 3) a.join(e[i][1], e[i][2]); + + UnionFind b = a; + for (int i = 0; i < e.size(); i++) + if (e[i][0] == 1) + a.join(e[i][1], e[i][2]); + else if (e[i][0] == 2) + b.join(e[i][1], e[i][2]); + + // count must be 2, since 0 is not used + return a.count() == 2 && b.count() == 2 ? UnionFind::redundant : -1; + } }; diff --git a/Problems/1584.cpp b/Problems/1584.cpp @@ -1,57 +1,54 @@ class UnionFind { - int n; - vector<int> root, rank; - -public: - UnionFind(int n) : n(n), root(n), rank(n, 1) { - iota(root.begin(), root.end(), 0); - } - - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } - - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (rank[x] > rank[y]) swap(x, y); - root[x] = y; - rank[y] += 1; - n--; + int n; + vector<int> root, rank; + + public: + UnionFind(int n) : n(n), root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } + + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } + + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (rank[x] > rank[y]) swap(x, y); + root[x] = y; + rank[y] += 1; + n--; + } } - } - int count() { return n; } - bool connected(int x, int y) { return find(x) == find(y); } + int count() { return n; } + bool connected(int x, int y) { return find(x) == find(y); } }; class Solution { - typedef array<int, 3> edge; - typedef vector<int> point; - - int distance(const point &p1, const point &p2) { - return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]); - } - -public: - int minCostConnectPoints(vector<vector<int>> &points) { - auto cmp = [](const edge &a, const edge &b) { return a[2] > b[2]; }; - priority_queue<edge, vector<edge>, decltype(cmp)> pq(cmp); - UnionFind uf(points.size()); - - for (int i = 0; i < points.size(); i++) - for (int j = i + 1; j < points.size(); j++) - pq.push({i, j, distance(points[i], points[j])}); - - int res = 0; - while (uf.count() != 1) { - auto [s, d, w] = pq.top(); - pq.pop(); - if (uf.connected(s, d)) continue; - uf.join(s, d); - res += w; + typedef array<int, 3> edge; + typedef vector<int> point; + + int distance(const point &p1, const point &p2) { return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]); } + + public: + int minCostConnectPoints(vector<vector<int>> &points) { + auto cmp = [](const edge &a, const edge &b) { return a[2] > b[2]; }; + priority_queue<edge, vector<edge>, decltype(cmp)> pq(cmp); + UnionFind uf(points.size()); + + for (int i = 0; i < points.size(); i++) + for (int j = i + 1; j < points.size(); j++) + pq.push({i, j, distance(points[i], points[j])}); + + int res = 0; + while (uf.count() != 1) { + auto [s, d, w] = pq.top(); + pq.pop(); + if (uf.connected(s, d)) continue; + uf.join(s, d); + res += w; + } + return res; } - return res; - } }; diff --git a/Problems/1601.cpp b/Problems/1601.cpp @@ -1,27 +1,26 @@ class Solution { - int degree[21] = {0}; - int res = 0; + int degree[21] = {0}; + int res = 0; - void rec(const vector<vector<int>> &req, int cur = 0, int cnt = 0, - int dirty = 0) { - if (cnt + (req.size() - cur) < res) return; - if (cur == req.size()) { - if (dirty) return; - res = max(res, cnt); - return; - } + void rec(const vector<vector<int>> &req, int cur = 0, int cnt = 0, int dirty = 0) { + if (cnt + (req.size() - cur) < res) return; + if (cur == req.size()) { + if (dirty) return; + res = max(res, cnt); + return; + } - rec(req, cur + 1, cnt, dirty); + rec(req, cur + 1, cnt, dirty); - if (degree[req[cur][0]]++ == 0) dirty++; - if (--degree[req[cur][1]] == 0) dirty--; - rec(req, cur + 1, cnt + 1, dirty); - degree[req[cur][0]]--, degree[req[cur][1]]++; - } + if (degree[req[cur][0]]++ == 0) dirty++; + if (--degree[req[cur][1]] == 0) dirty--; + rec(req, cur + 1, cnt + 1, dirty); + degree[req[cur][0]]--, degree[req[cur][1]]++; + } -public: - int maximumRequests(int n, const vector<vector<int>> &requests) { - rec(requests); - return res; - } + public: + int maximumRequests(int n, const vector<vector<int>> &requests) { + rec(requests); + return res; + } }; diff --git a/Problems/1603.cpp b/Problems/1603.cpp @@ -1,13 +1,12 @@ class ParkingSystem { - vector<int> space; + vector<int> space; -public: - ParkingSystem(int big, int medium, int small) - : space(vector<int>{0, big, medium, small}) {} + public: + ParkingSystem(int big, int medium, int small) : space(vector<int>{0, big, medium, small}) {} - bool addCar(int carType) { - if (space[carType] == 0) return false; - space[carType]--; - return true; - } + bool addCar(int carType) { + if (space[carType] == 0) return false; + space[carType]--; + return true; + } }; diff --git a/Problems/1605.cpp b/Problems/1605.cpp @@ -1,14 +1,14 @@ class Solution { -public: - vector<vector<int>> restoreMatrix(vector<int> &row, vector<int> &col) { - int m = row.size(), n = col.size(); - vector<vector<int>> res(m, vector<int>(n, 0)); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - res[i][j] = min(row[i], col[j]); - row[i] -= res[i][j], col[j] -= res[i][j]; - } + public: + vector<vector<int>> restoreMatrix(vector<int> &row, vector<int> &col) { + int m = row.size(), n = col.size(); + vector<vector<int>> res(m, vector<int>(n, 0)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + res[i][j] = min(row[i], col[j]); + row[i] -= res[i][j], col[j] -= res[i][j]; + } + } + return res; } - return res; - } }; diff --git a/Problems/1609.cpp b/Problems/1609.cpp @@ -1,28 +1,28 @@ class Solution { -public: - bool isEvenOddTree(TreeNode *root) { - if (!root) return false; + public: + bool isEvenOddTree(TreeNode *root) { + if (!root) return false; - queue<TreeNode *> q; - TreeNode *de = new TreeNode(0); - TreeNode *dd = new TreeNode(INT_MAX); + queue<TreeNode *> q; + TreeNode *de = new TreeNode(0); + TreeNode *dd = new TreeNode(INT_MAX); - q.push(root); - for (int lvl = 0; !q.empty(); lvl++) { - TreeNode *p = (lvl % 2 == 0) ? de : dd; - for (int t = q.size(); t > 0; t--) { - TreeNode *root = q.front(); - q.pop(); - if (lvl % 2 == 0) { - if (root->val % 2 != 1 || root->val <= p->val) return false; - } else { - if (root->val % 2 != 0 || root->val >= p->val) return false; + q.push(root); + for (int lvl = 0; !q.empty(); lvl++) { + TreeNode *p = (lvl % 2 == 0) ? de : dd; + for (int t = q.size(); t > 0; t--) { + TreeNode *root = q.front(); + q.pop(); + if (lvl % 2 == 0) { + if (root->val % 2 != 1 || root->val <= p->val) return false; + } else { + if (root->val % 2 != 0 || root->val >= p->val) return false; + } + p = root; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } } - p = root; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } + return true; } - return true; - } }; diff --git a/Problems/1615.cpp b/Problems/1615.cpp @@ -1,20 +1,20 @@ class Solution { -public: - int maximalNetworkRank(int n, vector<vector<int>> &roads) { - int mat[101][101] = {0}, degree[101] = {0}; - int res = 0; + public: + int maximalNetworkRank(int n, vector<vector<int>> &roads) { + int mat[101][101] = {0}, degree[101] = {0}; + int res = 0; - for (int i = 0; i < roads.size(); i++) { - int u = roads[i][0], v = roads[i][1]; - degree[u]++, degree[v]++; - mat[u][v] = mat[v][u] = 1; - } + for (int i = 0; i < roads.size(); i++) { + int u = roads[i][0], v = roads[i][1]; + degree[u]++, degree[v]++; + mat[u][v] = mat[v][u] = 1; + } - for (int i = 0; i < n; i++) { - for (int j = i + 1; j < n; j++) { - res = max(res, degree[i] + degree[j] - mat[i][j]); - } + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + res = max(res, degree[i] + degree[j] - mat[i][j]); + } + } + return res; } - return res; - } }; diff --git a/Problems/1626.cpp b/Problems/1626.cpp @@ -1,20 +1,21 @@ class Solution { -public: - int bestTeamScore(vector<int> &scores, vector<int> &ages) { - int n = scores.size(), res = 0; - vector<pair<int, int>> v(n); - for (int i = 0; i < n; i++) v[i] = {ages[i], scores[i]}; - sort(v.begin(), v.end()); + public: + int bestTeamScore(vector<int> &scores, vector<int> &ages) { + int n = scores.size(), res = 0; + vector<pair<int, int>> v(n); + for (int i = 0; i < n; i++) + v[i] = {ages[i], scores[i]}; + sort(v.begin(), v.end()); - vector<int> dp(n, 0); - for (int i = 0; i < n; i++) { - int total = 0; - for (int j = 0; j < i; j++) { - if (v[j].second <= v[i].second) dp[i] = max(dp[i], dp[j]); - } - res = max(res, dp[i] += v[i].second); - } + vector<int> dp(n, 0); + for (int i = 0; i < n; i++) { + int total = 0; + for (int j = 0; j < i; j++) { + if (v[j].second <= v[i].second) dp[i] = max(dp[i], dp[j]); + } + res = max(res, dp[i] += v[i].second); + } - return res; - } + return res; + } }; diff --git a/Problems/1630.cpp b/Problems/1630.cpp @@ -1,22 +1,21 @@ class Solution { -public: - vector<bool> checkArithmeticSubarrays(const vector<int> &nums, - const vector<int> &l, - const vector<int> &r) { - int n = nums.size(), m = l.size(); - vector<bool> res(m, true); - for (int q = 0; q < m; q++) { - if (r[q] - l[q] < 2) continue; - vector<int> range(nums.begin() + l[q], nums.begin() + r[q] + 1); - sort(range.begin(), range.end()); - const int diff = range[1] - range[0]; - for (int i = 2; i < range.size(); i++) { - if (range[i] - range[i - 1] != diff) { - res[q] = false; - break; + public: + vector<bool> checkArithmeticSubarrays(const vector<int> &nums, const vector<int> &l, + const vector<int> &r) { + int n = nums.size(), m = l.size(); + vector<bool> res(m, true); + for (int q = 0; q < m; q++) { + if (r[q] - l[q] < 2) continue; + vector<int> range(nums.begin() + l[q], nums.begin() + r[q] + 1); + sort(range.begin(), range.end()); + const int diff = range[1] - range[0]; + for (int i = 2; i < range.size(); i++) { + if (range[i] - range[i - 1] != diff) { + res[q] = false; + break; + } + } } - } + return res; } - return res; - } }; diff --git a/Problems/1637.cpp b/Problems/1637.cpp @@ -1,13 +1,15 @@ class Solution { -public: - int maxWidthOfVerticalArea(const vector<vector<int>> &points) { - vector<int> v; - v.reserve(points.size()); - for (int i = 0; i < points.size(); i++) v.push_back(points[i][0]); - sort(v.begin(), v.end()); + public: + int maxWidthOfVerticalArea(const vector<vector<int>> &points) { + vector<int> v; + v.reserve(points.size()); + for (int i = 0; i < points.size(); i++) + v.push_back(points[i][0]); + sort(v.begin(), v.end()); - int maxi = 0; - for (int k = 1; k < v.size(); k++) maxi = max(maxi, v[k] - v[k - 1]); - return maxi; - } + int maxi = 0; + for (int k = 1; k < v.size(); k++) + maxi = max(maxi, v[k] - v[k - 1]); + return maxi; + } }; diff --git a/Problems/1639.cpp b/Problems/1639.cpp @@ -1,46 +1,45 @@ // Concise way class Solution { - long dp[1001] = {1, 0}; + long dp[1001] = {1, 0}; -public: - int numWays(const vector<string> &words, const string &target) { - int n = target.length(), mod = 1e9 + 7; - for (int i = 0; i < words[0].length(); ++i) { - vector<int> count(26); - for (const auto &w : words) count[w[i] - 'a']++; - for (int j = n - 1; j >= 0; --j) - dp[j + 1] += (dp[j] * count[target[j] - 'a']) % mod; + public: + int numWays(const vector<string> &words, const string &target) { + int n = target.length(), mod = 1e9 + 7; + for (int i = 0; i < words[0].length(); ++i) { + vector<int> count(26); + for (const auto &w : words) + count[w[i] - 'a']++; + for (int j = n - 1; j >= 0; --j) + dp[j + 1] += (dp[j] * count[target[j] - 'a']) % mod; + } + return dp[n] % mod; } - return dp[n] % mod; - } }; // Relatively dump way class Solution { - int dp[1001][1001] = {0}; - int count[1001][26] = {0}; - int mod = 1E9 + 7; + int dp[1001][1001] = {0}; + int count[1001][26] = {0}; + int mod = 1E9 + 7; - int rec(const vector<string> &words, const string &target, int k = 0, - int l = 0) { - if (k >= target.size()) return 1; - if (l >= words[0].size()) return 0; - if (dp[k][l] != -1) return dp[k][l]; + int rec(const vector<string> &words, const string &target, int k = 0, int l = 0) { + if (k >= target.size()) return 1; + if (l >= words[0].size()) return 0; + if (dp[k][l] != -1) return dp[k][l]; - long long res = rec(words, target, k, l + 1); - res += ((long long)count[l][target[k] - 'a'] * - rec(words, target, k + 1, l + 1)) % - mod; - return dp[k][l] = res % mod; - } + long long res = rec(words, target, k, l + 1); + res += ((long long)count[l][target[k] - 'a'] * rec(words, target, k + 1, l + 1)) % mod; + return dp[k][l] = res % mod; + } -public: - int numWays(const vector<string> &words, const string &target) { - memset(dp, 0xFF, 1001 * 1001 * sizeof(int)); // init dp to -1 - for (int i = 0; i < words.size(); i++) - for (int j = 0; j < words[i].size(); j++) count[j][words[i][j] - 'a']++; + public: + int numWays(const vector<string> &words, const string &target) { + memset(dp, 0xFF, 1001 * 1001 * sizeof(int)); // init dp to -1 + for (int i = 0; i < words.size(); i++) + for (int j = 0; j < words[i].size(); j++) + count[j][words[i][j] - 'a']++; - return rec(words, target, 0, 0); - } + return rec(words, target, 0, 0); + } }; diff --git a/Problems/1641.cpp b/Problems/1641.cpp @@ -1,10 +1,11 @@ class Solution { -public: - int countVowelStrings(int n) { - int vec[5] = {1, 1, 1, 1, 1}; - for (int i = 1; i <= n; i++) { - for (int i = 4, sum = 0; i >= 0; i--) vec[i] = sum += vec[i]; + public: + int countVowelStrings(int n) { + int vec[5] = {1, 1, 1, 1, 1}; + for (int i = 1; i <= n; i++) { + for (int i = 4, sum = 0; i >= 0; i--) + vec[i] = sum += vec[i]; + } + return vec[0]; } - return vec[0]; - } }; diff --git a/Problems/1646.cpp b/Problems/1646.cpp @@ -1,19 +1,19 @@ class Solution { -public: - int getMaximumGenerated(int n) { - if (n == 0) return 0; - if (n == 1) return 1; - vector<int> vec(n + 1); - vec[0] = 0; - vec[1] = 1; + public: + int getMaximumGenerated(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + vector<int> vec(n + 1); + vec[0] = 0; + vec[1] = 1; - int maxi = 0; - for (int i = 2; i <= n; i++) { - vec[i] = vec[i / 2]; - if (i % 2) vec[i] += vec[i / 2 + 1]; - maxi = max(vec[i], maxi); - } + int maxi = 0; + for (int i = 2; i <= n; i++) { + vec[i] = vec[i / 2]; + if (i % 2) vec[i] += vec[i / 2 + 1]; + maxi = max(vec[i], maxi); + } - return maxi; - } + return maxi; + } }; diff --git a/Problems/1669.cpp b/Problems/1669.cpp @@ -1,13 +1,16 @@ class Solution { -public: - ListNode *mergeInBetween(ListNode *list1, int a, int b, ListNode *list2) { - ListNode *ap, *bp; - a--; - for (ap = list1; a; a--, b--) ap = ap->next; - for (bp = ap; b; b--) bp = bp->next; - ap->next = list2; - while (ap->next) ap = ap->next; - ap->next = bp->next; - return list1; - } + public: + ListNode *mergeInBetween(ListNode *list1, int a, int b, ListNode *list2) { + ListNode *ap, *bp; + a--; + for (ap = list1; a; a--, b--) + ap = ap->next; + for (bp = ap; b; b--) + bp = bp->next; + ap->next = list2; + while (ap->next) + ap = ap->next; + ap->next = bp->next; + return list1; + } }; diff --git a/Problems/1672.cpp b/Problems/1672.cpp @@ -1,8 +1,9 @@ class Solution { -public: - int maximumWealth(vector<vector<int>> &accounts) { - vector<int> w; - for (auto &v : accounts) w.push_back(accumulate(v.begin(), v.end(), 0)); - return *max_element(w.begin(), w.end()); - } + public: + int maximumWealth(vector<vector<int>> &accounts) { + vector<int> w; + for (auto &v : accounts) + w.push_back(accumulate(v.begin(), v.end(), 0)); + return *max_element(w.begin(), w.end()); + } }; diff --git a/Problems/1675.cpp b/Problems/1675.cpp @@ -1,21 +1,21 @@ class Solution { -public: - int minimumDeviation(vector<int> &nums) { - int res = INT_MAX, mini = INT_MAX; - for (auto &num : nums) { - num = num % 2 ? num * 2 : num; - mini = min(mini, num); - } + public: + int minimumDeviation(vector<int> &nums) { + int res = INT_MAX, mini = INT_MAX; + for (auto &num : nums) { + num = num % 2 ? num * 2 : num; + mini = min(mini, num); + } - make_heap(begin(nums), end(nums)); - while (nums.front() % 2 == 0) { - res = min(res, nums.front() - mini); - mini = min(mini, nums.front() / 2); - pop_heap(begin(nums), end(nums)); - nums.back() /= 2; - push_heap(begin(nums), end(nums)); - } + make_heap(begin(nums), end(nums)); + while (nums.front() % 2 == 0) { + res = min(res, nums.front() - mini); + mini = min(mini, nums.front() / 2); + pop_heap(begin(nums), end(nums)); + nums.back() /= 2; + push_heap(begin(nums), end(nums)); + } - return min(res, nums.front() - mini); - } + return min(res, nums.front() - mini); + } }; diff --git a/Problems/1689.cpp b/Problems/1689.cpp @@ -1,6 +1,4 @@ class Solution { -public: - int minPartitions(const string &n) { - return *max_element(n.begin(), n.end()) & 0xF; - } + public: + int minPartitions(const string &n) { return *max_element(n.begin(), n.end()) & 0xF; } }; diff --git a/Problems/1696.cpp b/Problems/1696.cpp @@ -1,15 +1,16 @@ class Solution { -public: - int maxResult(vector<int> &nums, int k) { - vector<int> dp(size(nums)); - dp[0] = nums[0]; - deque<int> q{0}; - for (int i = 1; i < size(nums); i++) { - if (q.front() < i - k) q.pop_front(); - dp[i] = nums[i] + dp[q.front()]; - while (!q.empty() && dp[q.back()] <= dp[i]) q.pop_back(); - q.push_back(i); + public: + int maxResult(vector<int> &nums, int k) { + vector<int> dp(size(nums)); + dp[0] = nums[0]; + deque<int> q{0}; + for (int i = 1; i < size(nums); i++) { + if (q.front() < i - k) q.pop_front(); + dp[i] = nums[i] + dp[q.front()]; + while (!q.empty() && dp[q.back()] <= dp[i]) + q.pop_back(); + q.push_back(i); + } + return dp.back(); } - return dp.back(); - } }; diff --git a/Problems/1697.cpp b/Problems/1697.cpp @@ -1,50 +1,49 @@ class UnionFind { - int n, cnt = n; - vector<int> root, size; - -public: - UnionFind(int n) : n(n), root(n), size(n, 1) { - iota(root.begin(), root.end(), 0); - } - - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } - - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (size[x] > size[y]) swap(x, y); - root[x] = y; - size[y] += size[x]; - cnt--; + int n, cnt = n; + vector<int> root, size; + + public: + UnionFind(int n) : n(n), root(n), size(n, 1) { iota(root.begin(), root.end(), 0); } + + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } + + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (size[x] > size[y]) swap(x, y); + root[x] = y; + size[y] += size[x]; + cnt--; + } } - } - int count() { return cnt; } - bool connected(int x, int y) { return find(x) == find(y); } + int count() { return cnt; } + bool connected(int x, int y) { return find(x) == find(y); } }; class Solution { -public: - vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>> &edges, - vector<vector<int>> &queries) { - vector<bool> res(queries.size()); - UnionFind uf(n); - - for (int i = 0; i < queries.size(); ++i) queries[i].push_back(i); - - const auto cmp = [](auto &a, auto &b) { return a[2] < b[2]; }; - sort(begin(queries), end(queries), cmp); - sort(begin(edges), end(edges), cmp); - - int i = 0; - for (auto &q : queries) { - for (; i < edges.size() && edges[i][2] < q[2]; i++) - uf.join(edges[i][0], edges[i][1]); - res[q[3]] = uf.connected(q[0], q[1]); + public: + vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>> &edges, vector<vector<int>> &queries) { + vector<bool> res(queries.size()); + UnionFind uf(n); + + for (int i = 0; i < queries.size(); ++i) + queries[i].push_back(i); + + const auto cmp = [](auto &a, auto &b) { return a[2] < b[2]; }; + sort(begin(queries), end(queries), cmp); + sort(begin(edges), end(edges), cmp); + + int i = 0; + for (auto &q : queries) { + for (; i < edges.size() && edges[i][2] < q[2]; i++) + uf.join(edges[i][0], edges[i][1]); + res[q[3]] = uf.connected(q[0], q[1]); + } + return res; } - return res; - } }; diff --git a/Problems/1700.cpp b/Problems/1700.cpp @@ -1,21 +1,21 @@ class Solution { -public: - int countStudents(vector<int> &students, vector<int> &sandwiches) { - vector<int> count(2, 0); - queue<int> q; + public: + int countStudents(vector<int> &students, vector<int> &sandwiches) { + vector<int> count(2, 0); + queue<int> q; - for (int s : students) { - q.push(s); - count[s]++; - } + for (int s : students) { + q.push(s); + count[s]++; + } - for (int i = 0; i < sandwiches.size() && count[sandwiches[i]] != 0; q.pop()) - if (q.front() == sandwiches[i]) { - count[sandwiches[i]]--; - i++; - } else - q.push(q.front()); + for (int i = 0; i < sandwiches.size() && count[sandwiches[i]] != 0; q.pop()) + if (q.front() == sandwiches[i]) { + count[sandwiches[i]]--; + i++; + } else + q.push(q.front()); - return q.size(); - } + return q.size(); + } }; diff --git a/Problems/1704.cpp b/Problems/1704.cpp @@ -1,14 +1,12 @@ class Solution { - bool is_vowel(char c) { - return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; - } + bool is_vowel(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; } -public: - bool halvesAreAlike(string s) { - int i = 0, j = s.size() / 2, count = 0; - while (j < s.size()) - count += is_vowel(tolower(s[i++])) - is_vowel(tolower(s[j++])); - ; - return !count; - } + public: + bool halvesAreAlike(string s) { + int i = 0, j = s.size() / 2, count = 0; + while (j < s.size()) + count += is_vowel(tolower(s[i++])) - is_vowel(tolower(s[j++])); + ; + return !count; + } }; diff --git a/Problems/1706.cpp b/Problems/1706.cpp @@ -1,29 +1,30 @@ class Solution { - int m, n; + int m, n; - bool valid_column(int column) { return column >= 0 && column < n; } + bool valid_column(int column) { return column >= 0 && column < n; } - int simulate(int column, vector<vector<int>> &grid) { - int row = 0; - while (row < m) { - int type = grid[row][column]; - int nextc = column + type; - if (valid_column(nextc) && grid[row][nextc] == type) { - row++; - column = nextc; - } else - return -1; + int simulate(int column, vector<vector<int>> &grid) { + int row = 0; + while (row < m) { + int type = grid[row][column]; + int nextc = column + type; + if (valid_column(nextc) && grid[row][nextc] == type) { + row++; + column = nextc; + } else + return -1; + } + return column; } - return column; - } -public: - vector<int> findBall(vector<vector<int>> &grid) { - m = grid.size(); - n = grid[0].size(); + public: + vector<int> findBall(vector<vector<int>> &grid) { + m = grid.size(); + n = grid[0].size(); - vector<int> res; - for (int i = 0; i < n; i++) res.push_back(simulate(i, grid)); - return res; - } + vector<int> res; + for (int i = 0; i < n; i++) + res.push_back(simulate(i, grid)); + return res; + } }; diff --git a/Problems/1721.cpp b/Problems/1721.cpp @@ -1,14 +1,16 @@ class Solution { -public: - ListNode *swapNodes(ListNode *head, int k) { - ListNode *tmp = head, *first; - while (--k) tmp = tmp->next; - first = tmp; + public: + ListNode *swapNodes(ListNode *head, int k) { + ListNode *tmp = head, *first; + while (--k) + tmp = tmp->next; + first = tmp; - ListNode *second = head; - tmp = tmp->next; - while (tmp) tmp = tmp->next, second = second->next; - swap(first->val, second->val); - return head; - } + ListNode *second = head; + tmp = tmp->next; + while (tmp) + tmp = tmp->next, second = second->next; + swap(first->val, second->val); + return head; + } }; diff --git a/Problems/1722.cpp b/Problems/1722.cpp @@ -1,51 +1,51 @@ class UnionFind { - int n, cnt = n; - vector<int> root, size; - -public: - UnionFind(int n) : n(n), root(n), size(n, 1) { - iota(root.begin(), root.end(), 0); - } - - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } - - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (size[x] > size[y]) swap(x, y); - root[x] = y; - size[y] += size[x]; - cnt--; + int n, cnt = n; + vector<int> root, size; + + public: + UnionFind(int n) : n(n), root(n), size(n, 1) { iota(root.begin(), root.end(), 0); } + + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } + + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (size[x] > size[y]) swap(x, y); + root[x] = y; + size[y] += size[x]; + cnt--; + } } - } - int count() { return cnt; } - bool connected(int x, int y) { return find(x) == find(y); } + int count() { return cnt; } + bool connected(int x, int y) { return find(x) == find(y); } }; class Solution { -public: - int minimumHammingDistance(vector<int> &source, vector<int> &target, - vector<vector<int>> &allowedSwaps) { - int n = source.size(); - UnionFind uf(n); - - for (auto &s : allowedSwaps) uf.join(s[0], s[1]); - - vector<unordered_map<int, int>> vus(n); - for (int i = 0; i < n; i++) { - int pos = uf.find(i); - vus[pos][target[i]]++; - vus[pos][source[i]]--; + public: + int minimumHammingDistance(vector<int> &source, vector<int> &target, vector<vector<int>> &allowedSwaps) { + int n = source.size(); + UnionFind uf(n); + + for (auto &s : allowedSwaps) + uf.join(s[0], s[1]); + + vector<unordered_map<int, int>> vus(n); + for (int i = 0; i < n; i++) { + int pos = uf.find(i); + vus[pos][target[i]]++; + vus[pos][source[i]]--; + } + + int res = 0; + for (int i = 0; i < n; i++) + for (auto [_, val] : vus[i]) + res += abs(val); + + return res / 2; } - - int res = 0; - for (int i = 0; i < n; i++) - for (auto [_, val] : vus[i]) res += abs(val); - - return res / 2; - } }; diff --git a/Problems/1732.cpp b/Problems/1732.cpp @@ -1,8 +1,9 @@ class Solution { -public: - int largestAltitude(const vector<int> &gain) { - int maxi = 0, crnt = 0; - for (int n : gain) maxi = max(maxi, crnt += n); - return maxi; - } + public: + int largestAltitude(const vector<int> &gain) { + int maxi = 0, crnt = 0; + for (int n : gain) + maxi = max(maxi, crnt += n); + return maxi; + } }; diff --git a/Problems/1751.cpp b/Problems/1751.cpp @@ -1,57 +1,52 @@ // Recursive, top down class Solution { - typedef vector<int> Event; - vector<vector<int>> dp; - - int rec(const vector<Event> &events, const vector<Event>::const_iterator it, - int k) { - static const auto cmp = [](const Event &a, int val) { return a[0] <= val; }; - - if (!k || it == events.end()) return 0; - int idx = distance(events.begin(), it); - if (dp[k][idx] != -1) return dp[k][idx]; - - auto next = lower_bound(it, events.end(), (*it)[1], cmp); - int with = (*it)[2] + rec(events, next, k - 1); - int without = rec(events, it + 1, k); - return dp[k][idx] = max(with, without); - } - -public: - int maxValue(vector<Event> &events, int k) { - static const auto cmp = [](const Event &a, const Event &b) { - return a[0] < b[0]; - }; - sort(events.begin(), events.end(), cmp); - - dp = vector(k + 1, vector(events.size(), -1)); - return rec(events, events.begin(), k); - } + typedef vector<int> Event; + vector<vector<int>> dp; + + int rec(const vector<Event> &events, const vector<Event>::const_iterator it, int k) { + static const auto cmp = [](const Event &a, int val) { return a[0] <= val; }; + + if (!k || it == events.end()) return 0; + int idx = distance(events.begin(), it); + if (dp[k][idx] != -1) return dp[k][idx]; + + auto next = lower_bound(it, events.end(), (*it)[1], cmp); + int with = (*it)[2] + rec(events, next, k - 1); + int without = rec(events, it + 1, k); + return dp[k][idx] = max(with, without); + } + + public: + int maxValue(vector<Event> &events, int k) { + static const auto cmp = [](const Event &a, const Event &b) { return a[0] < b[0]; }; + sort(events.begin(), events.end(), cmp); + + dp = vector(k + 1, vector(events.size(), -1)); + return rec(events, events.begin(), k); + } }; // Iterative, bottom up class Solution { - typedef vector<int> Event; - -public: - int maxValue(vector<Event> &events, int k) { - static const auto cmp = [](const Event &a, int val) { return a[0] <= val; }; - static const auto cmp_sort = [](const Event &a, const Event &b) { - return a[0] < b[0]; - }; - sort(events.begin(), events.end(), cmp_sort); - - vector<vector<int>> dp(k + 1, vector(events.size() + 1, 0)); - - auto start = events.rbegin(); - for (int i = events.size() - 1; i >= 0; i--, start++) { - auto it = lower_bound(start.base(), events.end(), events[i][1], cmp); - int offset = distance(events.begin(), it); - for (int cnt = 1; cnt <= k; cnt++) { - dp[cnt][i] = max(dp[cnt][i + 1], events[i][2] + dp[cnt - 1][offset]); - } + typedef vector<int> Event; + + public: + int maxValue(vector<Event> &events, int k) { + static const auto cmp = [](const Event &a, int val) { return a[0] <= val; }; + static const auto cmp_sort = [](const Event &a, const Event &b) { return a[0] < b[0]; }; + sort(events.begin(), events.end(), cmp_sort); + + vector<vector<int>> dp(k + 1, vector(events.size() + 1, 0)); + + auto start = events.rbegin(); + for (int i = events.size() - 1; i >= 0; i--, start++) { + auto it = lower_bound(start.base(), events.end(), events[i][1], cmp); + int offset = distance(events.begin(), it); + for (int cnt = 1; cnt <= k; cnt++) { + dp[cnt][i] = max(dp[cnt][i + 1], events[i][2] + dp[cnt - 1][offset]); + } + } + + return dp[k][0]; } - - return dp[k][0]; - } }; diff --git a/Problems/1768.cpp b/Problems/1768.cpp @@ -1,17 +1,19 @@ class Solution { -public: - string mergeAlternately(string word1, string word2) { - int i = 0, j = 0; - string res = ""; + public: + string mergeAlternately(string word1, string word2) { + int i = 0, j = 0; + string res = ""; - while (i < word1.size() && j < word2.size()) { - res += word1[i++]; - res += word2[j++]; - } + while (i < word1.size() && j < word2.size()) { + res += word1[i++]; + res += word2[j++]; + } - while (i < word1.size()) res += word1[i++]; - while (j < word2.size()) res += word2[j++]; + while (i < word1.size()) + res += word1[i++]; + while (j < word2.size()) + res += word2[j++]; - return res; - } + return res; + } }; diff --git a/Problems/1769.cpp b/Problems/1769.cpp @@ -1,18 +1,18 @@ class Solution { -public: - vector<int> minOperations(const string &boxes) { - vector<int> res(boxes.size(), 0); + public: + vector<int> minOperations(const string &boxes) { + vector<int> res(boxes.size(), 0); - for (int i = 0, ops = 0, cnt = 0; i < boxes.size(); i++) { - res[i] += ops; - ops += cnt += (boxes[i] == '1'); - } + for (int i = 0, ops = 0, cnt = 0; i < boxes.size(); i++) { + res[i] += ops; + ops += cnt += (boxes[i] == '1'); + } - for (int i = boxes.size() - 1, ops = 0, cnt = 0; i >= 0; i--) { - res[i] += ops; - ops += cnt += (boxes[i] == '1'); - } + for (int i = boxes.size() - 1, ops = 0, cnt = 0; i >= 0; i--) { + res[i] += ops; + ops += cnt += (boxes[i] == '1'); + } - return res; - } + return res; + } }; diff --git a/Problems/1786.cpp b/Problems/1786.cpp @@ -1,80 +1,79 @@ class Solution { - const int mod = 1000000007; + const int mod = 1000000007; - struct edge { - int dest, w; - edge(int d, int w) : dest(d), w(w) {} - friend bool operator<(const edge &e1, const edge &e2) { - return e1.w > e2.w; - } - }; + struct edge { + int dest, w; + edge(int d, int w) : dest(d), w(w) {} + friend bool operator<(const edge &e1, const edge &e2) { return e1.w > e2.w; } + }; - vector<int> dijkstra(int n, vector<vector<edge>> &adj, int start) { - vector<int> dist(n + 1, INT_MAX); - priority_queue<edge> pq; + vector<int> dijkstra(int n, vector<vector<edge>> &adj, int start) { + vector<int> dist(n + 1, INT_MAX); + priority_queue<edge> pq; - vector<int> visited(n + 1, false); - pq.push({n, dist[n] = 0}); - for (int k = 0; k < n; k++) { - while (!pq.empty() && visited[pq.top().dest]) pq.pop(); - if (pq.empty()) break; - edge c = pq.top(); - pq.pop(); - visited[c.dest] = true; - for (edge &p : adj[c.dest]) - if (!visited[p.dest] && dist[c.dest] + p.w < dist[p.dest]) { - dist[p.dest] = dist[c.dest] + p.w; - pq.push({p.dest, dist[p.dest]}); + vector<int> visited(n + 1, false); + pq.push({n, dist[n] = 0}); + for (int k = 0; k < n; k++) { + while (!pq.empty() && visited[pq.top().dest]) + pq.pop(); + if (pq.empty()) break; + edge c = pq.top(); + pq.pop(); + visited[c.dest] = true; + for (edge &p : adj[c.dest]) + if (!visited[p.dest] && dist[c.dest] + p.w < dist[p.dest]) { + dist[p.dest] = dist[c.dest] + p.w; + pq.push({p.dest, dist[p.dest]}); + } } + return dist; } - return dist; - } -public: - int countRestrictedPaths(int n, vector<vector<int>> &edges) { - vector<vector<edge>> adj(n + 1); + public: + int countRestrictedPaths(int n, vector<vector<int>> &edges) { + vector<vector<edge>> adj(n + 1); - for (int i = 0; i < edges.size(); i++) { - adj[edges[i][0]].push_back({edges[i][1], edges[i][2]}); - adj[edges[i][1]].push_back({edges[i][0], edges[i][2]}); - } + for (int i = 0; i < edges.size(); i++) { + adj[edges[i][0]].push_back({edges[i][1], edges[i][2]}); + adj[edges[i][1]].push_back({edges[i][0], edges[i][2]}); + } - vector<int> dist = dijkstra(n, adj, n); - vector<int> dp(n + 1, 0); - vector<int> visited(n + 1, 0); - stack<int> st; + vector<int> dist = dijkstra(n, adj, n); + vector<int> dp(n + 1, 0); + vector<int> visited(n + 1, 0); + stack<int> st; - int count = 0; - st.push(1); - while (!st.empty()) { - int root = st.top(); + int count = 0; + st.push(1); + while (!st.empty()) { + int root = st.top(); - if (root == n) { - st.pop(); - count++; - continue; - } + if (root == n) { + st.pop(); + count++; + continue; + } - if (root == -1) { - st.pop(); - root = st.top(); - st.pop(); - dp[root] += count; - continue; - } + if (root == -1) { + st.pop(); + root = st.top(); + st.pop(); + dp[root] += count; + continue; + } - dp[root] = -count; - visited[root] = true; - st.push(-1); - for (auto [c, w] : adj[root]) - if (dist[root] > dist[c]) { - if (visited[c] && dp[c] >= 0) - count = (count + dp[c]) % mod; - else - st.push(c); + dp[root] = -count; + visited[root] = true; + st.push(-1); + for (auto [c, w] : adj[root]) + if (dist[root] > dist[c]) { + if (visited[c] && dp[c] >= 0) + count = (count + dp[c]) % mod; + else + st.push(c); + } } - } - return count; - } + return count; + } }; diff --git a/Problems/1791.cpp b/Problems/1791.cpp @@ -1,18 +1,18 @@ class Solution { -public: - int findCenter(vector<vector<int>> &edges) { - unordered_set<int> us; + public: + int findCenter(vector<vector<int>> &edges) { + unordered_set<int> us; - for (auto &p : edges) { - if (us.count(p[0])) - return p[0]; - else - us.insert(p[0]); - if (us.count(p[1])) - return p[1]; - else - us.insert(p[1]); + for (auto &p : edges) { + if (us.count(p[0])) + return p[0]; + else + us.insert(p[0]); + if (us.count(p[1])) + return p[1]; + else + us.insert(p[1]); + } + return -1; } - return -1; - } }; diff --git a/Problems/1799.cpp b/Problems/1799.cpp @@ -1,21 +1,20 @@ class Solution { - int dp[8][16384]; + int dp[8][16384]; -public: - Solution() { memset(dp, 0xFF, sizeof(dp)); } + public: + Solution() { memset(dp, 0xFF, sizeof(dp)); } - int maxScore(vector<int> &n, int i = 1, int mask = 0) { - if (i > n.size() / 2) return 0; - if (dp[i][mask] != -1) return dp[i][mask]; - dp[i][mask] = 0; - for (int j = 0; j < n.size(); j++) { - for (auto k = j + 1; k < n.size(); k++) { - int new_mask = (1 << j) | (1 << k); - if ((mask & new_mask)) continue; - dp[i][mask] = max(dp[i][mask], i * gcd(n[j], n[k]) + - maxScore(n, i + 1, mask + new_mask)); - } + int maxScore(vector<int> &n, int i = 1, int mask = 0) { + if (i > n.size() / 2) return 0; + if (dp[i][mask] != -1) return dp[i][mask]; + dp[i][mask] = 0; + for (int j = 0; j < n.size(); j++) { + for (auto k = j + 1; k < n.size(); k++) { + int new_mask = (1 << j) | (1 << k); + if ((mask & new_mask)) continue; + dp[i][mask] = max(dp[i][mask], i * gcd(n[j], n[k]) + maxScore(n, i + 1, mask + new_mask)); + } + } + return dp[i][mask]; } - return dp[i][mask]; - } }; diff --git a/Problems/1802.cpp b/Problems/1802.cpp @@ -1,20 +1,18 @@ class Solution { -public: - int maxValue(int n, int index, int maxSum) { - const int a = index, b = n - index - 1; - int low = 0, high = maxSum; + public: + int maxValue(int n, int index, int maxSum) { + const int a = index, b = n - index - 1; + int low = 0, high = maxSum; - const auto arit = [](long n, int mid) { - return (long)n * mid - n * (n + 1) / 2; - }; - while (low < high) { - int mid = (low + high + 1) / 2; - long res = mid + arit(min(a, mid - 1), mid) + arit(min(b, mid - 1), mid); - if (res <= maxSum - n) - low = mid; - else - high = mid - 1; + const auto arit = [](long n, int mid) { return (long)n * mid - n * (n + 1) / 2; }; + while (low < high) { + int mid = (low + high + 1) / 2; + long res = mid + arit(min(a, mid - 1), mid) + arit(min(b, mid - 1), mid); + if (res <= maxSum - n) + low = mid; + else + high = mid - 1; + } + return low + 1; } - return low + 1; - } }; diff --git a/Problems/1817.cpp b/Problems/1817.cpp @@ -1,23 +1,23 @@ class Solution { -public: - vector<int> findingUsersActiveMinutes(vector<vector<int>> &logs, int k) { - sort(logs.begin(), logs.end()); + public: + vector<int> findingUsersActiveMinutes(vector<vector<int>> &logs, int k) { + sort(logs.begin(), logs.end()); - vector<int> res(k, 0); - int crnt = logs.front()[0], val = logs.front()[1], count = 1; - for (const auto &log : logs) { - if (log[0] == crnt) { - if (log[1] == val) continue; - val = log[1]; - count++; - } else { + vector<int> res(k, 0); + int crnt = logs.front()[0], val = logs.front()[1], count = 1; + for (const auto &log : logs) { + if (log[0] == crnt) { + if (log[1] == val) continue; + val = log[1]; + count++; + } else { + if (count >= 1 && count <= k) res[count - 1]++; + crnt = log[0]; + val = log[1]; + count = 1; + } + } if (count >= 1 && count <= k) res[count - 1]++; - crnt = log[0]; - val = log[1]; - count = 1; - } + return res; } - if (count >= 1 && count <= k) res[count - 1]++; - return res; - } }; diff --git a/Problems/1822.cpp b/Problems/1822.cpp @@ -1,11 +1,11 @@ class Solution { -public: - int arraySign(vector<int> &nums) { - int sign = 1; - for (auto num : nums) { - if (num == 0) return 0; - if (num < 0) sign = -sign; + public: + int arraySign(vector<int> &nums) { + int sign = 1; + for (auto num : nums) { + if (num == 0) return 0; + if (num < 0) sign = -sign; + } + return sign; } - return sign; - } }; diff --git a/Problems/1823.cpp b/Problems/1823.cpp @@ -1,25 +1,27 @@ class Solution { - struct Node { - Node *next; - int val; - Node(int val = -1, Node *next = nullptr) : val(val), next(next) {} - }; + struct Node { + Node *next; + int val; + Node(int val = -1, Node *next = nullptr) : val(val), next(next) {} + }; -public: - int findTheWinner(int n, int k) { - Node *h, *t; - t = h = new Node(); - for (int i = 1; i <= n; i++) t = t->next = new Node(i); - t->next = h->next; - delete h; + public: + int findTheWinner(int n, int k) { + Node *h, *t; + t = h = new Node(); + for (int i = 1; i <= n; i++) + t = t->next = new Node(i); + t->next = h->next; + delete h; - while (t != t->next) { - for (int c = k - 1; c; c--) t = t->next; - h = t->next; - t->next = t->next->next; - delete h; - } + while (t != t->next) { + for (int c = k - 1; c; c--) + t = t->next; + h = t->next; + t->next = t->next->next; + delete h; + } - return t->val; - } + return t->val; + } }; diff --git a/Problems/1828.cpp b/Problems/1828.cpp @@ -1,14 +1,13 @@ class Solution { -public: - vector<int> countPoints(const vector<vector<int>>& points, const vector<vector<int>>& queries) { + public: + vector<int> countPoints(const vector<vector<int>> &points, const vector<vector<int>> &queries) { vector<int> res(queries.size(), 0); - for(int i=0; i<queries.size(); i++) { + for (int i = 0; i < queries.size(); i++) { int r2 = queries[i][2] * queries[i][2]; - for(int j=0; j<points.size(); j++) { + for (int j = 0; j < points.size(); j++) { int dx = points[j][0] - queries[i][0]; int dy = points[j][1] - queries[i][1]; - if(dx * dx + dy * dy <= r2) - res[i]++; + if (dx * dx + dy * dy <= r2) res[i]++; } } return res; diff --git a/Problems/1829.cpp b/Problems/1829.cpp @@ -1,12 +1,12 @@ class Solution { -public: - vector<int> getMaximumXor(vector<int> &nums, int maximumBit) { - const int n = nums.size(), mask = (1 << maximumBit) - 1; - vector<int> res(n); - for (int i = 0, acc = 0; i < n; i++) { - nums[i] = acc ^= nums[i]; - res[n - i - 1] = nums[i] ^ mask; + public: + vector<int> getMaximumXor(vector<int> &nums, int maximumBit) { + const int n = nums.size(), mask = (1 << maximumBit) - 1; + vector<int> res(n); + for (int i = 0, acc = 0; i < n; i++) { + nums[i] = acc ^= nums[i]; + res[n - i - 1] = nums[i] ^ mask; + } + return res; } - return res; - } }; diff --git a/Problems/1833.cpp b/Problems/1833.cpp @@ -1,10 +1,10 @@ class Solution { -public: - int maxIceCream(vector<int> &costs, int coins) { - sort(costs.begin(), costs.end()); - int index = 0, count = 0; - while (index < costs.size() && coins - costs[index] >= 0) - coins -= costs[index++], count++; - return count; - } + public: + int maxIceCream(vector<int> &costs, int coins) { + sort(costs.begin(), costs.end()); + int index = 0, count = 0; + while (index < costs.size() && coins - costs[index] >= 0) + coins -= costs[index++], count++; + return count; + } }; diff --git a/Problems/1834.cpp b/Problems/1834.cpp @@ -1,32 +1,33 @@ class Solution { - struct item { - int index, et, pt; - item(int i, int e, int p) : index(i), et(e), pt(p) {} - friend bool operator<(const item &i1, const item &i2) { - return (i1.pt > i2.pt) || (i1.pt == i2.pt && i1.index > i2.index); - } - }; + struct item { + int index, et, pt; + item(int i, int e, int p) : index(i), et(e), pt(p) {} + friend bool operator<(const item &i1, const item &i2) { + return (i1.pt > i2.pt) || (i1.pt == i2.pt && i1.index > i2.index); + } + }; -public: - vector<int> getOrder(vector<vector<int>> &tasks) { - vector<item> ss; - for (int i = 0; i < tasks.size(); i++) - ss.push_back({i, tasks[i][0], tasks[i][1]}); - sort(ss.begin(), ss.end(), - [](const item &i1, const item &i2) { return (i1.et < i2.et); }); + public: + vector<int> getOrder(vector<vector<int>> &tasks) { + vector<item> ss; + for (int i = 0; i < tasks.size(); i++) + ss.push_back({i, tasks[i][0], tasks[i][1]}); + sort(ss.begin(), ss.end(), [](const item &i1, const item &i2) { return (i1.et < i2.et); }); - vector<int> res; - priority_queue<item> pq; - int t = 0; - for (int i = 0; i < ss.size();) { - if (pq.empty() && t < ss[i].et) t = ss[i].et; - while (i < ss.size() && ss[i].et <= t) pq.push(ss[i++]); - item it = pq.top(); - pq.pop(); - res.push_back(it.index); - t += it.pt; + vector<int> res; + priority_queue<item> pq; + int t = 0; + for (int i = 0; i < ss.size();) { + if (pq.empty() && t < ss[i].et) t = ss[i].et; + while (i < ss.size() && ss[i].et <= t) + pq.push(ss[i++]); + item it = pq.top(); + pq.pop(); + res.push_back(it.index); + t += it.pt; + } + while (!pq.empty()) + res.push_back(pq.top().index), pq.pop(); + return res; } - while (!pq.empty()) res.push_back(pq.top().index), pq.pop(); - return res; - } }; diff --git a/Problems/1857.cpp b/Problems/1857.cpp @@ -1,46 +1,46 @@ class Solution { -public: - int largestPathValue(string colors, vector<vector<int>> &edges) { - int n = colors.size(); - vector<unordered_map<int, int>> dp(n); - vector<vector<int>> adj(n); - vector<int> count(n, 0); + public: + int largestPathValue(string colors, vector<vector<int>> &edges) { + int n = colors.size(); + vector<unordered_map<int, int>> dp(n); + vector<vector<int>> adj(n); + vector<int> count(n, 0); - for (auto &edge : edges) { - adj[edge[0]].push_back(edge[1]); - count[edge[1]]++; - } + for (auto &edge : edges) { + adj[edge[0]].push_back(edge[1]); + count[edge[1]]++; + } - queue<int> q; - stack<int> st; + queue<int> q; + stack<int> st; - for (int i = 0; i < n; i++) - if (!count[i]) q.push(i); + for (int i = 0; i < n; i++) + if (!count[i]) q.push(i); - while (!q.empty()) { - int root = q.front(); - q.pop(); - st.push(root); - for (int child : adj[root]) { - if (--count[child]) continue; - q.push(child); - } - } + while (!q.empty()) { + int root = q.front(); + q.pop(); + st.push(root); + for (int child : adj[root]) { + if (--count[child]) continue; + q.push(child); + } + } - for (int i = 0; i < n; i++) - if (count[i]) return -1; + for (int i = 0; i < n; i++) + if (count[i]) return -1; - int res = 0; - while (!st.empty()) { - int root = st.top(); - st.pop(); - for (int child : adj[root]) { - for (auto [color, count] : dp[child]) { - dp[root][color] = max(dp[root][color], count); + int res = 0; + while (!st.empty()) { + int root = st.top(); + st.pop(); + for (int child : adj[root]) { + for (auto [color, count] : dp[child]) { + dp[root][color] = max(dp[root][color], count); + } + } + res = max(res, ++dp[root][colors[root]]); } - } - res = max(res, ++dp[root][colors[root]]); + return res; } - return res; - } }; diff --git a/Problems/1870.cpp b/Problems/1870.cpp @@ -1,18 +1,19 @@ class Solution { -public: - int minSpeedOnTime(vector<int>& dist, double hour) { + public: + int minSpeedOnTime(vector<int> &dist, double hour) { int low = 1, high = 10000000; int res = -1; - while(low <= high) { + while (low <= high) { int mid = low + (high - low) / 2; double time = 0; - for(int i=0; i<dist.size() - 1; i++) - time+=ceil((double)dist[i] / mid); + for (int i = 0; i < dist.size() - 1; i++) + time += ceil((double)dist[i] / mid); time += (double)dist.back() / mid; - if(time <= hour) { + if (time <= hour) { res = mid; high = mid - 1; - } else low = mid + 1; + } else + low = mid + 1; } return res; } diff --git a/Problems/1877.cpp b/Problems/1877.cpp @@ -1,9 +1,10 @@ class Solution { -public: - int minPairSum(vector<int> &nums) { - sort(nums.begin(), nums.end()); - int res = INT_MIN, i = 0, j = nums.size() - 1; - while (i < j) res = max(res, nums[i++] + nums[j--]); - return res; - } + public: + int minPairSum(vector<int> &nums) { + sort(nums.begin(), nums.end()); + int res = INT_MIN, i = 0, j = nums.size() - 1; + while (i < j) + res = max(res, nums[i++] + nums[j--]); + return res; + } }; diff --git a/Problems/1910.cpp b/Problems/1910.cpp @@ -1,8 +1,8 @@ class Solution { -public: - string removeOccurrences(string s, const string &part) { - for (int pos = s.find(part); pos != string::npos; pos = s.find(part)) - s.erase(pos, part.size()); - return s; - } + public: + string removeOccurrences(string s, const string &part) { + for (int pos = s.find(part); pos != string::npos; pos = s.find(part)) + s.erase(pos, part.size()); + return s; + } }; diff --git a/Problems/1926.cpp b/Problems/1926.cpp @@ -1,43 +1,41 @@ class Solution { - int m, n; - vector<int> ox = {-1, 1, 0, 0}; - vector<int> oy = {0, 0, -1, 1}; + int m, n; + vector<int> ox = {-1, 1, 0, 0}; + vector<int> oy = {0, 0, -1, 1}; - bool is_valid(int x, int y) { return x >= 0 && x < m && y >= 0 && y < n; } + bool is_valid(int x, int y) { return x >= 0 && x < m && y >= 0 && y < n; } - bool is_exit(int x, int y) { - return x == 0 || x == m - 1 || y == 0 || y == n - 1; - } + bool is_exit(int x, int y) { return x == 0 || x == m - 1 || y == 0 || y == n - 1; } -public: - int nearestExit(vector<vector<char>> &maze, vector<int> &entrance) { - m = maze.size(); - n = maze[0].size(); + public: + int nearestExit(vector<vector<char>> &maze, vector<int> &entrance) { + m = maze.size(); + n = maze[0].size(); - queue<pair<int, int>> q; - q.push({entrance[0], entrance[1]}); - for (int lvl = 0; !q.empty(); lvl++) { - for (int t = q.size(); t > 0; t--) { - int x = q.front().first; - int y = q.front().second; - q.pop(); + queue<pair<int, int>> q; + q.push({entrance[0], entrance[1]}); + for (int lvl = 0; !q.empty(); lvl++) { + for (int t = q.size(); t > 0; t--) { + int x = q.front().first; + int y = q.front().second; + q.pop(); - // cout << x << " " << y << endl; + // cout << x << " " << y << endl; - if (maze[x][y] == '+') continue; + if (maze[x][y] == '+') continue; - if ((x != entrance[0] || y != entrance[1]) && is_exit(x, y)) return lvl; + if ((x != entrance[0] || y != entrance[1]) && is_exit(x, y)) return lvl; - maze[x][y] = '+'; + maze[x][y] = '+'; - for (int i = 0; i < 4; i++) { - int nx = x + ox[i]; - int ny = y + oy[i]; - if (is_valid(nx, ny) && maze[nx][ny] != '+') q.push({nx, ny}); + for (int i = 0; i < 4; i++) { + int nx = x + ox[i]; + int ny = y + oy[i]; + if (is_valid(nx, ny) && maze[nx][ny] != '+') q.push({nx, ny}); + } + } } - } - } - return -1; - } + return -1; + } }; diff --git a/Problems/1962.cpp b/Problems/1962.cpp @@ -1,32 +1,34 @@ // Using a priority_queue class Solution { -public: - int minStoneSum(vector<int> &piles, int k) { - priority_queue<int> pq; - int res = 0; - for (int e : piles) res += e, pq.push(e); - while (k--) { - int t = pq.top(), pq.pop(); - pq.push(t - t / 2), res -= t / 2; + public: + int minStoneSum(vector<int> &piles, int k) { + priority_queue<int> pq; + int res = 0; + for (int e : piles) + res += e, pq.push(e); + while (k--) { + int t = pq.top(), pq.pop(); + pq.push(t - t / 2), res -= t / 2; + } + return res; } - return res; - } }; // Using heap, constant memory class Solution { -public: - int minStoneSum(vector<int> &piles, int k) { - auto b = piles.begin(), e = piles.end(); - make_heap(b, e); - while (k--) { - pop_heap(b, e); - auto &elem = *(e - 1); - elem -= elem / 2; - push_heap(b, e); + public: + int minStoneSum(vector<int> &piles, int k) { + auto b = piles.begin(), e = piles.end(); + make_heap(b, e); + while (k--) { + pop_heap(b, e); + auto &elem = *(e - 1); + elem -= elem / 2; + push_heap(b, e); + } + int sum = 0; + for (auto v : piles) + sum += v; + return sum; } - int sum = 0; - for (auto v : piles) sum += v; - return sum; - } }; diff --git a/Problems/1964.cpp b/Problems/1964.cpp @@ -1,25 +1,25 @@ class Solution { -public: - vector<int> longestObstacleCourseAtEachPosition(vector<int> &obstacles) { - vector<int> res; - res.reserve(obstacles.size()); - vector<int> mono; - mono.reserve(obstacles.size()); + public: + vector<int> longestObstacleCourseAtEachPosition(vector<int> &obstacles) { + vector<int> res; + res.reserve(obstacles.size()); + vector<int> mono; + mono.reserve(obstacles.size()); - for (int o : obstacles) { - int left = 0, right = mono.size(); - while (left < right) { - int mid = (left + right) / 2; - if (mono[mid] <= o) - left = mid + 1; - else - right = mid; - } - res.push_back(left + 1); - if (mono.size() == left) mono.push_back(o); - mono[left] = o; - } + for (int o : obstacles) { + int left = 0, right = mono.size(); + while (left < right) { + int mid = (left + right) / 2; + if (mono[mid] <= o) + left = mid + 1; + else + right = mid; + } + res.push_back(left + 1); + if (mono.size() == left) mono.push_back(o); + mono[left] = o; + } - return res; - } + return res; + } }; diff --git a/Problems/1970.cpp b/Problems/1970.cpp @@ -1,60 +1,59 @@ class UnionFind { - int root[20002], size[20002]; + int root[20002], size[20002]; + + public: + UnionFind() { + for (int i = 0; i < 20002; i++) { + root[i] = i; + size[i] = 1; + } + } -public: - UnionFind() { - for (int i = 0; i < 20002; i++) { - root[i] = i; - size[i] = 1; + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; } - } - - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } - - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (size[x] > size[y]) swap(x, y); - root[x] = y; - size[y] += size[x]; + + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (size[x] > size[y]) swap(x, y); + root[x] = y; + size[y] += size[x]; + } } - } - bool connected(int x, int y) { return find(x) == find(y); } + bool connected(int x, int y) { return find(x) == find(y); } }; class Solution { - int grid[20000] = {0}; - -public: - int latestDayToCross(int row, int col, const vector<vector<int>> &cells) { - static const auto index = [&](int i, int j) { return i * col + j; }; - static const auto valid = [&](int i, int j) { - return i >= 0 && j >= 0 && i < row && j < col; - }; - static const int offset_x[] = {0, 0, 1, -1}; - static const int offset_y[] = {1, -1, 0, 0}; - - UnionFind uf; - - for (int i = cells.size() - 1; i >= 0; i--) { - const int x = cells[i][0] - 1, y = cells[i][1] - 1, ind = index(x, y); - grid[ind] = true; - - for (int k = 0; k < 4; k++) { - int i = x + offset_x[k], j = y + offset_y[k]; - if (!valid(i, j) || !grid[index(i, j)]) continue; - uf.join(ind, index(i, j)); - } - - if (x == 0) uf.join(ind, 20000); - if (x == row - 1) uf.join(ind, 20001); - if (uf.connected(20000, 20001)) return i; - } + int grid[20000] = {0}; + + public: + int latestDayToCross(int row, int col, const vector<vector<int>> &cells) { + static const auto index = [&](int i, int j) { return i * col + j; }; + static const auto valid = [&](int i, int j) { return i >= 0 && j >= 0 && i < row && j < col; }; + static const int offset_x[] = {0, 0, 1, -1}; + static const int offset_y[] = {1, -1, 0, 0}; + + UnionFind uf; - return row * col; - } + for (int i = cells.size() - 1; i >= 0; i--) { + const int x = cells[i][0] - 1, y = cells[i][1] - 1, ind = index(x, y); + grid[ind] = true; + + for (int k = 0; k < 4; k++) { + int i = x + offset_x[k], j = y + offset_y[k]; + if (!valid(i, j) || !grid[index(i, j)]) continue; + uf.join(ind, index(i, j)); + } + + if (x == 0) uf.join(ind, 20000); + if (x == row - 1) uf.join(ind, 20001); + if (uf.connected(20000, 20001)) return i; + } + + return row * col; + } }; diff --git a/Problems/1971.cpp b/Problems/1971.cpp @@ -1,33 +1,34 @@ class UnionFind { - vector<int> root, rank; + vector<int> root, rank; -public: - UnionFind(int n) : root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } + public: + UnionFind(int n) : root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } - void join(int x, int y) { - x = find(x), y = find(y); + void join(int x, int y) { + x = find(x), y = find(y); - if (x != y) { - if (rank[x] > rank[y]) swap(x, y); + if (x != y) { + if (rank[x] > rank[y]) swap(x, y); - root[x] = y; - rank[y] += rank[x]; + root[x] = y; + rank[y] += rank[x]; + } } - } }; class Solution { -public: - bool validPath(int n, vector<vector<int>> &edges, int source, - int destination) { - UnionFind uf(n); - for (auto &p : edges) uf.join(p[0], p[1]); + public: + bool validPath(int n, vector<vector<int>> &edges, int source, int destination) { + UnionFind uf(n); + for (auto &p : edges) + uf.join(p[0], p[1]); - return uf.find(source) == uf.find(destination); - } + return uf.find(source) == uf.find(destination); + } }; diff --git a/Problems/1976.cpp b/Problems/1976.cpp @@ -1,36 +1,36 @@ class Solution { - const int MOD = 1e9 + 7; - typedef pair<long long, int> road; + const int MOD = 1e9 + 7; + typedef pair<long long, int> road; -public: - int countPaths(int n, vector<vector<int>> &roads) { - vector<vector<road>> adj(n); - for (auto &r : roads) { - adj[r[0]].push_back({r[2], r[1]}); - adj[r[1]].push_back({r[2], r[0]}); - } + public: + int countPaths(int n, vector<vector<int>> &roads) { + vector<vector<road>> adj(n); + for (auto &r : roads) { + adj[r[0]].push_back({r[2], r[1]}); + adj[r[1]].push_back({r[2], r[0]}); + } - priority_queue<road, vector<road>, greater<road>> pq; - vector<long long> dist(n, LONG_MAX); - vector<int> count(n); - pq.push({0, 0}); - count[0] = 1; - dist[0] = 0; - while (!pq.empty()) { - auto [w, e] = pq.top(); - pq.pop(); - if (w > dist[e]) continue; - for (auto [time, v] : adj[e]) { - if (dist[v] < w + time) continue; - if (dist[v] == w + time) { - count[v] = (count[v] + count[e]) % MOD; - continue; + priority_queue<road, vector<road>, greater<road>> pq; + vector<long long> dist(n, LONG_MAX); + vector<int> count(n); + pq.push({0, 0}); + count[0] = 1; + dist[0] = 0; + while (!pq.empty()) { + auto [w, e] = pq.top(); + pq.pop(); + if (w > dist[e]) continue; + for (auto [time, v] : adj[e]) { + if (dist[v] < w + time) continue; + if (dist[v] == w + time) { + count[v] = (count[v] + count[e]) % MOD; + continue; + } + dist[v] = w + time; + count[v] = count[e]; + pq.push({dist[v], v}); + } } - dist[v] = w + time; - count[v] = count[e]; - pq.push({dist[v], v}); - } + return count[n - 1]; } - return count[n - 1]; - } }; diff --git a/Problems/1991.cpp b/Problems/1991.cpp @@ -1,12 +1,12 @@ class Solution { -public: - int findMiddleIndex(vector<int> &nums) { - int left = 0; - int right = accumulate(nums.begin(), nums.end(), 0); - for (int i = 0; i < nums.size(); left += nums[i++]) { - right -= nums[i]; - if (left == right) return i; + public: + int findMiddleIndex(vector<int> &nums) { + int left = 0; + int right = accumulate(nums.begin(), nums.end(), 0); + for (int i = 0; i < nums.size(); left += nums[i++]) { + right -= nums[i]; + if (left == right) return i; + } + return -1; } - return -1; - } }; diff --git a/Problems/2023.cpp b/Problems/2023.cpp @@ -1,15 +1,16 @@ class Solution { -public: - int numOfPairs(const vector<string> &nums, const string target) { - unordered_map<string, int> um; - for (const auto &s : nums) um[s]++; + public: + int numOfPairs(const vector<string> &nums, const string target) { + unordered_map<string, int> um; + for (const auto &s : nums) + um[s]++; - int res = 0; - for (int i = 0; i < target.size(); i++) { - const string s1 = target.substr(0, i); - const string s2 = target.substr(i); - res += (s1 != s2) ? um[s1] * um[s2] : um[s1] * (um[s1] - 1); + int res = 0; + for (int i = 0; i < target.size(); i++) { + const string s1 = target.substr(0, i); + const string s2 = target.substr(i); + res += (s1 != s2) ? um[s1] * um[s2] : um[s1] * (um[s1] - 1); + } + return res; } - return res; - } }; diff --git a/Problems/2024.cpp b/Problems/2024.cpp @@ -1,16 +1,16 @@ class Solution { -public: - int maxConsecutiveAnswers(string answerKey, int k) { - int i = 0, j = 0, res = 0, t = 0, f = 0; - while (true) { - if (min(t, f) <= k) { - if (j == answerKey.size()) break; - (answerKey[j++] == 'T' ? t : f)++; - } else { - res = max(res, j - i); - (answerKey[i++] == 'T' ? t : f)--; - } + public: + int maxConsecutiveAnswers(string answerKey, int k) { + int i = 0, j = 0, res = 0, t = 0, f = 0; + while (true) { + if (min(t, f) <= k) { + if (j == answerKey.size()) break; + (answerKey[j++] == 'T' ? t : f)++; + } else { + res = max(res, j - i); + (answerKey[i++] == 'T' ? t : f)--; + } + } + return max(res - 1, j - i); } - return max(res - 1, j - i); - } }; diff --git a/Problems/2039.cpp b/Problems/2039.cpp @@ -1,31 +1,30 @@ class Solution { -public: - int networkBecomesIdle(vector<vector<int>> &edges, vector<int> &patience) { - const int n = patience.size(); - vector<vector<int>> adj(n, vector<int>()); + public: + int networkBecomesIdle(vector<vector<int>> &edges, vector<int> &patience) { + const int n = patience.size(); + vector<vector<int>> adj(n, vector<int>()); - for (auto &p : edges) { - adj[p[0]].push_back(p[1]); - adj[p[1]].push_back(p[0]); - } + for (auto &p : edges) { + adj[p[0]].push_back(p[1]); + adj[p[1]].push_back(p[0]); + } - const int master = 0; - int time = 0; - vector<int> dist(n, 0); - queue<int> q; - q.push(0); - while (!q.empty()) { - int root = q.front(); - q.pop(); - for (int c : adj[root]) { - if (!dist[c] && c != master) { - dist[c] = dist[root] + 1; - time = max(time, ((2 * dist[c] - 1) / patience[c]) * patience[c] + - 2 * dist[c]); - q.push(c); + const int master = 0; + int time = 0; + vector<int> dist(n, 0); + queue<int> q; + q.push(0); + while (!q.empty()) { + int root = q.front(); + q.pop(); + for (int c : adj[root]) { + if (!dist[c] && c != master) { + dist[c] = dist[root] + 1; + time = max(time, ((2 * dist[c] - 1) / patience[c]) * patience[c] + 2 * dist[c]); + q.push(c); + } + } } - } + return time + 1; } - return time + 1; - } }; diff --git a/Problems/2044.cpp b/Problems/2044.cpp @@ -1,15 +1,15 @@ class Solution { - int rec(const vector<int> &nums, const int maxi, int crnt = 0, int idx = 0) { - if (idx == nums.size()) return crnt == maxi; - if (crnt == maxi) return 1 << (nums.size() - idx); - return rec(nums, maxi, crnt, idx + 1) + - rec(nums, maxi, crnt | nums[idx], idx + 1); - } + int rec(const vector<int> &nums, const int maxi, int crnt = 0, int idx = 0) { + if (idx == nums.size()) return crnt == maxi; + if (crnt == maxi) return 1 << (nums.size() - idx); + return rec(nums, maxi, crnt, idx + 1) + rec(nums, maxi, crnt | nums[idx], idx + 1); + } -public: - int countMaxOrSubsets(const vector<int> &nums) { - int maxi = 0; - for (int n : nums) maxi |= n; - return rec(nums, maxi); - } + public: + int countMaxOrSubsets(const vector<int> &nums) { + int maxi = 0; + for (int n : nums) + maxi |= n; + return rec(nums, maxi); + } }; diff --git a/Problems/2073.cpp b/Problems/2073.cpp @@ -1,12 +1,12 @@ class Solution { -public: - int timeRequiredToBuy(vector<int> &tickets, int k) { - int time = 0; - for (int i = 0; i < tickets.size(); i++) - if (tickets[i] >= tickets[k]) - time += tickets[k] - (i > k); - else - time += tickets[i]; - return time; - } + public: + int timeRequiredToBuy(vector<int> &tickets, int k) { + int time = 0; + for (int i = 0; i < tickets.size(); i++) + if (tickets[i] >= tickets[k]) + time += tickets[k] - (i > k); + else + time += tickets[i]; + return time; + } }; diff --git a/Problems/2079.cpp b/Problems/2079.cpp @@ -1,15 +1,15 @@ class Solution { -public: - int wateringPlants(const vector<int> &plants, int capacity) { - int res = plants.size(), crnt = capacity; - for (int i = 0; i < plants.size(); i++) { - if (crnt >= plants[i]) - crnt -= plants[i]; - else { - crnt = capacity - plants[i]; - res += 2 * i; - } + public: + int wateringPlants(const vector<int> &plants, int capacity) { + int res = plants.size(), crnt = capacity; + for (int i = 0; i < plants.size(); i++) { + if (crnt >= plants[i]) + crnt -= plants[i]; + else { + crnt = capacity - plants[i]; + res += 2 * i; + } + } + return res; } - return res; - } }; diff --git a/Problems/2085.cpp b/Problems/2085.cpp @@ -1,14 +1,16 @@ class Solution { -public: - int countWords(vector<string> &words1, vector<string> &words2) { - unordered_map<string, int> um1, um2; + public: + int countWords(vector<string> &words1, vector<string> &words2) { + unordered_map<string, int> um1, um2; - for (auto &t : words1) um1[t]++; - for (auto &t : words2) um2[t]++; + for (auto &t : words1) + um1[t]++; + for (auto &t : words2) + um2[t]++; - int count = 0; - for (auto &[str, cnt] : um1) - if (cnt == 1 && um2[str] == 1) count++; - return count; - } + int count = 0; + for (auto &[str, cnt] : um1) + if (cnt == 1 && um2[str] == 1) count++; + return count; + } }; diff --git a/Problems/2090.cpp b/Problems/2090.cpp @@ -1,22 +1,22 @@ class Solution { -public: - vector<int> getAverages(const vector<int> &nums, int k) { - int n = nums.size(); - if (n <= 2 * k) return vector<int>(n, -1); + public: + vector<int> getAverages(const vector<int> &nums, int k) { + int n = nums.size(); + if (n <= 2 * k) return vector<int>(n, -1); - vector<int> res(n); - long long sum = 0; - for (int i = 0; i < k; i++) { - sum += nums[i] + nums[i + k]; - res[i] = res[n - k + i] = -1; - } + vector<int> res(n); + long long sum = 0; + for (int i = 0; i < k; i++) { + sum += nums[i] + nums[i + k]; + res[i] = res[n - k + i] = -1; + } - for (int i = k; i < n - k; i++) { - sum += nums[i + k]; - res[i] = sum / (2 * k + 1); - sum -= nums[i - k]; - } + for (int i = k; i < n - k; i++) { + sum += nums[i + k]; + res[i] = sum / (2 * k + 1); + sum -= nums[i - k]; + } - return res; - } + return res; + } }; diff --git a/Problems/2095.cpp b/Problems/2095.cpp @@ -1,18 +1,18 @@ class Solution { - ListNode *pre_mid(ListNode *head) { - ListNode *slow = head, *fast = head->next; - while (fast && fast->next && fast->next->next) { - slow = slow->next; - fast = fast->next->next; + ListNode *pre_mid(ListNode *head) { + ListNode *slow = head, *fast = head->next; + while (fast && fast->next && fast->next->next) { + slow = slow->next; + fast = fast->next->next; + } + return slow; } - return slow; - } -public: - ListNode *deleteMiddle(ListNode *head) { - if (!head || !head->next) return nullptr; - ListNode *pre = pre_mid(head); - pre->next = pre->next->next; - return head; - } + public: + ListNode *deleteMiddle(ListNode *head) { + if (!head || !head->next) return nullptr; + ListNode *pre = pre_mid(head); + pre->next = pre->next->next; + return head; + } }; diff --git a/Problems/2101.cpp b/Problems/2101.cpp @@ -1,36 +1,35 @@ class Solution { -public: - int maximumDetonation(vector<vector<int>> &bombs) { - vector<vector<int>> adj(bombs.size()); - for (int i = 0; i < bombs.size(); i++) { - for (int j = i + 1; j < bombs.size(); j++) { - double dist = sqrt(pow(bombs[i][0] - bombs[j][0], 2) + - pow(bombs[i][1] - bombs[j][1], 2)); - if (dist <= bombs[i][2]) adj[i].push_back(j); - if (dist <= bombs[j][2]) adj[j].push_back(i); - } - } + public: + int maximumDetonation(vector<vector<int>> &bombs) { + vector<vector<int>> adj(bombs.size()); + for (int i = 0; i < bombs.size(); i++) { + for (int j = i + 1; j < bombs.size(); j++) { + double dist = sqrt(pow(bombs[i][0] - bombs[j][0], 2) + pow(bombs[i][1] - bombs[j][1], 2)); + if (dist <= bombs[i][2]) adj[i].push_back(j); + if (dist <= bombs[j][2]) adj[j].push_back(i); + } + } - int maxi = INT_MIN; - for (int i = 0; i < bombs.size(); i++) { - vector<bool> visited(bombs.size(), false); - int count = 0; - stack<int> st; - st.push(i); - visited[i] = true; - while (!st.empty()) { - int root = st.top(); - st.pop(); - count++; - for (int c : adj[root]) - if (!visited[c]) { - visited[c] = true; - st.push(c); - } - } - maxi = max(maxi, count); - } + int maxi = INT_MIN; + for (int i = 0; i < bombs.size(); i++) { + vector<bool> visited(bombs.size(), false); + int count = 0; + stack<int> st; + st.push(i); + visited[i] = true; + while (!st.empty()) { + int root = st.top(); + st.pop(); + count++; + for (int c : adj[root]) + if (!visited[c]) { + visited[c] = true; + st.push(c); + } + } + maxi = max(maxi, count); + } - return maxi; - } + return maxi; + } }; diff --git a/Problems/2115.cpp b/Problems/2115.cpp @@ -1,47 +1,47 @@ class Solution { - const int SIZE = 101; + const int SIZE = 101; -public: - vector<string> findAllRecipes(vector<string> &recipes, - vector<vector<string>> &ingredients, - vector<string> &supplies) { - unordered_map<string, int> hash; - unordered_set<string> us(supplies.begin(), supplies.end()); - vector<vector<int>> adj(SIZE); - vector<int> count(SIZE); - vector<string> finished; + public: + vector<string> findAllRecipes(vector<string> &recipes, vector<vector<string>> &ingredients, + vector<string> &supplies) { + unordered_map<string, int> hash; + unordered_set<string> us(supplies.begin(), supplies.end()); + vector<vector<int>> adj(SIZE); + vector<int> count(SIZE); + vector<string> finished; - for (int i = 0; i < recipes.size(); i++) hash.insert({recipes[i], i}); - for (int i = 0; i < recipes.size(); i++) { - for (string &s : ingredients[i]) - if (!us.count(s)) { - count[i]++; - if (!hash.count(s)) - count[i] = INT_MAX; - else - adj[hash[s]].push_back(i); + for (int i = 0; i < recipes.size(); i++) + hash.insert({recipes[i], i}); + for (int i = 0; i < recipes.size(); i++) { + for (string &s : ingredients[i]) + if (!us.count(s)) { + count[i]++; + if (!hash.count(s)) + count[i] = INT_MAX; + else + adj[hash[s]].push_back(i); + } } - } - queue<int> q; - for (int i = 0; i < recipes.size(); i++) { - if (!count[i]) { - q.push(i); - finished.push_back(recipes[i]); - } - } + queue<int> q; + for (int i = 0; i < recipes.size(); i++) { + if (!count[i]) { + q.push(i); + finished.push_back(recipes[i]); + } + } - while (!q.empty()) { - int root = q.front(); - q.pop(); - for (int c : adj[root]) { - if (!--count[c]) { - q.push(c); - finished.push_back(recipes[c]); + while (!q.empty()) { + int root = q.front(); + q.pop(); + for (int c : adj[root]) { + if (!--count[c]) { + q.push(c); + finished.push_back(recipes[c]); + } + } } - } - } - return finished; - } + return finished; + } }; diff --git a/Problems/2120.cpp b/Problems/2120.cpp @@ -1,29 +1,26 @@ // 2120. Execution of All Suffix Instructions Staying in a Grid class Solution { -public: - vector<int> executeInstructions(int n, const vector<int> &startPos, - string s) { - const auto valid = [n](int x, int y) { - return x >= 0 && x < n && y >= 0 && y < n; - }; + public: + vector<int> executeInstructions(int n, const vector<int> &startPos, string s) { + const auto valid = [n](int x, int y) { return x >= 0 && x < n && y >= 0 && y < n; }; - vector<int> res; - res.reserve(s.size()); - for (int k = 0; k < s.size(); k++) { - int x = startPos[0], y = startPos[1]; - for (int i = k; i < s.size(); i++) { - if (s[i] == 'L') y--; - if (s[i] == 'R') y++; - if (s[i] == 'U') x--; - if (s[i] == 'D') x++; - if (!valid(x, y)) { - res.push_back(i - k); - goto next; + vector<int> res; + res.reserve(s.size()); + for (int k = 0; k < s.size(); k++) { + int x = startPos[0], y = startPos[1]; + for (int i = k; i < s.size(); i++) { + if (s[i] == 'L') y--; + if (s[i] == 'R') y++; + if (s[i] == 'U') x--; + if (s[i] == 'D') x++; + if (!valid(x, y)) { + res.push_back(i - k); + goto next; + } + } + res.push_back(s.size() - k); + next:; } - } - res.push_back(s.size() - k); - next:; + return res; } - return res; - } }; diff --git a/Problems/2125.cpp b/Problems/2125.cpp @@ -1,18 +1,19 @@ // 2125. Number of Laser Beams in a Bank class Solution { -public: - int numberOfBeams(const vector<string> &bank) { - vector<int> count; - count.reserve(bank.size()); - for (const auto &floor : bank) { - int cnt = 0; - for (char c : floor) - if (c == '1') cnt++; - if (cnt) count.push_back(cnt); - } + public: + int numberOfBeams(const vector<string> &bank) { + vector<int> count; + count.reserve(bank.size()); + for (const auto &floor : bank) { + int cnt = 0; + for (char c : floor) + if (c == '1') cnt++; + if (cnt) count.push_back(cnt); + } - int res = 0; - for (int i = 1; i < count.size(); i++) res += count[i] * count[i - 1]; - return res; - } + int res = 0; + for (int i = 1; i < count.size(); i++) + res += count[i] * count[i - 1]; + return res; + } }; diff --git a/Problems/2130.cpp b/Problems/2130.cpp @@ -1,34 +1,34 @@ class Solution { - ListNode *pre_mid(ListNode *head) { - ListNode *slow = head, *fast = head; - while (fast->next && fast->next->next) { - slow = slow->next; - fast = fast->next->next; + ListNode *pre_mid(ListNode *head) { + ListNode *slow = head, *fast = head; + while (fast->next && fast->next->next) { + slow = slow->next; + fast = fast->next->next; + } + return slow; } - return slow; - } - ListNode *reverse(ListNode *head) { - ListNode *p = head, *q = nullptr, *r = nullptr; - while (p) { - r = q; - q = p; - p = p->next; - q->next = r; + ListNode *reverse(ListNode *head) { + ListNode *p = head, *q = nullptr, *r = nullptr; + while (p) { + r = q; + q = p; + p = p->next; + q->next = r; + } + return q; } - return q; - } -public: - int pairSum(ListNode *head) { - ListNode *pre = pre_mid(head); - ListNode *head2 = reverse(pre->next); + public: + int pairSum(ListNode *head) { + ListNode *pre = pre_mid(head); + ListNode *head2 = reverse(pre->next); - int maxi = INT_MIN; - for (ListNode *p = head, *q = head2; q; p = p->next, q = q->next) - maxi = max(p->val + q->val, maxi); + int maxi = INT_MIN; + for (ListNode *p = head, *q = head2; q; p = p->next, q = q->next) + maxi = max(p->val + q->val, maxi); - pre->next = reverse(head2); - return maxi; - } + pre->next = reverse(head2); + return maxi; + } }; diff --git a/Problems/2131.cpp b/Problems/2131.cpp @@ -1,26 +1,27 @@ class Solution { -public: - int longestPalindrome(vector<string> &words) { - unordered_map<string, int> um; - for (string &w : words) um[w]++; + public: + int longestPalindrome(vector<string> &words) { + unordered_map<string, int> um; + for (string &w : words) + um[w]++; - bool odd = false; - int res = 0; - for (const auto &[s, count] : um) { - if (!count) continue; + bool odd = false; + int res = 0; + for (const auto &[s, count] : um) { + if (!count) continue; - if (s[0] == s[1]) { - if (count % 2 == 0) { - res += count; - } else { - res += count - 1; - odd = true; + if (s[0] == s[1]) { + if (count % 2 == 0) { + res += count; + } else { + res += count - 1; + odd = true; + } + } else if (s[0] < s[1] && um.count({s[1], s[0]})) { + res += min(count, um[{s[1], s[0]}]) * 2; + } } - } else if (s[0] < s[1] && um.count({s[1], s[0]})) { - res += min(count, um[{s[1], s[0]}]) * 2; - } + if (odd) res++; + return res * 2; } - if (odd) res++; - return res * 2; - } }; diff --git a/Problems/2140.cpp b/Problems/2140.cpp @@ -1,15 +1,14 @@ class Solution { - static const int size = 1E5 + 1; - long long dp[size]; + static const int size = 1E5 + 1; + long long dp[size]; -public: - Solution() { memset(dp, 0xFF, sizeof(dp)); } + public: + Solution() { memset(dp, 0xFF, sizeof(dp)); } - long long mostPoints(const vector<vector<int>> &questions, int i = 0) { - if (i >= questions.size()) return 0; - if (dp[i] != -1) return dp[i]; - return dp[i] = max(questions[i][0] + - mostPoints(questions, i + questions[i][1] + 1), - mostPoints(questions, i + 1)); - } + long long mostPoints(const vector<vector<int>> &questions, int i = 0) { + if (i >= questions.size()) return 0; + if (dp[i] != -1) return dp[i]; + return dp[i] = max(questions[i][0] + mostPoints(questions, i + questions[i][1] + 1), + mostPoints(questions, i + 1)); + } }; diff --git a/Problems/2141.cpp b/Problems/2141.cpp @@ -1,16 +1,16 @@ class Solution { -public: - long long maxRunTime(int n, const vector<int> &batteries) { - long long low = 1, - high = reduce(batteries.begin(), batteries.end(), 0LL) / n; - while (low < high) { - long long mid = high - (high - low) / 2, sum = 0; - for (long long bat : batteries) sum += min(bat, mid); - if (sum >= (long long)(n * mid)) - low = mid; - else - high = mid - 1; + public: + long long maxRunTime(int n, const vector<int> &batteries) { + long long low = 1, high = reduce(batteries.begin(), batteries.end(), 0LL) / n; + while (low < high) { + long long mid = high - (high - low) / 2, sum = 0; + for (long long bat : batteries) + sum += min(bat, mid); + if (sum >= (long long)(n * mid)) + low = mid; + else + high = mid - 1; + } + return low; } - return low; - } }; diff --git a/Problems/2149.cpp b/Problems/2149.cpp @@ -1,11 +1,12 @@ // 2149. Rearrange Array Elements by Sign class Solution { -public: - vector<int> rearrangeArray(const vector<int> &nums) { - vector<int> res(nums.size()); - int i = -2, j = -1; - for (int num : nums) (num > 0 ? res[i += 2] : res[j += 2]) = num; + public: + vector<int> rearrangeArray(const vector<int> &nums) { + vector<int> res(nums.size()); + int i = -2, j = -1; + for (int num : nums) + (num > 0 ? res[i += 2] : res[j += 2]) = num; - return res; - } + return res; + } }; diff --git a/Problems/2161.cpp b/Problems/2161.cpp @@ -1,20 +1,22 @@ class Solution { -public: - vector<int> pivotArray(vector<int> &nums, int pivot) { - vector<int> tmp; - tmp.reserve(nums.size()); - int count = 0, idx = 0; - for (int num : nums) { - if (num == pivot) - count++; - else if (num > pivot) - tmp.push_back(num); - else - nums[idx++] = num; - } + public: + vector<int> pivotArray(vector<int> &nums, int pivot) { + vector<int> tmp; + tmp.reserve(nums.size()); + int count = 0, idx = 0; + for (int num : nums) { + if (num == pivot) + count++; + else if (num > pivot) + tmp.push_back(num); + else + nums[idx++] = num; + } - for (int i = 0; i < count; i++) nums[idx++] = pivot; - for (int num : tmp) nums[idx++] = num; - return nums; - } + for (int i = 0; i < count; i++) + nums[idx++] = pivot; + for (int num : tmp) + nums[idx++] = num; + return nums; + } }; diff --git a/Problems/2177.cpp b/Problems/2177.cpp @@ -1,8 +1,8 @@ class Solution { -public: - vector<long long> sumOfThree(long long num) { - if (num % 3) return {}; - long long a = num / 3; - return {a - 1, a, a + 1}; - } + public: + vector<long long> sumOfThree(long long num) { + if (num % 3) return {}; + long long a = num / 3; + return {a - 1, a, a + 1}; + } }; diff --git a/Problems/2181.cpp b/Problems/2181.cpp @@ -1,20 +1,20 @@ class Solution { -public: - ListNode *mergeNodes(ListNode *head) { - if (!head) return nullptr; - for (ListNode *p = head; p->next->next;) - if (p->val == 0 && p->next->val != 0 && p->next->next->val != 0) { - p->next->next->val += p->next->val; - p->next = p->next->next; - } else - p = p->next; + public: + ListNode *mergeNodes(ListNode *head) { + if (!head) return nullptr; + for (ListNode *p = head; p->next->next;) + if (p->val == 0 && p->next->val != 0 && p->next->next->val != 0) { + p->next->next->val += p->next->val; + p->next = p->next->next; + } else + p = p->next; - for (ListNode *p = head; p->next;) - if (!p->next->val) - p->next = p->next->next; - else - p = p->next; + for (ListNode *p = head; p->next;) + if (!p->next->val) + p->next = p->next->next; + else + p = p->next; - return head->val ? head : head->next; - } + return head->val ? head : head->next; + } }; diff --git a/Problems/2187.cpp b/Problems/2187.cpp @@ -1,15 +1,16 @@ class Solution { -public: - long long minimumTime(vector<int> &time, int totalTrips) { - long long low = 1, high = 1e14, mid, count; - while (low < high) { - mid = low + (high - low) / 2, count = 0; - for (long long t : time) count += mid / t; - if (count >= totalTrips) - high = mid; - else - low = mid + 1; + public: + long long minimumTime(vector<int> &time, int totalTrips) { + long long low = 1, high = 1e14, mid, count; + while (low < high) { + mid = low + (high - low) / 2, count = 0; + for (long long t : time) + count += mid / t; + if (count >= totalTrips) + high = mid; + else + low = mid + 1; + } + return low; } - return low; - } }; diff --git a/Problems/2192.cpp b/Problems/2192.cpp @@ -1,24 +1,25 @@ class Solution { -public: - vector<vector<int>> getAncestors(int n, vector<vector<int>> &edges) { - vector<vector<int>> adj(n, vector<int>()); - vector<vector<int>> anc(n, vector<int>()); + public: + vector<vector<int>> getAncestors(int n, vector<vector<int>> &edges) { + vector<vector<int>> adj(n, vector<int>()); + vector<vector<int>> anc(n, vector<int>()); - for (auto &p : edges) adj[p[0]].push_back(p[1]); - for (int i = 0; i < n; i++) { - stack<int> st; - st.push(i); - while (!st.empty()) { - int root = st.top(); - st.pop(); - for (int c : adj[root]) { - if (!anc[c].empty() && anc[c].back() == i) continue; - anc[c].push_back(i); - st.push(c); + for (auto &p : edges) + adj[p[0]].push_back(p[1]); + for (int i = 0; i < n; i++) { + stack<int> st; + st.push(i); + while (!st.empty()) { + int root = st.top(); + st.pop(); + for (int c : adj[root]) { + if (!anc[c].empty() && anc[c].back() == i) continue; + anc[c].push_back(i); + st.push(c); + } + } } - } - } - return anc; - } + return anc; + } }; diff --git a/Problems/2215.cpp b/Problems/2215.cpp @@ -1,77 +1,81 @@ // Solution 1: time O(n); space O(n) class Solution { -public: - vector<vector<int>> findDifference(vector<int> &nums1, vector<int> &nums2) { - unordered_set<int> s1(nums1.begin(), nums1.end()); - unordered_set<int> s2(nums2.begin(), nums2.end()); - vector<vector<int>> res(2); - for (auto num : s1) - if (!s2.count(num)) res[0].push_back(num); - for (auto num : s2) - if (!s1.count(num)) res[1].push_back(num); - return res; - } + public: + vector<vector<int>> findDifference(vector<int> &nums1, vector<int> &nums2) { + unordered_set<int> s1(nums1.begin(), nums1.end()); + unordered_set<int> s2(nums2.begin(), nums2.end()); + vector<vector<int>> res(2); + for (auto num : s1) + if (!s2.count(num)) res[0].push_back(num); + for (auto num : s2) + if (!s1.count(num)) res[1].push_back(num); + return res; + } }; // Solution 2: time O(nlogn); space O(1) class Solution { -public: - vector<vector<int>> findDifference(vector<int> &nums1, vector<int> &nums2) { - vector<vector<int>> res(2); + public: + vector<vector<int>> findDifference(vector<int> &nums1, vector<int> &nums2) { + vector<vector<int>> res(2); - int i = 0, j = 0; - sort(nums1.begin(), nums1.end()); - sort(nums2.begin(), nums2.end()); - while (i < nums1.size() && j < nums2.size()) { - while (i < nums1.size() - 1 && nums1[i] == nums1[i + 1]) i++; - while (j < nums2.size() - 1 && nums2[j] == nums2[j + 1]) j++; + int i = 0, j = 0; + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + while (i < nums1.size() && j < nums2.size()) { + while (i < nums1.size() - 1 && nums1[i] == nums1[i + 1]) + i++; + while (j < nums2.size() - 1 && nums2[j] == nums2[j + 1]) + j++; - if (i >= nums1.size() || j >= nums2.size()) - break; - else if (nums1[i] < nums2[j]) - res[0].push_back(nums1[i++]); - else if (nums1[i] > nums2[j]) - res[1].push_back(nums2[j++]); - else - i++, j++; - } + if (i >= nums1.size() || j >= nums2.size()) + break; + else if (nums1[i] < nums2[j]) + res[0].push_back(nums1[i++]); + else if (nums1[i] > nums2[j]) + res[1].push_back(nums2[j++]); + else + i++, j++; + } - while (i < nums1.size()) { - res[0].push_back(nums1[i]); - while (++i < nums1.size() && nums1[i - 1] == nums1[i]) - ; - } + while (i < nums1.size()) { + res[0].push_back(nums1[i]); + while (++i < nums1.size() && nums1[i - 1] == nums1[i]) + ; + } - while (j < nums2.size()) { - res[1].push_back(nums2[j]); - while (++j < nums2.size() && nums2[j - 1] == nums2[j]) - ; - } + while (j < nums2.size()) { + res[1].push_back(nums2[j]); + while (++j < nums2.size() && nums2[j - 1] == nums2[j]) + ; + } - return res; - } + return res; + } }; // Solution 3: time O(1); space O(n) class Solution { -public: - vector<vector<int>> findDifference(vector<int> &nums1, vector<int> &nums2) { - vector<vector<int>> res(2); + public: + vector<vector<int>> findDifference(vector<int> &nums1, vector<int> &nums2) { + vector<vector<int>> res(2); - bitset<2002> bs1, bs2; - for (auto num : nums1) bs1.set(num + 1000); - for (auto num : nums2) bs2.set(num + 1000); + bitset<2002> bs1, bs2; + for (auto num : nums1) + bs1.set(num + 1000); + for (auto num : nums2) + bs2.set(num + 1000); - for (int i = 0; i < 2002; i++) { - if (bs1[i] && bs2[i]) - continue; - else if (bs1[i]) - res[0].push_back(i - 1000); - else if (bs2[i]) - res[1].push_back(i - 1000); - } + for (int i = 0; i < 2002; i++) { + if (bs1[i] && bs2[i]) + continue; + else if (bs1[i]) + res[0].push_back(i - 1000); + else if (bs2[i]) + res[1].push_back(i - 1000); + } - return res; - O - } + return res; + O + } }; diff --git a/Problems/2218.cpp b/Problems/2218.cpp @@ -1,18 +1,16 @@ class Solution { - int dp[1001][2001] = {0}; + int dp[1001][2001] = {0}; -public: - int maxValueOfCoins(const vector<vector<int>> &piles, int left, - int pile = 0) { - if (!left || pile >= piles.size()) return 0; - if (dp[pile][left]) return dp[pile][left]; + public: + int maxValueOfCoins(const vector<vector<int>> &piles, int left, int pile = 0) { + if (!left || pile >= piles.size()) return 0; + if (dp[pile][left]) return dp[pile][left]; - int res = maxValueOfCoins(piles, left, pile + 1), sum = 0; - for (int i = 0; i < piles[pile].size() && i < left; i++) { - res = max(res, (sum += piles[pile][i]) + - maxValueOfCoins(piles, left - i - 1, pile + 1)); - } + int res = maxValueOfCoins(piles, left, pile + 1), sum = 0; + for (int i = 0; i < piles[pile].size() && i < left; i++) { + res = max(res, (sum += piles[pile][i]) + maxValueOfCoins(piles, left - i - 1, pile + 1)); + } - return dp[pile][left] = res; - } + return dp[pile][left] = res; + } }; diff --git a/Problems/2221.cpp b/Problems/2221.cpp @@ -1,11 +1,11 @@ class Solution { -public: - int triangularSum(vector<int> &nums) { - for (int k = 0; k < nums.size() - 1; k++) { - for (int i = 1; i < nums.size() - k; i++) { - nums[i - 1] = (nums[i - 1] + nums[i]) % 10; - } + public: + int triangularSum(vector<int> &nums) { + for (int k = 0; k < nums.size() - 1; k++) { + for (int i = 1; i < nums.size() - k; i++) { + nums[i - 1] = (nums[i - 1] + nums[i]) % 10; + } + } + return nums.front(); } - return nums.front(); - } }; diff --git a/Problems/2235.cpp b/Problems/2235.cpp @@ -1,4 +1,4 @@ class Solution { -public: - int sum(int num1, int num2) { return num1 + num2; } + public: + int sum(int num1, int num2) { return num1 + num2; } }; diff --git a/Problems/2236.cpp b/Problems/2236.cpp @@ -1,6 +1,4 @@ class Solution { -public: - bool checkTree(TreeNode *root) { - return root->val == root->left->val + root->right->val; - } + public: + bool checkTree(TreeNode *root) { return root->val == root->left->val + root->right->val; } }; diff --git a/Problems/2243.cpp b/Problems/2243.cpp @@ -1,15 +1,16 @@ class Solution { -public: - string digitSum(string s, int k) { - while (s.size() > k) { - string tmp = ""; - for (int i = 0; i < s.size();) { - int sum = 0; - for (int j = 0; j < k && i < s.size(); i++, j++) sum += s[i] - '0'; - tmp += to_string(sum); - } - s = tmp; + public: + string digitSum(string s, int k) { + while (s.size() > k) { + string tmp = ""; + for (int i = 0; i < s.size();) { + int sum = 0; + for (int j = 0; j < k && i < s.size(); i++, j++) + sum += s[i] - '0'; + tmp += to_string(sum); + } + s = tmp; + } + return s; } - return s; - } }; diff --git a/Problems/2244.cpp b/Problems/2244.cpp @@ -1,14 +1,15 @@ class Solution { -public: - int minimumRounds(vector<int> &tasks) { - unordered_map<int, int> um; - for (int t : tasks) um[t]++; + public: + int minimumRounds(vector<int> &tasks) { + unordered_map<int, int> um; + for (int t : tasks) + um[t]++; - int round = 0; - for (auto [_, c] : um) { - if (c == 1) return -1; - round += (c - 1) / 3 + 1; + int round = 0; + for (auto [_, c] : um) { + if (c == 1) return -1; + round += (c - 1) / 3 + 1; + } + return round; } - return round; - } }; diff --git a/Problems/2246.cpp b/Problems/2246.cpp @@ -1,40 +1,41 @@ class Solution { -public: - int longestPath(vector<int> &parent, string s) { - int n = parent.size(); + public: + int longestPath(vector<int> &parent, string s) { + int n = parent.size(); - vector<vector<int>> adj(n); - vector<int> pc(n, 0), count(n); - for (int i = 1; i < n; i++) pc[parent[i]]++; + vector<vector<int>> adj(n); + vector<int> pc(n, 0), count(n); + for (int i = 1; i < n; i++) + pc[parent[i]]++; - queue<int> q; - for (int i = 0; i < n; i++) - if (pc[i] == 0) q.push(i); + queue<int> q; + for (int i = 0; i < n; i++) + if (pc[i] == 0) q.push(i); - int res = 0; - while (true) { - int crnt = q.front(); - q.pop(); + int res = 0; + while (true) { + int crnt = q.front(); + q.pop(); - int mx1 = 0, mx2 = 0; - for (int c : adj[crnt]) { - int a = s[crnt] != s[c] ? count[c] : 0; - if (a > mx1) { - mx2 = mx1; - mx1 = a; - } else if (a > mx2) { - mx2 = a; + int mx1 = 0, mx2 = 0; + for (int c : adj[crnt]) { + int a = s[crnt] != s[c] ? count[c] : 0; + if (a > mx1) { + mx2 = mx1; + mx1 = a; + } else if (a > mx2) { + mx2 = a; + } + } + res = max(res, mx1 + mx2 + 1); + count[crnt] = mx1 + 1; + + if (crnt == 0) break; + int p = parent[crnt]; + adj[p].push_back(crnt); + if (!--pc[p]) q.push(p); } - } - res = max(res, mx1 + mx2 + 1); - count[crnt] = mx1 + 1; - if (crnt == 0) break; - int p = parent[crnt]; - adj[p].push_back(crnt); - if (!--pc[p]) q.push(p); + return res; } - - return res; - } }; diff --git a/Problems/2265.cpp b/Problems/2265.cpp @@ -1,33 +1,33 @@ class Solution { -public: - int averageOfSubtree(TreeNode *root) { - stack<TreeNode *> st; - unordered_map<TreeNode *, int> um; - int res = 0; + public: + int averageOfSubtree(TreeNode *root) { + stack<TreeNode *> st; + unordered_map<TreeNode *, int> um; + int res = 0; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - if (root == nullptr) { - st.pop(), root = st.top(), st.pop(); - int sum = root->val, count = 1; - if (root->left) { - sum += root->left->val; - count += um[root->left]; + st.push(root); + while (!st.empty()) { + TreeNode *root = st.top(); + if (root == nullptr) { + st.pop(), root = st.top(), st.pop(); + int sum = root->val, count = 1; + if (root->left) { + sum += root->left->val; + count += um[root->left]; + } + if (root->right) { + sum += root->right->val; + count += um[root->right]; + } + if (root->val == sum / count) res++; + um[root] = count; + root->val = sum; + continue; + } + st.push(nullptr); + if (root->left) st.push(root->left); + if (root->right) st.push(root->right); } - if (root->right) { - sum += root->right->val; - count += um[root->right]; - } - if (root->val == sum / count) res++; - um[root] = count; - root->val = sum; - continue; - } - st.push(nullptr); - if (root->left) st.push(root->left); - if (root->right) st.push(root->right); + return res; } - return res; - } }; diff --git a/Problems/2272.cpp b/Problems/2272.cpp @@ -1,24 +1,25 @@ class Solution { -public: - int largestVariance(const string &s) { - int count[27] = {0}, res = 0; - for (char c : s) count[c & 0xF]++; + public: + int largestVariance(const string &s) { + int count[27] = {0}, res = 0; + for (char c : s) + count[c & 0xF]++; - for (char ma = 'a'; ma <= 'z'; ma++) { - for (char mi = 'a'; mi <= 'z'; mi++) { - if (ma == mi || !count[ma & 0xF] || !count[mi & 0xF]) continue; - int mac = 0, mic = 0, rst = count[mi & 0xF]; - for (char c : s) { - if (c == ma) - mac++; - else if (c == mi) - mic++, rst--; + for (char ma = 'a'; ma <= 'z'; ma++) { + for (char mi = 'a'; mi <= 'z'; mi++) { + if (ma == mi || !count[ma & 0xF] || !count[mi & 0xF]) continue; + int mac = 0, mic = 0, rst = count[mi & 0xF]; + for (char c : s) { + if (c == ma) + mac++; + else if (c == mi) + mic++, rst--; - if (mic > 0) res = max(res, mac - mic); - if (mac < mic && rst > 0) mac = mic = 0; + if (mic > 0) res = max(res, mac - mic); + if (mac < mic && rst > 0) mac = mic = 0; + } + } } - } + return res; } - return res; - } }; diff --git a/Problems/2275.cpp b/Problems/2275.cpp @@ -1,11 +1,12 @@ class Solution { -public: - int largestCombination(const vector<int> &candidates) { - int res = 0, maxi = *max_element(begin(candidates), end(candidates)); - for (int mask = 1, cnt = 0; mask <= maxi; mask <<= 1, cnt = 0) { - for (int n : candidates) cnt += (n & mask) > 0; - res = max(res, cnt); + public: + int largestCombination(const vector<int> &candidates) { + int res = 0, maxi = *max_element(begin(candidates), end(candidates)); + for (int mask = 1, cnt = 0; mask <= maxi; mask <<= 1, cnt = 0) { + for (int n : candidates) + cnt += (n & mask) > 0; + res = max(res, cnt); + } + return res; } - return res; - } }; diff --git a/Problems/2279.cpp b/Problems/2279.cpp @@ -1,16 +1,16 @@ class Solution { -public: - int maximumBags(vector<int> &capacity, vector<int> &rocks, - int additionalRocks) { - for (int i = 0; i < capacity.size(); i++) rocks[i] = capacity[i] - rocks[i]; - sort(rocks.begin(), rocks.end()); + public: + int maximumBags(vector<int> &capacity, vector<int> &rocks, int additionalRocks) { + for (int i = 0; i < capacity.size(); i++) + rocks[i] = capacity[i] - rocks[i]; + sort(rocks.begin(), rocks.end()); - int res = 0; - for (int i = 0; i < capacity.size(); i++) - if (rocks[i] <= additionalRocks) - additionalRocks -= rocks[i], res++; - else - break; - return res; - } + int res = 0; + for (int i = 0; i < capacity.size(); i++) + if (rocks[i] <= additionalRocks) + additionalRocks -= rocks[i], res++; + else + break; + return res; + } }; diff --git a/Problems/2285.cpp b/Problems/2285.cpp @@ -1,21 +1,22 @@ class Solution { - typedef pair<int, int> pii; + typedef pair<int, int> pii; -public: - long long maximumImportance(int n, vector<vector<int>> &roads) { - vector<int> count(n, 0); + public: + long long maximumImportance(int n, vector<vector<int>> &roads) { + vector<int> count(n, 0); - for (auto &e : roads) { - count[e[0]]++; - count[e[1]]++; - } + for (auto &e : roads) { + count[e[0]]++; + count[e[1]]++; + } - sort(count.begin(), count.end()); + sort(count.begin(), count.end()); - long long res = 0ll; - for (int i = 0; i < n; i++) res += (i + 1ll) * count[i]; + long long res = 0ll; + for (int i = 0; i < n; i++) + res += (i + 1ll) * count[i]; - return res; - } + return res; + } }; diff --git a/Problems/2294.cpp b/Problems/2294.cpp @@ -1,12 +1,12 @@ class Solution { -public: - int partitionArray(vector<int> &nums, int k) { - sort(begin(nums), end(nums)); + public: + int partitionArray(vector<int> &nums, int k) { + sort(begin(nums), end(nums)); - int res = 1, j = 0; - for (int i = 1; i < nums.size(); i++) { - if (nums[i] - nums[j] > k) j = i, res++; + int res = 1, j = 0; + for (int i = 1; i < nums.size(); i++) { + if (nums[i] - nums[j] > k) j = i, res++; + } + return res; } - return res; - } }; diff --git a/Problems/2300.cpp b/Problems/2300.cpp @@ -1,15 +1,13 @@ class Solution { -public: - vector<int> successfulPairs(vector<int> &spells, vector<int> &potions, - long long success) { - sort(potions.begin(), potions.end()); + public: + vector<int> successfulPairs(vector<int> &spells, vector<int> &potions, long long success) { + sort(potions.begin(), potions.end()); - vector<int> res; - for (int i = 0; i < spells.size(); i++) { - auto it = lower_bound(potions.begin(), potions.end(), - ceil(success / (double)spells[i])); - res.push_back(potions.end() - it); + vector<int> res; + for (int i = 0; i < spells.size(); i++) { + auto it = lower_bound(potions.begin(), potions.end(), ceil(success / (double)spells[i])); + res.push_back(potions.end() - it); + } + return res; } - return res; - } }; diff --git a/Problems/2305.cpp b/Problems/2305.cpp @@ -1,28 +1,27 @@ class Solution { - vector<int> children = vector(8, 0); - int res = INT_MAX; + vector<int> children = vector(8, 0); + int res = INT_MAX; - void rec(const vector<int> &cookies, vector<int> &children, int k, int cur, - int zero, int maxi = 0) { - if (cookies.size() - cur < zero) return; - if (cur >= cookies.size()) { - res = min(res, maxi); - return; - } + void rec(const vector<int> &cookies, vector<int> &children, int k, int cur, int zero, int maxi = 0) { + if (cookies.size() - cur < zero) return; + if (cur >= cookies.size()) { + res = min(res, maxi); + return; + } - for (int i = 0; i < k; i++) { - zero -= children[i] == 0 ? 1 : 0; - children[i] += cookies[cur]; - rec(cookies, children, k, cur + 1, zero, max(maxi, children[i])); - children[i] -= cookies[cur]; - zero += children[i] == 0 ? 1 : 0; + for (int i = 0; i < k; i++) { + zero -= children[i] == 0 ? 1 : 0; + children[i] += cookies[cur]; + rec(cookies, children, k, cur + 1, zero, max(maxi, children[i])); + children[i] -= cookies[cur]; + zero += children[i] == 0 ? 1 : 0; + } } - } -public: - int distributeCookies(const vector<int> &cookies, int k) { - vector<int> children = vector(k, 0); - rec(cookies, children, k, 0, k); - return res; - } + public: + int distributeCookies(const vector<int> &cookies, int k) { + vector<int> children = vector(k, 0); + rec(cookies, children, k, 0, k); + return res; + } }; diff --git a/Problems/2306.cpp b/Problems/2306.cpp @@ -1,44 +1,47 @@ // Group by first letter, 637ms class Solution { -public: - long long distinctNames(vector<string> &ideas) { - array<unordered_set<string>, 26> um; - for (const auto &idea : ideas) - um[idea.front() - 'a'].insert(idea.substr(1)); + public: + long long distinctNames(vector<string> &ideas) { + array<unordered_set<string>, 26> um; + for (const auto &idea : ideas) + um[idea.front() - 'a'].insert(idea.substr(1)); - long long res = 0ll; - for (int i = 0; i < 26; i++) { - for (int j = i + 1; j < 26; j++) { - long long c1 = 0ll, c2 = 0ll; - for (const auto &s : um[i]) c1 += !um[j].count(s); - for (const auto &s : um[j]) c2 += !um[i].count(s); - res += c1 * c2; - } - } + long long res = 0ll; + for (int i = 0; i < 26; i++) { + for (int j = i + 1; j < 26; j++) { + long long c1 = 0ll, c2 = 0ll; + for (const auto &s : um[i]) + c1 += !um[j].count(s); + for (const auto &s : um[j]) + c2 += !um[i].count(s); + res += c1 * c2; + } + } - return res * 2; - } + return res * 2; + } }; // Group by suffix, 373ms class Solution { -public: - long long distinctNames(vector<string> &ideas) { - unordered_map<string, bitset<32>> um; - unordered_map<bitset<32>, int> cnt; + public: + long long distinctNames(vector<string> &ideas) { + unordered_map<string, bitset<32>> um; + unordered_map<bitset<32>, int> cnt; - for (const auto &idea : ideas) um[idea.substr(1)].set(idea.front() - 'a'); - for (const auto &[k, v] : um) cnt[v]++; + for (const auto &idea : ideas) + um[idea.substr(1)].set(idea.front() - 'a'); + for (const auto &[k, v] : um) + cnt[v]++; - long long res = 0ll; - for (auto it1 = cnt.begin(); it1 != cnt.end(); it1++) { - for (auto it2 = next(it1); it2 != cnt.end(); it2++) { - int same = (it1->first & it2->first).count(); - res += (it2->first.count() - same) * (it1->first.count() - same) * - it1->second * it2->second; - } - } + long long res = 0ll; + for (auto it1 = cnt.begin(); it1 != cnt.end(); it1++) { + for (auto it2 = next(it1); it2 != cnt.end(); it2++) { + int same = (it1->first & it2->first).count(); + res += (it2->first.count() - same) * (it1->first.count() - same) * it1->second * it2->second; + } + } - return res * 2; - } + return res * 2; + } }; diff --git a/Problems/2316.cpp b/Problems/2316.cpp @@ -1,45 +1,45 @@ class UnionFind { - int n, cnt = n; - vector<int> root, size; - -public: - UnionFind(int n) : n(n), root(n), size(n, 1) { - iota(root.begin(), root.end(), 0); - } - - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } - - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (size[x] > size[y]) swap(x, y); - root[x] = y; - size[y] += size[x]; - cnt--; + int n, cnt = n; + vector<int> root, size; + + public: + UnionFind(int n) : n(n), root(n), size(n, 1) { iota(root.begin(), root.end(), 0); } + + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } + + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (size[x] > size[y]) swap(x, y); + root[x] = y; + size[y] += size[x]; + cnt--; + } } - } - int count() { return cnt; } - bool connected(int x, int y) { return find(x) == find(y); } + int count() { return cnt; } + bool connected(int x, int y) { return find(x) == find(y); } - long long count_unreachable() { - long long res = 0; + long long count_unreachable() { + long long res = 0; - for (int i = 0; i < n; i++) - if (root[i] == i) res += (long long)size[i] * (n - size[i]); + for (int i = 0; i < n; i++) + if (root[i] == i) res += (long long)size[i] * (n - size[i]); - return res / 2; - } + return res / 2; + } }; class Solution { -public: - long long countPairs(int n, vector<vector<int>> &edges) { - UnionFind uf(n); - for (auto &e : edges) uf.join(e[0], e[1]); - return uf.count_unreachable(); - } + public: + long long countPairs(int n, vector<vector<int>> &edges) { + UnionFind uf(n); + for (auto &e : edges) + uf.join(e[0], e[1]); + return uf.count_unreachable(); + } }; diff --git a/Problems/2317.cpp b/Problems/2317.cpp @@ -1,8 +1,9 @@ class Solution { -public: - int maximumXOR(vector<int> &nums) { - int res = 0; - for (const int n : nums) res |= n; - return res; - } + public: + int maximumXOR(vector<int> &nums) { + int res = 0; + for (const int n : nums) + res |= n; + return res; + } }; diff --git a/Problems/2326.cpp b/Problems/2326.cpp @@ -1,45 +1,38 @@ class Solution { - pair<int, int> offset[4] = { - { 0, 1}, - { 1, 0}, - { 0, -1}, - {-1, 0} - }; - int limit_offset[4] = {1, -1, -1, 1}; - int limit[4] = {0, 0, 0, 0}; - - int &m = limit[2], &n = limit[1]; - - bool valid(int i, int j) { - return i >= limit[0] && i <= m && j >= limit[3] && j <= n; - } - -public: - vector<vector<int>> spiralMatrix(int dm, int dn, ListNode *head) { - vector<vector<int>> res(dm, vector<int>(dn, -1)); - int direction = 0; - int cnt = 0; - int size; - int i = 0, j = 0; - - m = dm - 1; - n = dn - 1; - size = (m + 1) * (n + 1); - - while (true) { - res[i][j] = head->val; - head = head->next; - if (!head || ++cnt == size) break; - - if (!valid(i + offset[direction].first, j + offset[direction].second)) { - limit[direction] += limit_offset[direction]; - direction = (direction + 1) % 4; - } - - i += offset[direction].first; - j += offset[direction].second; - } + pair<int, int> offset[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int limit_offset[4] = {1, -1, -1, 1}; + int limit[4] = {0, 0, 0, 0}; + + int &m = limit[2], &n = limit[1]; + + bool valid(int i, int j) { return i >= limit[0] && i <= m && j >= limit[3] && j <= n; } + + public: + vector<vector<int>> spiralMatrix(int dm, int dn, ListNode *head) { + vector<vector<int>> res(dm, vector<int>(dn, -1)); + int direction = 0; + int cnt = 0; + int size; + int i = 0, j = 0; + + m = dm - 1; + n = dn - 1; + size = (m + 1) * (n + 1); - return res; - } + while (true) { + res[i][j] = head->val; + head = head->next; + if (!head || ++cnt == size) break; + + if (!valid(i + offset[direction].first, j + offset[direction].second)) { + limit[direction] += limit_offset[direction]; + direction = (direction + 1) % 4; + } + + i += offset[direction].first; + j += offset[direction].second; + } + + return res; + } }; diff --git a/Problems/2328.cpp b/Problems/2328.cpp @@ -1,34 +1,35 @@ class Solution { - int MOD = 1E9 + 7; - int dp[1001][1001]; + int MOD = 1E9 + 7; + int dp[1001][1001]; - int n, m; - bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } + int n, m; + bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } - int rec(const vector<vector<int>> &grid, int i, int j) { - if (dp[i][j] != -1) return dp[i][j]; + int rec(const vector<vector<int>> &grid, int i, int j) { + if (dp[i][j] != -1) return dp[i][j]; - static const int offs_x[4] = {0, 0, 1, -1}; - static const int offs_y[4] = {1, -1, 0, 0}; + static const int offs_x[4] = {0, 0, 1, -1}; + static const int offs_y[4] = {1, -1, 0, 0}; - int res = 0; - for (int k = 0; k < 4; k++) { - int x = i + offs_x[k], y = j + offs_y[k]; - if (!valid(x, y)) continue; - if (grid[i][j] < grid[x][y]) res = (res + rec(grid, x, y) + 1) % MOD; + int res = 0; + for (int k = 0; k < 4; k++) { + int x = i + offs_x[k], y = j + offs_y[k]; + if (!valid(x, y)) continue; + if (grid[i][j] < grid[x][y]) res = (res + rec(grid, x, y) + 1) % MOD; + } + return dp[i][j] = res; } - return dp[i][j] = res; - } -public: - Solution() { memset(dp, 0xFF, sizeof(dp)); } - int countPaths(const vector<vector<int>> &grid) { - n = grid.size(), m = grid[0].size(); + public: + Solution() { memset(dp, 0xFF, sizeof(dp)); } + int countPaths(const vector<vector<int>> &grid) { + n = grid.size(), m = grid[0].size(); - int res = m * n; - for (int i = 0; i < n; i++) - for (int j = 0; j < m; j++) res = (res + rec(grid, i, j)) % MOD; + int res = m * n; + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + res = (res + rec(grid, i, j)) % MOD; - return res; - } + return res; + } }; diff --git a/Problems/2331.cpp b/Problems/2331.cpp @@ -1,12 +1,12 @@ class Solution { -public: - bool evaluateTree(TreeNode *root) { - switch (root->val) { - case 0: - case 1: return root->val; - case 2: return evaluateTree(root->left) || evaluateTree(root->right); - case 3: return evaluateTree(root->left) && evaluateTree(root->right); - default: return false; + public: + bool evaluateTree(TreeNode *root) { + switch (root->val) { + case 0: + case 1: return root->val; + case 2: return evaluateTree(root->left) || evaluateTree(root->right); + case 3: return evaluateTree(root->left) && evaluateTree(root->right); + default: return false; + } } - } }; diff --git a/Problems/2336.cpp b/Problems/2336.cpp @@ -1,19 +1,19 @@ class SmallestInfiniteSet { - int count = 1; - set<int> st; + int count = 1; + set<int> st; -public: - int popSmallest() { - if (!st.empty()) { - int elem = *st.begin(); - st.erase(st.begin()); - return elem; + public: + int popSmallest() { + if (!st.empty()) { + int elem = *st.begin(); + st.erase(st.begin()); + return elem; + } + return count++; } - return count++; - } - void addBack(int num) { - if (num >= count) return; - st.insert(num); - } + void addBack(int num) { + if (num >= count) return; + st.insert(num); + } }; diff --git a/Problems/2343.cpp b/Problems/2343.cpp @@ -1,4 +1,3 @@ -Formating: Problems/0164.cpp -Formating: Problems/0164.cpp -Formating: Problems/0912.cpp -Formating: Problems/2343.cpp +Formating + : Problems / + 0164.cpp Formating : Problems / 0164.cpp Formating : Problems / 0912.cpp Formating : Problems / 2343.cpp diff --git a/Problems/2348.cpp b/Problems/2348.cpp @@ -1,13 +1,13 @@ class Solution { -public: - long long zeroFilledSubarray(vector<int> &nums) { - long long res = 0, count = 0; - for (int crnt : nums) { - if (!crnt) - res += ++count; - else - count = 0; + public: + long long zeroFilledSubarray(vector<int> &nums) { + long long res = 0, count = 0; + for (int crnt : nums) { + if (!crnt) + res += ++count; + else + count = 0; + } + return res; } - return res; - } }; diff --git a/Problems/2352.cpp b/Problems/2352.cpp @@ -1,15 +1,17 @@ class Solution { -public: - int equalPairs(vector<vector<int>> &grid) { - int n = grid.size(), res = 0; - map<vector<int>, int> m; - for (const auto &vec : grid) m[vec]++; + public: + int equalPairs(vector<vector<int>> &grid) { + int n = grid.size(), res = 0; + map<vector<int>, int> m; + for (const auto &vec : grid) + m[vec]++; - for (int i = 0; i < n; i++) - for (int j = 0; j < n; j++) - if (i < j) swap(grid[i][j], grid[j][i]); + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + if (i < j) swap(grid[i][j], grid[j][i]); - for (const auto &vec : grid) res += m[vec]; - return res; - } + for (const auto &vec : grid) + res += m[vec]; + return res; + } }; diff --git a/Problems/2359.cpp b/Problems/2359.cpp @@ -1,24 +1,25 @@ class Solution { -public: - int closestMeetingNode(vector<int> &e, int node1, int node2) { - const int n = e.size(); - vector<int> d(n, -1); + public: + int closestMeetingNode(vector<int> &e, int node1, int node2) { + const int n = e.size(); + vector<int> d(n, -1); - for (int i = node1, di = 0; i != -1 && d[i] == -1; i = e[i]) d[i] = di++; + for (int i = node1, di = 0; i != -1 && d[i] == -1; i = e[i]) + d[i] = di++; - int res = -1, mini = INT_MAX; - for (int i = node2, di = 0; i != -1 && d[i] != -2; i = e[i], di++) { - int t = max(d[i], di); - if (d[i] != -1 && t <= mini) { - if (t < mini) - res = i; - else - res = min(res, i); - mini = t; - } - d[i] = -2; - } + int res = -1, mini = INT_MAX; + for (int i = node2, di = 0; i != -1 && d[i] != -2; i = e[i], di++) { + int t = max(d[i], di); + if (d[i] != -1 && t <= mini) { + if (t < mini) + res = i; + else + res = min(res, i); + mini = t; + } + d[i] = -2; + } - return res; - } + return res; + } }; diff --git a/Problems/2360.cpp b/Problems/2360.cpp @@ -1,33 +1,33 @@ class Solution { -public: - int longestCycle(vector<int> &edges) { - int n = edges.size(), res = -1; - vector<int> count(n, 0); - for (int edge : edges) - if (edge != -1) count[edge]++; + public: + int longestCycle(vector<int> &edges) { + int n = edges.size(), res = -1; + vector<int> count(n, 0); + for (int edge : edges) + if (edge != -1) count[edge]++; - queue<int> q; - for (int i = 0; i < n; i++) - if (!count[i]) q.push(i); + queue<int> q; + for (int i = 0; i < n; i++) + if (!count[i]) q.push(i); - while (!q.empty()) { - int root = q.front(); - q.pop(); - if (edges[root] == -1) continue; - if (--count[edges[root]] == 0) q.push(edges[root]); - } + while (!q.empty()) { + int root = q.front(); + q.pop(); + if (edges[root] == -1) continue; + if (--count[edges[root]] == 0) q.push(edges[root]); + } - for (int i = 0; i < n; i++) { - if (!count[i]) continue; - int k = i, num = 1; - while (edges[k] != i) { - count[k] = 0; - k = edges[k]; - num++; - } - res = max(res, num); - } + for (int i = 0; i < n; i++) { + if (!count[i]) continue; + int k = i, num = 1; + while (edges[k] != i) { + count[k] = 0; + k = edges[k]; + num++; + } + res = max(res, num); + } - return res; - } + return res; + } }; diff --git a/Problems/2368.cpp b/Problems/2368.cpp @@ -1,31 +1,30 @@ class Solution { -public: - int reachableNodes(int n, vector<vector<int>> &edges, - vector<int> &restricted) { - unordered_set<int> rest(restricted.begin(), restricted.end()); - vector<vector<int>> adj(n, vector<int>()); + public: + int reachableNodes(int n, vector<vector<int>> &edges, vector<int> &restricted) { + unordered_set<int> rest(restricted.begin(), restricted.end()); + vector<vector<int>> adj(n, vector<int>()); - for (auto &p : edges) { - if (rest.count(p[0]) || rest.count(p[1])) continue; - adj[p[0]].push_back(p[1]); - adj[p[1]].push_back(p[0]); - } + for (auto &p : edges) { + if (rest.count(p[0]) || rest.count(p[1])) continue; + adj[p[0]].push_back(p[1]); + adj[p[1]].push_back(p[0]); + } - int res = 0; - stack<int> st; - vector<bool> visited(n, false); - st.push(0); - visited[0] = true; - while (!st.empty()) { - int root = st.top(); - st.pop(); - res++; - for (int c : adj[root]) - if (!visited[c]) { - st.push(c); - visited[c] = true; + int res = 0; + stack<int> st; + vector<bool> visited(n, false); + st.push(0); + visited[0] = true; + while (!st.empty()) { + int root = st.top(); + st.pop(); + res++; + for (int c : adj[root]) + if (!visited[c]) { + st.push(c); + visited[c] = true; + } } + return res; } - return res; - } }; diff --git a/Problems/2369.cpp b/Problems/2369.cpp @@ -1,28 +1,28 @@ class Solution { - int8_t dp[100001]; + int8_t dp[100001]; -public: - Solution() { memset(dp, 0xFF, sizeof(dp)); } - bool validPartition(const vector<int> &nums, int idx = 0) { - if (idx == nums.size()) return true; - if (idx == nums.size() - 1) return false; + public: + Solution() { memset(dp, 0xFF, sizeof(dp)); } + bool validPartition(const vector<int> &nums, int idx = 0) { + if (idx == nums.size()) return true; + if (idx == nums.size() - 1) return false; - if (dp[idx] != -1) return dp[idx]; + if (dp[idx] != -1) return dp[idx]; - if (nums[idx] == nums[idx + 1]) { - if (validPartition(nums, idx + 2)) return dp[idx] = true; - } + if (nums[idx] == nums[idx + 1]) { + if (validPartition(nums, idx + 2)) return dp[idx] = true; + } - if (idx == nums.size() - 2) return dp[idx] = false; + if (idx == nums.size() - 2) return dp[idx] = false; - if (nums[idx] == nums[idx + 1] && nums[idx] == nums[idx + 2]) { - if (validPartition(nums, idx + 3)) return dp[idx] = true; - } + if (nums[idx] == nums[idx + 1] && nums[idx] == nums[idx + 2]) { + if (validPartition(nums, idx + 3)) return dp[idx] = true; + } - if (nums[idx] + 1 == nums[idx + 1] && nums[idx] + 2 == nums[idx + 2]) { - if (validPartition(nums, idx + 3)) return dp[idx] = true; - } + if (nums[idx] + 1 == nums[idx + 1] && nums[idx] + 2 == nums[idx + 2]) { + if (validPartition(nums, idx + 3)) return dp[idx] = true; + } - return dp[idx] = false; - } + return dp[idx] = false; + } }; diff --git a/Problems/2374.cpp b/Problems/2374.cpp @@ -1,19 +1,19 @@ class Solution { -public: - int edgeScore(vector<int> &edges) { - vector<long long> score(edges.size(), 0); - long long maxi = LONG_MIN; - int index = -1; + public: + int edgeScore(vector<int> &edges) { + vector<long long> score(edges.size(), 0); + long long maxi = LONG_MIN; + int index = -1; - for (int i = 0; i < edges.size(); i++) { - score[edges[i]] += i; - if (score[edges[i]] > maxi) { - maxi = score[edges[i]]; - index = edges[i]; - } else if (score[edges[i]] == maxi) - index = min(index, edges[i]); - } + for (int i = 0; i < edges.size(); i++) { + score[edges[i]] += i; + if (score[edges[i]] > maxi) { + maxi = score[edges[i]]; + index = edges[i]; + } else if (score[edges[i]] == maxi) + index = min(index, edges[i]); + } - return index; - } + return index; + } }; diff --git a/Problems/2375.cpp b/Problems/2375.cpp @@ -1,35 +1,35 @@ class Solution { - string crnt = string(9, '#'); + string crnt = string(9, '#'); - int rec(const string &pattern, uint mask = 0, uint idx = 0) { - if (idx == pattern.size() + 1) return 1; + int rec(const string &pattern, uint mask = 0, uint idx = 0) { + if (idx == pattern.size() + 1) return 1; - int start, end; - if (!idx) { - start = 1; - end = 9; - } else { - if (pattern[idx - 1] == 'I') { - start = (crnt[idx - 1] & 0xF) + 1; - end = 9; - } else { - start = 1; - end = (crnt[idx - 1] & 0xF) - 1; - } - } + int start, end; + if (!idx) { + start = 1; + end = 9; + } else { + if (pattern[idx - 1] == 'I') { + start = (crnt[idx - 1] & 0xF) + 1; + end = 9; + } else { + start = 1; + end = (crnt[idx - 1] & 0xF) - 1; + } + } - for (int i = start; i <= end; i++) { - if (mask & (1 << i)) continue; - crnt[idx] = '0' + i; - if (rec(pattern, mask | (1 << i), idx + 1)) return 1; + for (int i = start; i <= end; i++) { + if (mask & (1 << i)) continue; + crnt[idx] = '0' + i; + if (rec(pattern, mask | (1 << i), idx + 1)) return 1; + } + return 0; } - return 0; - } -public: - string smallestNumber(const string &pattern) { - crnt.resize(pattern.size() + 1); - rec(pattern); - return crnt; - } + public: + string smallestNumber(const string &pattern) { + crnt.resize(pattern.size() + 1); + rec(pattern); + return crnt; + } }; diff --git a/Problems/2390.cpp b/Problems/2390.cpp @@ -1,55 +1,55 @@ // Stack solution class Solution { -public: - string removeStars(string s) { - stack<char> st; - for (char c : s) - if (c == '*') - st.pop(); - else - st.push(c); + public: + string removeStars(string s) { + stack<char> st; + for (char c : s) + if (c == '*') + st.pop(); + else + st.push(c); - string res = ""; - while (!st.empty()) { - res += st.top(); - st.pop(); + string res = ""; + while (!st.empty()) { + res += st.top(); + st.pop(); + } + reverse(res.begin(), res.end()); + return res; } - reverse(res.begin(), res.end()); - return res; - } }; // Deque solution, avoid reversal class Solution { -public: - string removeStars(string s) { - deque<char> dq; - for (const char &c : s) - if (c == '*') - dq.pop_back(); - else - dq.push_back(c); + public: + string removeStars(string s) { + deque<char> dq; + for (const char &c : s) + if (c == '*') + dq.pop_back(); + else + dq.push_back(c); - string res = ""; - while (!dq.empty()) { - res += dq.front(); - dq.pop_front(); + string res = ""; + while (!dq.empty()) { + res += dq.front(); + dq.pop_front(); + } + return res; } - return res; - } }; // Two pointer, constant space, solution class Solution { -public: - string removeStars(string s) { - int i = 0; - for (int j = 0; j < s.size(); j++) { - if (s[j] == '*') - i--; - else - s[i++] = s[j]; + public: + string removeStars(string s) { + int i = 0; + for (int j = 0; j < s.size(); j++) { + if (s[j] == '*') + i--; + else + s[i++] = s[j]; + } + return s.substr(0, i); } - return s.substr(0, i); - } }; diff --git a/Problems/2391.cpp b/Problems/2391.cpp @@ -1,14 +1,14 @@ class Solution { -public: - int garbageCollection(const vector<string> &garbage, - const vector<int> &travel) { - int truck[4] = {0}, sum = 0, total = 0, i = 0; - while (true) { - total += garbage[i].size(); - for (char c : garbage[i]) truck[c & 3] = sum; - if (i == garbage.size() - 1) break; - sum += travel[i++]; + public: + int garbageCollection(const vector<string> &garbage, const vector<int> &travel) { + int truck[4] = {0}, sum = 0, total = 0, i = 0; + while (true) { + total += garbage[i].size(); + for (char c : garbage[i]) + truck[c & 3] = sum; + if (i == garbage.size() - 1) break; + sum += travel[i++]; + } + return total + truck[0] + truck[1] + truck[3]; } - return total + truck[0] + truck[1] + truck[3]; - } }; diff --git a/Problems/2396.cpp b/Problems/2396.cpp @@ -1,19 +1,20 @@ class Solution { -public: + public: bool isStrictlyPalindromic(int n) { return false; } }; class Solution { -public: + public: bool isStrictlyPalindromic(int n) { string s = ""; - for(int base = n - 2, crnt = n; base >= 2; base--, crnt=n) { + for (int base = n - 2, crnt = n; base >= 2; base--, crnt = n) { s.clear(); do { - s+='0' + crnt%base; - } while((crnt /= base) > 0); - int i = 0, j=s.size() - 1; - while(i < j) if(s[i++] != s[j--]) return false; + s += '0' + crnt % base; + } while ((crnt /= base) > 0); + int i = 0, j = s.size() - 1; + while (i < j) + if (s[i++] != s[j--]) return false; } return true; diff --git a/Problems/2405.cpp b/Problems/2405.cpp @@ -1,18 +1,18 @@ class Solution { -public: - int partitionString(string s) { - bitset<26> st; - int res = 0; - for (char c : s) { - int n = c - 'a'; - if (!st[n]) - st.set(n); - else { - res++; - st.reset(); - st.set(n); - } + public: + int partitionString(string s) { + bitset<26> st; + int res = 0; + for (char c : s) { + int n = c - 'a'; + if (!st[n]) + st.set(n); + else { + res++; + st.reset(); + st.set(n); + } + } + return res + 1; } - return res + 1; - } }; diff --git a/Problems/2415.cpp b/Problems/2415.cpp @@ -1,19 +1,20 @@ class Solution { -public: - TreeNode *reverseOddLevels(TreeNode *root) { - static vector<TreeNode *> vec(8192); - queue<TreeNode *> q({root}); - for (int lvl = 0; !q.empty(); lvl++) { - for (int k = q.size() - 1; k >= 0; k--) { - vec[k] = q.front(); - q.pop(); - if (vec[k]->left) q.push(vec[k]->left); - if (vec[k]->right) q.push(vec[k]->right); - } - if (lvl % 2 == 0) continue; - int i = 0, j = (1 << lvl) - 1; - while (i < j) swap(vec[i++]->val, vec[j--]->val); + public: + TreeNode *reverseOddLevels(TreeNode *root) { + static vector<TreeNode *> vec(8192); + queue<TreeNode *> q({root}); + for (int lvl = 0; !q.empty(); lvl++) { + for (int k = q.size() - 1; k >= 0; k--) { + vec[k] = q.front(); + q.pop(); + if (vec[k]->left) q.push(vec[k]->left); + if (vec[k]->right) q.push(vec[k]->right); + } + if (lvl % 2 == 0) continue; + int i = 0, j = (1 << lvl) - 1; + while (i < j) + swap(vec[i++]->val, vec[j--]->val); + } + return root; } - return root; - } }; diff --git a/Problems/2421.cpp b/Problems/2421.cpp @@ -1,54 +1,58 @@ class UnionFind { - int n, cnt = n; - vector<int> root, size; + int n, cnt = n; + vector<int> root, size; -public: - UnionFind(int n) : n(n), root(n), size(n, 1) { - iota(root.begin(), root.end(), 0); - } + public: + UnionFind(int n) : n(n), root(n), size(n, 1) { iota(root.begin(), root.end(), 0); } - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (size[x] > size[y]) swap(x, y); - root[x] = y; - size[y] += size[x]; - cnt--; + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (size[x] > size[y]) swap(x, y); + root[x] = y; + size[y] += size[x]; + cnt--; + } } - } }; class Solution { -public: - int numberOfGoodPaths(vector<int> &vals, vector<vector<int>> &edges) { - int n = vals.size(); - map<int, vector<int>> valuesToNodes; - vector<vector<int>> adj(n); - UnionFind uf(n); + public: + int numberOfGoodPaths(vector<int> &vals, vector<vector<int>> &edges) { + int n = vals.size(); + map<int, vector<int>> valuesToNodes; + vector<vector<int>> adj(n); + UnionFind uf(n); - for (auto &edge : edges) { - adj[edge[0]].push_back(edge[1]); - adj[edge[1]].push_back(edge[0]); - } + for (auto &edge : edges) { + adj[edge[0]].push_back(edge[1]); + adj[edge[1]].push_back(edge[0]); + } - for (int i = 0; i < n; i++) valuesToNodes[vals[i]].push_back(i); + for (int i = 0; i < n; i++) + valuesToNodes[vals[i]].push_back(i); - int goodPaths = 0; - for (auto &[value, nodes] : valuesToNodes) { - for (int node : nodes) { - for (int neighbor : adj[node]) { - if (vals[node] >= vals[neighbor]) { uf.join(node, neighbor); } + int goodPaths = 0; + for (auto &[value, nodes] : valuesToNodes) { + for (int node : nodes) { + for (int neighbor : adj[node]) { + if (vals[node] >= vals[neighbor]) { + uf.join(node, neighbor); + } + } + } + unordered_map<int, int> group; + for (int u : nodes) + group[uf.find(u)]++; + for (auto &[_, size] : group) + goodPaths += (size * (size + 1) / 2); } - } - unordered_map<int, int> group; - for (int u : nodes) group[uf.find(u)]++; - for (auto &[_, size] : group) goodPaths += (size * (size + 1) / 2); + return goodPaths; } - return goodPaths; - } }; diff --git a/Problems/2428.cpp b/Problems/2428.cpp @@ -1,14 +1,12 @@ class Solution { -public: - int maxSum(const vector<vector<int>> &grid) { - int m = grid.size(), n = grid[0].size(), res = 0; - for (int i = 0; i < m - 2; ++i) { - for (int j = 0; j < n - 2; ++j) - res = - max(res, grid[i + 0][j] + grid[i + 0][j + 1] + grid[i + 0][j + 2] + - grid[i + 1][j + 1] + grid[i + 2][j] + - grid[i + 2][j + 1] + grid[i + 2][j + 2]); + public: + int maxSum(const vector<vector<int>> &grid) { + int m = grid.size(), n = grid[0].size(), res = 0; + for (int i = 0; i < m - 2; ++i) { + for (int j = 0; j < n - 2; ++j) + res = max(res, grid[i + 0][j] + grid[i + 0][j + 1] + grid[i + 0][j + 2] + grid[i + 1][j + 1] + + grid[i + 2][j] + grid[i + 2][j + 1] + grid[i + 2][j + 2]); + } + return res; } - return res; - } }; diff --git a/Problems/2433.cpp b/Problems/2433.cpp @@ -1,11 +1,11 @@ class Solution { -public: - vector<int> findArray(vector<int> &pref) { - int mask = 0; - for (int &n : pref) { - n ^= mask; - mask ^= n; + public: + vector<int> findArray(vector<int> &pref) { + int mask = 0; + for (int &n : pref) { + n ^= mask; + mask ^= n; + } + return pref; } - return pref; - } }; diff --git a/Problems/2439.cpp b/Problems/2439.cpp @@ -1,11 +1,11 @@ class Solution { -public: - int minimizeArrayValue(vector<int> &nums) { - long sum = 0, res = 0; - for (int i = 0; i < nums.size(); ++i) { - sum += nums[i]; - res = max(res, (sum + i) / (i + 1)); + public: + int minimizeArrayValue(vector<int> &nums) { + long sum = 0, res = 0; + for (int i = 0; i < nums.size(); ++i) { + sum += nums[i]; + res = max(res, (sum + i) / (i + 1)); + } + return res; } - return res; - } }; diff --git a/Problems/2442.cpp b/Problems/2442.cpp @@ -1,14 +1,16 @@ class Solution { -public: - int countDistinctIntegers(const vector<int> &nums) { - unordered_set<int> us(nums.begin(), nums.end()); - for (int n : nums) { - int rev = 0; - while (n % 10 == 0) n /= 10; - do rev = (rev * 10) + n % 10; - while ((n /= 10) > 0); - us.insert(rev); + public: + int countDistinctIntegers(const vector<int> &nums) { + unordered_set<int> us(nums.begin(), nums.end()); + for (int n : nums) { + int rev = 0; + while (n % 10 == 0) + n /= 10; + do + rev = (rev * 10) + n % 10; + while ((n /= 10) > 0); + us.insert(rev); + } + return us.size(); } - return us.size(); - } }; diff --git a/Problems/2444.cpp b/Problems/2444.cpp @@ -1,19 +1,19 @@ class Solution { -public: - long long countSubarrays(vector<int> &nums, int minK, int maxK) { - int n = nums.size(), leftBound = -1, lastMin = -1, lastMax = -1; - long long count = 0; + public: + long long countSubarrays(vector<int> &nums, int minK, int maxK) { + int n = nums.size(), leftBound = -1, lastMin = -1, lastMax = -1; + long long count = 0; - for (int i = 0; i < n; i++) { - if (nums[i] < minK || nums[i] > maxK) { - leftBound = i, lastMin = -1, lastMax = -1; - continue; - } - if (nums[i] == minK) lastMin = i; - if (nums[i] == maxK) lastMax = i; - count += max(0, min(lastMin, lastMax) - leftBound); - } + for (int i = 0; i < n; i++) { + if (nums[i] < minK || nums[i] > maxK) { + leftBound = i, lastMin = -1, lastMax = -1; + continue; + } + if (nums[i] == minK) lastMin = i; + if (nums[i] == maxK) lastMax = i; + count += max(0, min(lastMin, lastMax) - leftBound); + } - return count; - } + return count; + } }; diff --git a/Problems/2448.cpp b/Problems/2448.cpp @@ -1,29 +1,29 @@ class Solution { -public: - long long minCost(const vector<int> &nums, const vector<int> &cost) { - const auto calc = [&const](int target) { - long long res = 0; - for (int i = 0; i < nums.size(); i++) - res += (long long)abs(nums[i] - target) * cost[i]; - return res; - }; + public: + long long minCost(const vector<int> &nums, const vector<int> &cost) { + const auto calc = [&const](int target) { + long long res = 0; + for (int i = 0; i < nums.size(); i++) + res += (long long)abs(nums[i] - target) * cost[i]; + return res; + }; - long left = 1L, right = 1000000L; - for (long num : nums) { - left = min(left, num); - right = max(right, num); - } + long left = 1L, right = 1000000L; + for (long num : nums) { + left = min(left, num); + right = max(right, num); + } - long ans = calc(1); - while (left < right) { - long mid = (left + right) / 2; - long y1 = calc(mid), y2 = calc(mid + 1); - ans = min(y1, y2); - if (y1 < y2) - right = mid; - else - left = mid + 1; + long ans = calc(1); + while (left < right) { + long mid = (left + right) / 2; + long y1 = calc(mid), y2 = calc(mid + 1); + ans = min(y1, y2); + if (y1 < y2) + right = mid; + else + left = mid + 1; + } + return ans; } - return ans; - } }; diff --git a/Problems/2461.cpp b/Problems/2461.cpp @@ -1,18 +1,18 @@ class Solution { -public: - long long maximumSubarraySum(vector<int> &nums, int k) { - unordered_map<int, int> mp; - long maxi = 0, sum = 0; - for (int i = 0; i < nums.size(); i++) { - sum += nums[i]; - mp[nums[i]]++; + public: + long long maximumSubarraySum(vector<int> &nums, int k) { + unordered_map<int, int> mp; + long maxi = 0, sum = 0; + for (int i = 0; i < nums.size(); i++) { + sum += nums[i]; + mp[nums[i]]++; - if (i < k - 1) continue; - if (mp.size() == k) maxi = max(maxi, sum); - int &tmp = nums[i - k + 1]; - sum -= tmp; - if (--mp[tmp] == 0) mp.erase(tmp); + if (i < k - 1) continue; + if (mp.size() == k) maxi = max(maxi, sum); + int &tmp = nums[i - k + 1]; + sum -= tmp; + if (--mp[tmp] == 0) mp.erase(tmp); + } + return maxi; } - return maxi; - } }; diff --git a/Problems/2462.cpp b/Problems/2462.cpp @@ -1,22 +1,24 @@ class Solution { -public: - long long totalCost(vector<int> &costs, int k, int candidates) { - priority_queue<int, vector<int>, greater<int>> pq1, pq2; - int i = 0, j = costs.size() - 1; - long long res = 0; - while (k--) { - while (pq1.size() < candidates && i <= j) pq1.push(costs[i++]); - while (pq2.size() < candidates && j >= i) pq2.push(costs[j--]); - int a = pq1.size() > 0 ? pq1.top() : INT_MAX; - int b = pq2.size() > 0 ? pq2.top() : INT_MAX; - if (a <= b) { - res += a; - pq1.pop(); - } else { - res += b; - pq2.pop(); - } + public: + long long totalCost(vector<int> &costs, int k, int candidates) { + priority_queue<int, vector<int>, greater<int>> pq1, pq2; + int i = 0, j = costs.size() - 1; + long long res = 0; + while (k--) { + while (pq1.size() < candidates && i <= j) + pq1.push(costs[i++]); + while (pq2.size() < candidates && j >= i) + pq2.push(costs[j--]); + int a = pq1.size() > 0 ? pq1.top() : INT_MAX; + int b = pq2.size() > 0 ? pq2.top() : INT_MAX; + if (a <= b) { + res += a; + pq1.pop(); + } else { + res += b; + pq2.pop(); + } + } + return res; } - return res; - } }; diff --git a/Problems/2465.cpp b/Problems/2465.cpp @@ -1,12 +1,12 @@ class Solution { -public: - int distinctAverages(vector<int> &nums) { - unordered_set<int> us; + public: + int distinctAverages(vector<int> &nums) { + unordered_set<int> us; - sort(nums.begin(), nums.end()); - for (int i = 0, j = nums.size() - 1; i < j; i++, j--) - us.insert(nums[i] + nums[j]); + sort(nums.begin(), nums.end()); + for (int i = 0, j = nums.size() - 1; i < j; i++, j--) + us.insert(nums[i] + nums[j]); - return us.size(); - } + return us.size(); + } }; diff --git a/Problems/2466.cpp b/Problems/2466.cpp @@ -1,14 +1,14 @@ class Solution { -public: - int countGoodStrings(int low, int high, int zero, int one) { - vector<int> dp(high + 1, 0); - dp[0] = 1; - int res = 0, mod = 1e9 + 7; - for (int i = 1; i <= high; i++) { - if (i >= zero) dp[i] = (dp[i] + dp[i - zero]) % mod; - if (i >= one) dp[i] = (dp[i] + dp[i - one]) % mod; - if (i >= low) res = (res + dp[i]) % mod; + public: + int countGoodStrings(int low, int high, int zero, int one) { + vector<int> dp(high + 1, 0); + dp[0] = 1; + int res = 0, mod = 1e9 + 7; + for (int i = 1; i <= high; i++) { + if (i >= zero) dp[i] = (dp[i] + dp[i - zero]) % mod; + if (i >= one) dp[i] = (dp[i] + dp[i - one]) % mod; + if (i >= low) res = (res + dp[i]) % mod; + } + return res; } - return res; - } }; diff --git a/Problems/2467.cpp b/Problems/2467.cpp @@ -1,72 +1,71 @@ class Solution { - vector<vector<int>> adj; - vector<bool> visited; - vector<int> distance, parent; + vector<vector<int>> adj; + vector<bool> visited; + vector<int> distance, parent; - void distance_parent(int start) { - stack<pair<int, int>> st; - st.push({start, 0}); - parent[start] = 0; - while (!st.empty()) { - int p = st.top().first; - int d = st.top().second; - st.pop(); - distance[p] = d; - for (int c : adj[p]) - if (distance[c] == -1) { - parent[c] = p; - st.push({c, d + 1}); + void distance_parent(int start) { + stack<pair<int, int>> st; + st.push({start, 0}); + parent[start] = 0; + while (!st.empty()) { + int p = st.top().first; + int d = st.top().second; + st.pop(); + distance[p] = d; + for (int c : adj[p]) + if (distance[c] == -1) { + parent[c] = p; + st.push({c, d + 1}); + } } } - } - int profit(int start, vector<int> &amount) { - stack<pair<int, int>> st; - st.push({start, 0}); + int profit(int start, vector<int> &amount) { + stack<pair<int, int>> st; + st.push({start, 0}); - int maxi = INT_MIN; - while (!st.empty()) { - int count = 0; - int root = st.top().first; - int value = st.top().second + amount[root]; - st.pop(); + int maxi = INT_MIN; + while (!st.empty()) { + int count = 0; + int root = st.top().first; + int value = st.top().second + amount[root]; + st.pop(); - visited[root] = true; - for (int c : adj[root]) - if (!visited[c]) { - count++; - st.push({c, value}); + visited[root] = true; + for (int c : adj[root]) + if (!visited[c]) { + count++; + st.push({c, value}); + } + if (!count) maxi = max(value, maxi); } - if (!count) maxi = max(value, maxi); + + return maxi; } - return maxi; - } + public: + int mostProfitablePath(vector<vector<int>> &edges, int bob, vector<int> &amount) { + int size = amount.size(); + adj.resize(size, vector<int>()); + distance.resize(size, -1); + parent.resize(size, -1); + visited.resize(size, false); -public: - int mostProfitablePath(vector<vector<int>> &edges, int bob, - vector<int> &amount) { - int size = amount.size(); - adj.resize(size, vector<int>()); - distance.resize(size, -1); - parent.resize(size, -1); - visited.resize(size, false); + for (auto &e : edges) { + adj[e[0]].push_back(e[1]); + adj[e[1]].push_back(e[0]); + } - for (auto &e : edges) { - adj[e[0]].push_back(e[1]); - adj[e[1]].push_back(e[0]); - } + distance_parent(0); - distance_parent(0); + for (int current = bob, bob_distance = 0; current; bob_distance++) { + if (distance[current] > bob_distance) + amount[current] = 0; + else if (distance[current] == bob_distance) + amount[current] /= 2; + current = parent[current]; + } - for (int current = bob, bob_distance = 0; current; bob_distance++) { - if (distance[current] > bob_distance) - amount[current] = 0; - else if (distance[current] == bob_distance) - amount[current] /= 2; - current = parent[current]; + return profit(0, amount); } - - return profit(0, amount); - } }; diff --git a/Problems/2477.cpp b/Problems/2477.cpp @@ -1,33 +1,33 @@ class Solution { -public: - long long minimumFuelCost(vector<vector<int>> &roads, int seats) { - int n = roads.size() + 1; - vector<vector<int>> adj(n, vector<int>()); - vector<int> count(n, 0); - stack<pair<int, int>> st; + public: + long long minimumFuelCost(vector<vector<int>> &roads, int seats) { + int n = roads.size() + 1; + vector<vector<int>> adj(n, vector<int>()); + vector<int> count(n, 0); + stack<pair<int, int>> st; - for (auto &p : roads) { - adj[p[0]].push_back(p[1]); - adj[p[1]].push_back(p[0]); - } + for (auto &p : roads) { + adj[p[0]].push_back(p[1]); + adj[p[1]].push_back(p[0]); + } - long long total = 0; - st.push({0, -1}); - while (!st.empty()) { - auto [root, parent] = st.top(); - st.pop(); - if (parent == -2) { - for (int c : adj[root]) { - count[root] += count[c]; - total += ceil(1.0 * count[c] / seats); + long long total = 0; + st.push({0, -1}); + while (!st.empty()) { + auto [root, parent] = st.top(); + st.pop(); + if (parent == -2) { + for (int c : adj[root]) { + count[root] += count[c]; + total += ceil(1.0 * count[c] / seats); + } + count[root]++; + continue; + } + st.push({root, -2}); + for (int c : adj[root]) + if (c != parent) st.push({c, root}); } - count[root]++; - continue; - } - st.push({root, -2}); - for (int c : adj[root]) - if (c != parent) st.push({c, root}); + return total; } - return total; - } }; diff --git a/Problems/2482.cpp b/Problems/2482.cpp @@ -1,20 +1,20 @@ class Solution { -public: - vector<vector<int>> onesMinusZeros(vector<vector<int>> &grid) { - int n = grid.size(), m = grid[0].size(); - vector<int> col(n, 0), row(m, 0); - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - col[i] += grid[i][j]; - row[j] += grid[i][j]; - } - } - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - grid[i][j] = 2 * (col[i] + row[j]) - (m + n); - } - } + public: + vector<vector<int>> onesMinusZeros(vector<vector<int>> &grid) { + int n = grid.size(), m = grid[0].size(); + vector<int> col(n, 0), row(m, 0); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + col[i] += grid[i][j]; + row[j] += grid[i][j]; + } + } + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + grid[i][j] = 2 * (col[i] + row[j]) - (m + n); + } + } - return grid; - } + return grid; + } }; diff --git a/Problems/2492.cpp b/Problems/2492.cpp @@ -1,36 +1,36 @@ class UnionFind { - int n; - vector<int> root, rank, res; + int n; + vector<int> root, rank, res; -public: - UnionFind(int n) : n(n), root(n), rank(n, 1), res(n, INT_MAX) { - iota(root.begin(), root.end(), 0); - } + public: + UnionFind(int n) : n(n), root(n), rank(n, 1), res(n, INT_MAX) { iota(root.begin(), root.end(), 0); } - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } - void join(int x, int y, int val) { - x = find(x), y = find(y); - if (x != y) { - if (rank[x] > rank[y]) swap(x, y); - res[y] = min(res[x], res[y]); - root[x] = y; - rank[y] += rank[x]; + void join(int x, int y, int val) { + x = find(x), y = find(y); + if (x != y) { + if (rank[x] > rank[y]) swap(x, y); + res[y] = min(res[x], res[y]); + root[x] = y; + rank[y] += rank[x]; + } + res[y] = min(val, res[y]); } - res[y] = min(val, res[y]); - } - int mini(int x) { return res[find(x)]; } + int mini(int x) { return res[find(x)]; } }; class Solution { -public: - int minScore(int n, vector<vector<int>> &roads) { - UnionFind uf(n + 1); - for (auto &r : roads) uf.join(r[0], r[1], r[2]); - return uf.mini(n); - } + public: + int minScore(int n, vector<vector<int>> &roads) { + UnionFind uf(n + 1); + for (auto &r : roads) + uf.join(r[0], r[1], r[2]); + return uf.mini(n); + } }; diff --git a/Problems/2497.cpp b/Problems/2497.cpp @@ -1,25 +1,26 @@ class Solution { -public: - int maxStarSum(vector<int> &vals, vector<vector<int>> &edges, int k) { - vector<vector<int>> adj(vals.size()); + public: + int maxStarSum(vector<int> &vals, vector<vector<int>> &edges, int k) { + vector<vector<int>> adj(vals.size()); - for (auto &e : edges) { - adj[e[0]].push_back(e[1]); - adj[e[1]].push_back(e[0]); - } + for (auto &e : edges) { + adj[e[0]].push_back(e[1]); + adj[e[1]].push_back(e[0]); + } - int res = INT_MIN; - for (int i = 0; i < vals.size(); i++) { - priority_queue<int, vector<int>, greater<int>> pq; - for (int c : adj[i]) { - if (vals[c] <= 0) continue; - pq.push(vals[c]); - if (pq.size() > k) pq.pop(); - } - int sum = vals[i]; - while (!pq.empty()) sum += pq.top(), pq.pop(); - res = max(res, sum); + int res = INT_MIN; + for (int i = 0; i < vals.size(); i++) { + priority_queue<int, vector<int>, greater<int>> pq; + for (int c : adj[i]) { + if (vals[c] <= 0) continue; + pq.push(vals[c]); + if (pq.size() > k) pq.pop(); + } + int sum = vals[i]; + while (!pq.empty()) + sum += pq.top(), pq.pop(); + res = max(res, sum); + } + return res; } - return res; - } }; diff --git a/Problems/2542.cpp b/Problems/2542.cpp @@ -1,24 +1,25 @@ class Solution { - typedef pair<long long, long long> elem; + typedef pair<long long, long long> elem; -public: - long long maxScore(vector<int> &nums1, vector<int> &nums2, int k) { - int n = nums1.size(); - vector<elem> arr(n); - for (int i = 0; i < n; ++i) arr[i] = {nums2[i], nums1[i]}; - sort(rbegin(arr), rend(arr)); + public: + long long maxScore(vector<int> &nums1, vector<int> &nums2, int k) { + int n = nums1.size(); + vector<elem> arr(n); + for (int i = 0; i < n; ++i) + arr[i] = {nums2[i], nums1[i]}; + sort(rbegin(arr), rend(arr)); - long long sum = 0, res = 0; - priority_queue<int, vector<int>, greater<int>> pq; - for (auto &[a, b] : arr) { - pq.emplace(b); - sum += b; - if (pq.size() > k) { - sum -= pq.top(); - pq.pop(); - } - if (pq.size() == k) res = max(res, sum * a); + long long sum = 0, res = 0; + priority_queue<int, vector<int>, greater<int>> pq; + for (auto &[a, b] : arr) { + pq.emplace(b); + sum += b; + if (pq.size() > k) { + sum -= pq.top(); + pq.pop(); + } + if (pq.size() == k) res = max(res, sum * a); + } + return res; } - return res; - } }; diff --git a/Problems/2545.cpp b/Problems/2545.cpp @@ -1,10 +1,8 @@ class Solution { -public: - vector<vector<int>> sortTheStudents(vector<vector<int>> &score, int k) { - sort(score.begin(), score.end(), - [k](const vector<int> &a, const vector<int> &b) { - return a[k] >= b[k]; - }); - return score; - } + public: + vector<vector<int>> sortTheStudents(vector<vector<int>> &score, int k) { + sort(score.begin(), score.end(), + [k](const vector<int> &a, const vector<int> &b) { return a[k] >= b[k]; }); + return score; + } }; diff --git a/Problems/2551.cpp b/Problems/2551.cpp @@ -1,15 +1,17 @@ class Solution { -public: - long long putMarbles(vector<int> &weights, int k) { - long long res = 0, n = weights.size(); + public: + long long putMarbles(vector<int> &weights, int k) { + long long res = 0, n = weights.size(); - for (int i = 0; i < n - 1; i++) weights[i] += weights[i + 1]; + for (int i = 0; i < n - 1; i++) + weights[i] += weights[i + 1]; - weights.resize(n - 1); - sort(weights.begin(), weights.end()); + weights.resize(n - 1); + sort(weights.begin(), weights.end()); - for (int i = 0; i < k - 1; i++) res += weights[n - 2 - i] - weights[i]; + for (int i = 0; i < k - 1; i++) + res += weights[n - 2 - i] - weights[i]; - return res; - } + return res; + } }; diff --git a/Problems/2610.cpp b/Problems/2610.cpp @@ -1,15 +1,15 @@ class Solution { -public: - vector<vector<int>> findMatrix(const vector<int> &nums) { - int count[201] = {0}; - vector<vector<int>> res; - for (int n : nums) { - if (count[n] >= res.size()) - res.push_back({n}); - else - res[count[n]].push_back(n); - count[n]++; + public: + vector<vector<int>> findMatrix(const vector<int> &nums) { + int count[201] = {0}; + vector<vector<int>> res; + for (int n : nums) { + if (count[n] >= res.size()) + res.push_back({n}); + else + res[count[n]].push_back(n); + count[n]++; + } + return res; } - return res; - } }; diff --git a/Problems/2616.cpp b/Problems/2616.cpp @@ -1,23 +1,23 @@ class Solution { - int count(const vector<int> &nums, int treshold) { - int cnt = 0; - for (int i = 1; i < nums.size(); i++) { - if (nums[i] - nums[i - 1] <= treshold) cnt++, i++; + int count(const vector<int> &nums, int treshold) { + int cnt = 0; + for (int i = 1; i < nums.size(); i++) { + if (nums[i] - nums[i - 1] <= treshold) cnt++, i++; + } + return cnt; } - return cnt; - } -public: - int minimizeMax(vector<int> &nums, int p) { - sort(nums.begin(), nums.end()); - int left = 0, right = nums.back() - nums.front(); - while (left < right) { - int mid = left + (right - left) / 2; - if (count(nums, mid) >= p) - right = mid; - else - left = mid + 1; + public: + int minimizeMax(vector<int> &nums, int p) { + sort(nums.begin(), nums.end()); + int left = 0, right = nums.back() - nums.front(); + while (left < right) { + int mid = left + (right - left) / 2; + if (count(nums, mid) >= p) + right = mid; + else + left = mid + 1; + } + return left; } - return left; - } }; diff --git a/Problems/2657.cpp b/Problems/2657.cpp @@ -1,25 +1,24 @@ // 2657. Find the Prefix Common Array of Two Arrays class Solution { -public: - vector<int> findThePrefixCommonArray(const vector<int> &A, - const vector<int> &B) { - vector<int> res(A.size()); - unordered_set<int> setA, setB; - for (int i = 0, count = 0; i < A.size(); i++) { - if (A[i] == B[i]) - count++; - else { - if (setB.count(A[i])) - count++; - else - setA.insert(A[i]); - if (setA.count(B[i])) - count++; - else - setB.insert(B[i]); - } - res[i] = count; + public: + vector<int> findThePrefixCommonArray(const vector<int> &A, const vector<int> &B) { + vector<int> res(A.size()); + unordered_set<int> setA, setB; + for (int i = 0, count = 0; i < A.size(); i++) { + if (A[i] == B[i]) + count++; + else { + if (setB.count(A[i])) + count++; + else + setA.insert(A[i]); + if (setA.count(B[i])) + count++; + else + setB.insert(B[i]); + } + res[i] = count; + } + return res; } - return res; - } }; diff --git a/Problems/2785.cpp b/Problems/2785.cpp @@ -1,21 +1,21 @@ class Solution { - static constexpr bool isvowel(char c) { - return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; - }; + static constexpr bool isvowel(char c) { + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; + }; -public: - string &sortVowels(string &s) { - vector<char> vowels; - for (char c : s) { - if (isvowel(tolower(c))) vowels.push_back(c); - } + public: + string &sortVowels(string &s) { + vector<char> vowels; + for (char c : s) { + if (isvowel(tolower(c))) vowels.push_back(c); + } - sort(vowels.begin(), vowels.end()); + sort(vowels.begin(), vowels.end()); - for (int i = 0, j = 0; i < s.size(); i++) { - if (isvowel(tolower(s[i]))) s[i] = vowels[j++]; - } + for (int i = 0, j = 0; i < s.size(); i++) { + if (isvowel(tolower(s[i]))) s[i] = vowels[j++]; + } - return s; - } + return s; + } }; diff --git a/Problems/2807.cpp b/Problems/2807.cpp @@ -1,18 +1,18 @@ class Solution { - int gcd(int a, int b) { - if (!a) return b; - if (!b) return a; - return gcd(b, a % b); - } + int gcd(int a, int b) { + if (!a) return b; + if (!b) return a; + return gcd(b, a % b); + } -public: - ListNode *insertGreatestCommonDivisors(ListNode *head) { - ListNode *crnt = head, *next = head->next; - while (next) { - crnt->next = new ListNode(gcd(crnt->val, next->val), next); - crnt = next; - next = next->next; + public: + ListNode *insertGreatestCommonDivisors(ListNode *head) { + ListNode *crnt = head, *next = head->next; + while (next) { + crnt->next = new ListNode(gcd(crnt->val, next->val), next); + crnt = next; + next = next->next; + } + return head; } - return head; - } }; diff --git a/Templates/MST_pq.cpp b/Templates/MST_pq.cpp @@ -2,16 +2,16 @@ // Require UnionFind int MST(int n, priority_queue<edge> &pq) { - int weight = 0; + int weight = 0; - UnionFind uf(n); - while (!pq.empty() && uf.count() != 1) { - const auto &e = pq.top(); - pq.pop(); - if (uf.connected(e[0], e[1])) continue; - uf.join(e[0], e[1]); - weight += e[2]; - } + UnionFind uf(n); + while (!pq.empty() && uf.count() != 1) { + const auto &e = pq.top(); + pq.pop(); + if (uf.connected(e[0], e[1])) continue; + uf.join(e[0], e[1]); + weight += e[2]; + } - return uf.count() == 1 ? weight : 1e9 + 7; + return uf.count() == 1 ? weight : 1e9 + 7; } diff --git a/Templates/MST_vector.cpp b/Templates/MST_vector.cpp @@ -2,15 +2,15 @@ // Require UnionFind int get_mst(int n, const vector<edge> &edges) { - int weight = 0; + int weight = 0; - UnionFind uf(n); - for (int i = 0; i < edges.size() && uf.count() != 1; i++) { - const auto &e = edges[i]; - if (uf.connected(e[0], e[1])) continue; - uf.join(e[0], e[1]); - weight += e[2]; - } + UnionFind uf(n); + for (int i = 0; i < edges.size() && uf.count() != 1; i++) { + const auto &e = edges[i]; + if (uf.connected(e[0], e[1])) continue; + uf.join(e[0], e[1]); + weight += e[2]; + } - return uf.count() == 1 ? weight : 1e9 + 7; + return uf.count() == 1 ? weight : 1e9 + 7; } diff --git a/Templates/Union_Find.cpp b/Templates/Union_Find.cpp @@ -1,30 +1,28 @@ class UnionFind { - int n, cnt = n; - vector<int> root, size; + int n, cnt = n; + vector<int> root, size; -public: - UnionFind(int n) : n(n), root(n), size(n, 1) { - iota(root.begin(), root.end(), 0); - } + public: + UnionFind(int n) : n(n), root(n), size(n, 1) { iota(root.begin(), root.end(), 0); } - UnionFind(const UnionFind &uf) - : n(uf.n), cnt(uf.cnt), root(uf.root), size(uf.size) {} + UnionFind(const UnionFind &uf) : n(uf.n), cnt(uf.cnt), root(uf.root), size(uf.size) {} - int find(int x) { - while (x != root[x]) x = root[x] = root[root[x]]; - return x; - } + int find(int x) { + while (x != root[x]) + x = root[x] = root[root[x]]; + return x; + } - void join(int x, int y) { - x = find(x), y = find(y); - if (x != y) { - if (size[x] > size[y]) swap(x, y); - root[x] = y; - size[y] += size[x]; - cnt--; + void join(int x, int y) { + x = find(x), y = find(y); + if (x != y) { + if (size[x] > size[y]) swap(x, y); + root[x] = y; + size[y] += size[x]; + cnt--; + } } - } - int count() { return cnt; } - bool connected(int x, int y) { return find(x) == find(y); } + int count() { return cnt; } + bool connected(int x, int y) { return find(x) == find(y); } }; diff --git a/Templates/bfs_floodfill.cpp b/Templates/bfs_floodfill.cpp @@ -2,28 +2,23 @@ typedef vector<vector<int>> Matrix; typedef queue<pair<int, int>> Queue; -const vector<pair<int, int>> offsets = { - { 0, 1}, - { 0, -1}, - { 1, 0}, - {-1, 0} -}; +const vector<pair<int, int>> offsets = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; int n, m; int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } void dfs(Matrix &mat, int x, int y) { - Queue q; + Queue q; - q.push({x, y}), mat[x][y] = 2; - while (!q.empty()) { - auto [a, b] = q.front(); - q.pop(); - for (auto [oa, ob] : offsets) { - int x = a + oa, y = b + ob; - if (!valid(x, y) || mat[x][y] == 0 || mat[x][y] != 1) continue; - mat[x][y] = 2; - q.push({x, y}); + q.push({x, y}), mat[x][y] = 2; + while (!q.empty()) { + auto [a, b] = q.front(); + q.pop(); + for (auto [oa, ob] : offsets) { + int x = a + oa, y = b + ob; + if (!valid(x, y) || mat[x][y] == 0 || mat[x][y] != 1) continue; + mat[x][y] = 2; + q.push({x, y}); + } } - } } diff --git a/Templates/bfs_floodfill_recursive.cpp b/Templates/bfs_floodfill_recursive.cpp @@ -2,26 +2,21 @@ typedef vector<vector<int>> Matrix; typedef vector<vector<bool>> Marked; -const vector<pair<int, int>> offsets = { - { 0, 1}, - { 0, -1}, - { 1, 0}, - {-1, 0} -}; +const vector<pair<int, int>> offsets = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; int n, m; int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } bool dfs(const Matrix &mat, Marked &mark, int a, int b) { - if (got == word.size()) return true; + if (got == word.size()) return true; - mark[a][b] = true; - for (auto [oa, ob] : offsets) { - int x = a + oa, y = b + ob; - if (!valid(x, y) || mark[x][y]) continue; - if (dfs(mat, mark, x, y)) return true; - } - mark[a][b] = false; + mark[a][b] = true; + for (auto [oa, ob] : offsets) { + int x = a + oa, y = b + ob; + if (!valid(x, y) || mark[x][y]) continue; + if (dfs(mat, mark, x, y)) return true; + } + mark[a][b] = false; - return false; + return false; }