diff --git a/Cargo.lock b/Cargo.lock index a8df0eae..a4de3d0e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,10 +3,58 @@ version = 3 [[package]] -name = "adler32" -version = "1.0.4" +name = "aead" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fc95d1bdb8e6666b2b217308eeeb09f2d6728d104be3e31916cc74d15420331" +dependencies = [ + "generic-array", +] + +[[package]] +name = "aes" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "884391ef1066acaa41e766ba8f596341b96e93ce34f9a43e7d24bf0a0eaf0561" +dependencies = [ + "aes-soft", + "aesni", + "cipher", +] + +[[package]] +name = "aes-gcm" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d2e7343e7fc9de883d1b0341e0b13970f764c14101234857d2ddafa1cb1cac2" +checksum = "5278b5fabbb9bd46e24aa69b2fdea62c99088e0a950a9be40e3e0101298f88da" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aes-soft" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be14c7498ea50828a38d0e24a765ed2effe92a705885b57d029cd67d45744072" +dependencies = [ + "cipher", + "opaque-debug", +] + +[[package]] +name = "aesni" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea2e11f5e94c2f7d386164cc2aa1f97823fed6f259e486940a71c174dd01b0ce" +dependencies = [ + "cipher", + "opaque-debug", +] [[package]] name = "aho-corasick" @@ -24,53 +72,153 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7825f6833612eb2414095684fcf6c635becf3ce97fe48cf6421321e93bfbd53c" [[package]] -name = "autocfg" -version = "0.1.6" +name = "async-channel" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b671c8fb71b457dd4ae18c4ba1e59aa81793daacc361d82fcd410cef0d491875" +checksum = "2114d64672151c0c5eaa5e131ec84a74f06e1e559830dabba01ca30605d66319" +dependencies = [ + "concurrent-queue", + "event-listener", + "futures-core", +] [[package]] -name = "autocfg" -version = "1.1.0" +name = "async-executor" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" +checksum = "90f47c78ea98277cb1f5e6f60ba4fc762f5eafe9f6511bc2f7dfd8b75c225650" +dependencies = [ + "async-io", + "futures-lite 0.1.11", + "multitask", + "parking 1.0.6", + "scoped-tls", + "waker-fn", +] [[package]] -name = "backtrace" -version = "0.3.38" +name = "async-io" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "690a62be8920ccf773ee00ef0968649b0e724cda8bd5b12286302b4ae955fdf5" +checksum = "3ae22a338d28c75b53702b66f77979062cb29675db376d99e451af4fa79dedb3" dependencies = [ - "backtrace-sys", "cfg-if 0.1.10", + "concurrent-queue", + "futures-lite 0.1.11", "libc", - "rustc-demangle", + "once_cell", + "parking 2.0.0", + "polling", + "socket2 0.3.19", + "vec-arena", + "wepoll-sys-stjepang", + "winapi", ] [[package]] -name = "backtrace-sys" -version = "0.1.31" +name = "async-mutex" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82a830b4ef2d1124a711c71d263c5abdc710ef8e907bd508c88be475cebc422b" +checksum = "479db852db25d9dbf6204e6cb6253698f175c15726470f78af0d918e99d6156e" dependencies = [ - "cc", - "libc", + "event-listener", ] [[package]] -name = "base64" -version = "0.10.1" +name = "async-std" +version = "1.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c8da367da62b8ff2313c406c9ac091c1b31d67a165becdd2de380d846260f7" +dependencies = [ + "async-executor", + "async-io", + "async-mutex", + "async-task", + "blocking", + "crossbeam-utils", + "futures-channel", + "futures-core", + "futures-io", + "futures-lite 0.1.11", + "kv-log-macro", + "log", + "memchr", + "num_cpus", + "once_cell", + "pin-project-lite 0.1.12", + "pin-utils", + "slab", + "wasm-bindgen-futures", +] + +[[package]] +name = "async-task" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e" +checksum = "c17772156ef2829aadc587461c7753af20b7e8db1529bc66855add962a3b35d3" + +[[package]] +name = "async-trait" +version = "0.1.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76464446b8bc32758d7e88ee1a804d9914cd9b1cb264c029899680b0be29826f" dependencies = [ - "byteorder", + "proc-macro2", + "quote", + "syn", ] +[[package]] +name = "atomic-waker" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "065374052e7df7ee4047b1160cca5e1467a12351a40b3da123c870ba0b8eda2a" + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "base-x" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cbbc9d0964165b47557570cce6c952866c2678457aca742aafc9fb771d30270" + +[[package]] +name = "base64" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" + [[package]] name = "bitflags" -version = "1.2.0" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "block-buffer" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" +dependencies = [ + "generic-array", +] + +[[package]] +name = "blocking" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5800d29218fea137b0880387e5948694a23c93fcdde157006966693a865c7c" +dependencies = [ + "async-channel", + "atomic-waker", + "futures-lite 0.1.11", + "once_cell", + "waker-fn", +] [[package]] name = "bumpalo" @@ -79,21 +227,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37ccbd214614c6783386c1af30caf03192f17891059cecc394b4fb119e363de3" [[package]] -name = "byteorder" -version = "1.3.2" +name = "bytes" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7c3dd8985a7111efc5c80b44e23ecdd8c007de8ade3b96595387e812b957cf5" +checksum = "0e4cec68f03f32e44924783795810fa50a7035d8c8ebe78580ad7e6c703fba38" [[package]] name = "bytes" -version = "0.4.12" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "206fdffcfa2df7cbe15601ef46c813fce0965eb3286db6b56c583b814b51c81c" -dependencies = [ - "byteorder", - "either", - "iovec", -] +checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db" [[package]] name = "c2-chacha" @@ -105,6 +248,12 @@ dependencies = [ "ppv-lite86", ] +[[package]] +name = "cache-padded" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1db59621ec70f09c5e9b597b220c7a2b43611f4710dc03ceb8748637775692c" + [[package]] name = "cc" version = "1.0.45" @@ -124,47 +273,51 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] -name = "cloudabi" -version = "0.0.3" +name = "cipher" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +checksum = "12f8e7987cbd042a63249497f41aed09f8e65add917ea6566effbc56578d6801" dependencies = [ - "bitflags", + "generic-array", ] [[package]] -name = "cookie" -version = "0.12.0" +name = "concurrent-queue" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "888604f00b3db336d2af898ec3c1d5d0ddf5e6d462220f2ededc33a87ac4bbd5" +checksum = "af4780a44ab5696ea9e28294517f1fffb421a83a25af521333c838635509db9c" dependencies = [ - "time", - "url 1.7.2", + "cache-padded", ] [[package]] -name = "cookie_store" -version = "0.7.0" +name = "const_fn" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46750b3f362965f197996c4448e4a0935e791bf7d6631bfce9ee0af3d24c919c" +checksum = "fbdcdcb6d86f71c5e97409ad45898af11cbc995b4ee8112d59095a28d376c935" + +[[package]] +name = "cookie" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03a5d7b21829bc7b4bf4754a978a241ae54ea55a40f92bb20216e54096f4b951" dependencies = [ - "cookie", - "failure", - "idna 0.1.5", - "log", - "publicsuffix", - "serde", - "serde_json", + "aes-gcm", + "base64", + "hkdf", + "hmac", + "percent-encoding", + "rand 0.8.5", + "sha2", "time", - "try_from", - "url 1.7.2", + "version_check 0.9.4", ] [[package]] name = "core-foundation" -version = "0.6.4" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25b9e03f145fd4f2bf705e07b900cd41fc636598fe5dc452fd0db1441c3f496d" +checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" dependencies = [ "core-foundation-sys", "libc", @@ -172,82 +325,63 @@ dependencies = [ [[package]] name = "core-foundation-sys" -version = "0.6.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7ca8a5221364ef15ce201e8ed2f609fc312682a8f4e0e3d4aa5879764e0fa3b" +checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc" [[package]] -name = "crc32fast" -version = "1.2.0" +name = "cpufeatures" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1" +checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" dependencies = [ - "cfg-if 0.1.10", + "libc", ] [[package]] -name = "crossbeam-channel" -version = "0.3.9" +name = "cpuid-bool" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8ec7fcd21571dc78f96cc96243cab8d8f035247c3efd16c687be154c3fa9efa" -dependencies = [ - "crossbeam-utils 0.6.6", -] +checksum = "dcb25d077389e53838a8158c8e99174c5a9d902dee4904320db714f3c653ffba" [[package]] -name = "crossbeam-deque" -version = "0.7.4" +name = "crossbeam-channel" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c20ff29ded3204c5106278a81a38f4b482636ed4fa1e6cfbeef193291beb29ed" +checksum = "b153fe7cbef478c567df0f972e02e6d736db11affe43dfc9c56a9374d1adfb87" dependencies = [ - "crossbeam-epoch", - "crossbeam-utils 0.7.2", + "crossbeam-utils", "maybe-uninit", ] [[package]] -name = "crossbeam-epoch" -version = "0.8.2" +name = "crossbeam-utils" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" +checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" dependencies = [ - "autocfg 1.1.0", + "autocfg", "cfg-if 0.1.10", - "crossbeam-utils 0.7.2", "lazy_static", - "maybe-uninit", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-queue" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c979cd6cfe72335896575c6b5688da489e420d36a27a0b9eb0c73db574b4a4b" -dependencies = [ - "crossbeam-utils 0.6.6", ] [[package]] -name = "crossbeam-utils" -version = "0.6.6" +name = "crypto-mac" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04973fa96e96579258a5091af6003abde64af786b860f18622b82e026cca60e6" +checksum = "bff07008ec701e8028e2ceb8f83f0e4274ee62bd2dbdc4fefff2e9a91824081a" dependencies = [ - "cfg-if 0.1.10", - "lazy_static", + "generic-array", + "subtle", ] [[package]] -name = "crossbeam-utils" -version = "0.7.2" +name = "ctr" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" +checksum = "fb4a30d54f7443bf3d6191dcd486aca19e67cb3c49fa7a06a319966346707e7f" dependencies = [ - "autocfg 1.1.0", - "cfg-if 0.1.10", - "lazy_static", + "cipher", ] [[package]] @@ -261,15 +395,15 @@ dependencies = [ "openssl-probe", "openssl-sys", "schannel", - "socket2", - "winapi 0.3.8", + "socket2 0.3.19", + "winapi", ] [[package]] name = "curl-sys" -version = "0.4.25" +version = "0.4.56+curl-7.83.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c38ca47d60b86d0cc9d42caa90a0885669c2abc9791f871c81f58cdf39e979b" +checksum = "6093e169dd4de29e468fa649fbae11cdcd5551c81fe5bf1b0677adad7ef3d26f" dependencies = [ "cc", "libc", @@ -278,20 +412,23 @@ dependencies = [ "openssl-sys", "pkg-config", "vcpkg", - "winapi 0.3.8", + "winapi", ] [[package]] -name = "dtoa" -version = "0.4.4" +name = "digest" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea57b42383d091c85abcc2706240b94ab2a8fa1fc81c10ff23c4de06e2a90b5e" +checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +dependencies = [ + "generic-array", +] [[package]] -name = "either" -version = "1.5.3" +name = "discard" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" +checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0" [[package]] name = "encoding_rs" @@ -303,47 +440,18 @@ dependencies = [ ] [[package]] -name = "error-chain" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ab49e9dcb602294bc42f9a7dfc9bc6e936fca4418ea300dbfb84fe16de0b7d9" -dependencies = [ - "backtrace", - "version_check", -] - -[[package]] -name = "failure" -version = "0.1.5" +name = "event-listener" +version = "2.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "795bd83d3abeb9220f257e597aa0080a508b27533824adf336529648f6abf7e2" -dependencies = [ - "backtrace", - "failure_derive", -] - -[[package]] -name = "failure_derive" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea1063915fd7ef4309e222a5a07cf9c319fb9c7836b1f89b85458672dbb127e1" -dependencies = [ - "proc-macro2 0.4.30", - "quote 0.6.13", - "syn 0.15.44", - "synstructure", -] +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" [[package]] -name = "flate2" -version = "1.0.12" +name = "fastrand" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad3c5233c9a940c8719031b423d7e6c16af66e031cb0420b0896f5245bf181d3" +checksum = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499" dependencies = [ - "cfg-if 0.1.10", - "crc32fast", - "libc", - "miniz_oxide", + "instant", ] [[package]] @@ -368,38 +476,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] -name = "fuchsia-cprng" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" - -[[package]] -name = "fuchsia-zircon" -version = "0.3.3" +name = "form_urlencoded" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" +checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" dependencies = [ - "bitflags", - "fuchsia-zircon-sys", + "matches", + "percent-encoding", ] -[[package]] -name = "fuchsia-zircon-sys" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" - -[[package]] -name = "futures" -version = "0.1.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b980f2816d6ee8673b6517b52cb0e808a180efc92e5c19d02cdda79066703ef" - [[package]] name = "futures" -version = "0.3.4" +version = "0.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c329ae8753502fb44ae4fc2b622fa2a94652c41e795143765ba0927f92ab780" +checksum = "f73fe65f54d1e12b726f517d3e2135ca3125a437b6d998caf1962961f7172d9e" dependencies = [ "futures-channel", "futures-core", @@ -420,43 +510,17 @@ dependencies = [ "futures-sink", ] -[[package]] -name = "futures-channel-preview" -version = "0.3.0-alpha.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5e5f4df964fa9c1c2f8bddeb5c3611631cacd93baf810fc8bb2fb4b495c263a" -dependencies = [ - "futures-core-preview", - "futures-sink-preview", -] - [[package]] name = "futures-core" version = "0.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c09fd04b7e4073ac7156a9539b57a484a8ea920f79c7c675d05d289ab6110d3" -[[package]] -name = "futures-core-preview" -version = "0.3.0-alpha.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b35b6263fb1ef523c3056565fa67b1d16f0a8604ff12b11b08c25f28a734c60a" - -[[package]] -name = "futures-cpupool" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab90cde24b3319636588d0c35fe03b1333857621051837ed769faefb4c2162e4" -dependencies = [ - "futures 0.1.29", - "num_cpus", -] - [[package]] name = "futures-executor" -version = "0.3.4" +version = "0.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f674f3e1bcb15b37284a90cedf55afdba482ab061c407a9c0ebbd0f3109741ba" +checksum = "9420b90cfa29e327d0429f19be13e7ddb68fa1cccb09d65e5706b8c7a749b8a6" dependencies = [ "futures-core", "futures-task", @@ -464,17 +528,6 @@ dependencies = [ "num_cpus", ] -[[package]] -name = "futures-executor-preview" -version = "0.3.0-alpha.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75236e88bd9fe88e5e8bfcd175b665d0528fe03ca4c5207fabc028c8f9d93e98" -dependencies = [ - "futures-core-preview", - "futures-util-preview", - "num_cpus", -] - [[package]] name = "futures-io" version = "0.3.21" @@ -482,34 +535,44 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc4045962a5a5e935ee2fdedaa4e08284547402885ab326734432bed5d12966b" [[package]] -name = "futures-io-preview" -version = "0.3.0-alpha.19" +name = "futures-lite" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4914ae450db1921a56c91bde97a27846287d062087d4a652efc09bb3a01ebda" +checksum = "97999970129b808f0ccba93211201d431fcc12d7e1ffae03a61b5cedd1a7ced2" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "memchr", + "parking 2.0.0", + "pin-project-lite 0.1.12", + "waker-fn", +] [[package]] -name = "futures-macro" -version = "0.3.21" +name = "futures-lite" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33c1e13800337f4d4d7a316bf45a567dbcb6ffe087f16424852d97e97a91f512" +checksum = "7694489acd39452c77daa48516b894c153f192c3578d5a839b62c58099fcbf48" dependencies = [ - "proc-macro2 1.0.39", - "quote 1.0.2", - "syn 1.0.96", + "fastrand", + "futures-core", + "futures-io", + "memchr", + "parking 2.0.0", + "pin-project-lite 0.2.9", + "waker-fn", ] [[package]] -name = "futures-preview" -version = "0.3.0-alpha.19" +name = "futures-macro" +version = "0.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b1dce2a0267ada5c6ff75a8ba864b4e679a9e2aa44262af7a3b5516d530d76e" +checksum = "33c1e13800337f4d4d7a316bf45a567dbcb6ffe087f16424852d97e97a91f512" dependencies = [ - "futures-channel-preview", - "futures-core-preview", - "futures-executor-preview", - "futures-io-preview", - "futures-sink-preview", - "futures-util-preview", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -518,12 +581,6 @@ version = "0.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21163e139fa306126e6eedaf49ecdb4588f939600f0b1e770f4205ee4b7fa868" -[[package]] -name = "futures-sink-preview" -version = "0.3.0-alpha.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86f148ef6b69f75bb610d4f9a2336d4fc88c4b5b67129d1a340dd0fd362efeec" - [[package]] name = "futures-task" version = "0.3.21" @@ -543,26 +600,19 @@ dependencies = [ "futures-sink", "futures-task", "memchr", - "pin-project-lite", + "pin-project-lite 0.2.9", "pin-utils", "slab", ] [[package]] -name = "futures-util-preview" -version = "0.3.0-alpha.19" +name = "generic-array" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ce968633c17e5f97936bd2797b6e38fb56cf16a7422319f7ec2e30d3c470e8d" +checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" dependencies = [ - "futures 0.1.29", - "futures-channel-preview", - "futures-core-preview", - "futures-io-preview", - "futures-sink-preview", - "memchr", - "pin-utils", - "slab", - "tokio-io", + "typenum", + "version_check 0.9.4", ] [[package]] @@ -573,113 +623,196 @@ checksum = "473a1265acc8ff1e808cd0a1af8cee3c2ee5200916058a2ca113c29f2d903571" dependencies = [ "cfg-if 0.1.10", "libc", - "wasi", + "wasi 0.7.0", +] + +[[package]] +name = "getrandom" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" +dependencies = [ + "cfg-if 1.0.0", + "libc", + "wasi 0.11.0+wasi-snapshot-preview1", +] + +[[package]] +name = "ghash" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97304e4cd182c3846f7575ced3890c53012ce534ad9114046b0a9e00bb30a375" +dependencies = [ + "opaque-debug", + "polyval", ] [[package]] name = "h2" -version = "0.1.26" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5b34c246847f938a410a03c5458c7fee2274436675e76d8b903c08efc29c462" +checksum = "37a82c6d637fc9515a4694bbf1cb2457b79d81ce52b3108bdeea58b07dd34a57" dependencies = [ - "byteorder", - "bytes", + "bytes 1.2.1", "fnv", - "futures 0.1.29", + "futures-core", + "futures-sink", + "futures-util", "http", "indexmap", - "log", "slab", - "string", - "tokio-io", + "tokio", + "tokio-util", + "tracing", ] [[package]] -name = "heck" -version = "0.3.1" +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hermit-abi" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" dependencies = [ - "unicode-segmentation", + "libc", +] + +[[package]] +name = "hkdf" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51ab2f639c231793c5f6114bdb9bbe50a7dbbfcd7c7c6bd8475dec2d991e964f" +dependencies = [ + "digest", + "hmac", +] + +[[package]] +name = "hmac" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1441c6b1e930e2817404b5046f1f989899143a12bf92de603b69f4e0aee1e15" +dependencies = [ + "crypto-mac", + "digest", ] [[package]] name = "http" -version = "0.1.21" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6ccf5ede3a895d8856620237b2f02972c1bbc78d2965ad7fe8838d4a0ed41f0" +checksum = "75f43d41e26995c17e71ee126451dd3941010b0514a81a9d11f3b341debc2399" dependencies = [ - "bytes", + "bytes 1.2.1", "fnv", "itoa", ] [[package]] name = "http-body" -version = "0.1.0" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6741c859c1b2463a423a1dbce98d418e6c3c3fc720fb0d45528657320920292d" +checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" dependencies = [ - "bytes", - "futures 0.1.29", + "bytes 1.2.1", "http", - "tokio-buf", + "pin-project-lite 0.2.9", +] + +[[package]] +name = "http-client" +version = "6.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1947510dc91e2bf586ea5ffb412caad7673264e14bb39fb9078da114a94ce1a5" +dependencies = [ + "async-std", + "async-trait", + "cfg-if 1.0.0", + "http-types", + "isahc", + "log", +] + +[[package]] +name = "http-types" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9b187a72d63adbfba487f48095306ac823049cb504ee195541e91c7775f5ad" +dependencies = [ + "anyhow", + "async-channel", + "async-std", + "base64", + "cookie", + "futures-lite 1.12.0", + "infer", + "pin-project-lite 0.2.9", + "rand 0.7.3", + "serde", + "serde_json", + "serde_qs", + "serde_urlencoded", + "url", ] [[package]] name = "httparse" -version = "1.3.4" +version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9" +checksum = "496ce29bb5a52785b44e0f7ca2847ae0bb839c9bd28f69acac9b99d461c0c04c" + +[[package]] +name = "httpdate" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" [[package]] name = "hyper" -version = "0.12.36" +version = "0.14.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c843caf6296fc1f93444735205af9ed4e109a539005abb2564ae1d6fad34c52" +checksum = "02c929dc5c39e335a03c405292728118860721b10190d98c2a0f0efd5baafbac" dependencies = [ - "bytes", - "futures 0.1.29", - "futures-cpupool", + "bytes 1.2.1", + "futures-channel", + "futures-core", + "futures-util", "h2", "http", "http-body", "httparse", - "iovec", + "httpdate", "itoa", - "log", - "net2", - "rustc_version", - "time", + "pin-project-lite 0.2.9", + "socket2 0.4.4", "tokio", - "tokio-buf", - "tokio-executor", - "tokio-io", - "tokio-reactor", - "tokio-tcp", - "tokio-threadpool", - "tokio-timer", + "tower-service", + "tracing", "want", ] [[package]] name = "hyper-tls" -version = "0.3.2" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a800d6aa50af4b5850b2b0f659625ce9504df908e9733b635720483be26174f" +checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" dependencies = [ - "bytes", - "futures 0.1.29", + "bytes 1.2.1", "hyper", "native-tls", - "tokio-io", + "tokio", + "tokio-native-tls", ] [[package]] name = "idna" -version = "0.1.5" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e" +checksum = "02e2673c30ee86b5b96a9cb52ad15718aa1f966f5ab9ad54a8b95d5ca33120a9" dependencies = [ "matches", "unicode-bidi", @@ -687,44 +820,50 @@ dependencies = [ ] [[package]] -name = "idna" -version = "0.2.0" +name = "indexmap" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02e2673c30ee86b5b96a9cb52ad15718aa1f966f5ab9ad54a8b95d5ca33120a9" +checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e" dependencies = [ - "matches", - "unicode-bidi", - "unicode-normalization", + "autocfg", + "hashbrown", ] [[package]] -name = "indexmap" -version = "1.2.0" +name = "infer" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a61202fbe46c4a951e9404a720a0180bcf3212c750d735cb5c4ba4dc551299f3" +checksum = "64e9829a50b42bb782c1df523f78d332fe371b10c661e78b7a3c34b0198e9fac" [[package]] -name = "iovec" -version = "0.1.3" +name = "instant" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9636900aa73ffed13cdbb199f17cd955670bb300927c8d25b517dfa136b6567" +checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" dependencies = [ - "libc", + "cfg-if 1.0.0", ] +[[package]] +name = "ipnet" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879d54834c8c76457ef4293a689b2a8c59b076067ad77b15efafbb05f92a592b" + [[package]] name = "isahc" -version = "0.7.6" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17b77027f12e53ae59a379f7074259d32eb10867e6183388020e922832d9c3fb" +checksum = "ee16417863ac2b4869ac774af7ef0322b08c53d952665edc5749ccaa37d68588" dependencies = [ - "bytes", + "bytes 0.5.6", "crossbeam-channel", - "crossbeam-utils 0.6.6", + "crossbeam-utils", "curl", "curl-sys", - "futures-io-preview", - "futures-util-preview", + "futures-channel", + "futures-io", + "futures-util", "http", "lazy_static", "log", @@ -734,27 +873,26 @@ dependencies = [ [[package]] name = "itoa" -version = "0.4.4" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "501266b7edd0174f8530248f87f99c88fbe60ca4ef3dd486835b8d8d53136f7f" +checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d" [[package]] name = "js-sys" -version = "0.3.35" +version = "0.3.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7889c7c36282151f6bf465be4700359318aef36baa951462382eae49e9577cf9" +checksum = "258451ab10b34f8af53416d1fdab72c22e805f0c92a1136d59470ec0b11138b2" dependencies = [ "wasm-bindgen", ] [[package]] -name = "kernel32-sys" -version = "0.2.2" +name = "kv-log-macro" +version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f" dependencies = [ - "winapi 0.2.8", - "winapi-build", + "log", ] [[package]] @@ -767,8 +905,8 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" name = "leetcode-rust" version = "0.1.0" dependencies = [ - "futures 0.3.4", - "rand 0.6.5", + "futures", + "rand 0.8.5", "regex", "reqwest", "serde", @@ -785,9 +923,9 @@ checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" [[package]] name = "libnghttp2-sys" -version = "0.1.2" +version = "0.1.7+1.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02254d44f4435dd79e695f2c2b83cd06a47919adea30216ceaf0c57ca0a72463" +checksum = "57ed28aba195b38d5ff02b9170cbff627e336a20925e43b4945390401c5dc93f" dependencies = [ "cc", "libc", @@ -795,9 +933,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.0.25" +version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2eb5e43362e38e2bca2fd5f5134c4d4564a23a5c28e9b95411652021a8675ebe" +checksum = "9702761c3935f8cc2f101793272e202c72b99da8f4224a19ddcf1279a6450bbf" dependencies = [ "cc", "libc", @@ -805,15 +943,6 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "lock_api" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8912e782533a93a167888781b836336a6ca5da6175c05944c86cf28c31104dc" -dependencies = [ - "scopeguard", -] - [[package]] name = "log" version = "0.4.8" @@ -837,79 +966,54 @@ checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" [[package]] name = "memchr" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88579771288728879b57485cc7d6b07d648c9f0141eb955f8ab7f9d45394468e" - -[[package]] -name = "memoffset" -version = "0.5.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6075db033bbbb7ee5a0bbd3a3186bbae616f57fb001c485c7ff77955f8177f" -dependencies = [ - "rustc_version", -] +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" [[package]] name = "mime" -version = "0.3.14" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd1d63acd1b78403cc0c325605908475dd9b9a3acbf65ed8bcab97e27014afcf" +checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" [[package]] name = "mime_guess" -version = "2.0.1" +version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a0ed03949aef72dbdf3116a383d7b38b4768e6f960528cd6a6044aa9ed68599" +checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef" dependencies = [ "mime", "unicase", ] -[[package]] -name = "miniz_oxide" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "304f66c19be2afa56530fa7c39796192eef38618da8d19df725ad7c6d6b2aaae" -dependencies = [ - "adler32", -] - [[package]] name = "mio" -version = "0.6.19" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83f51996a3ed004ef184e16818edc51fadffe8e7ca68be67f9dee67d84d0ff23" +checksum = "57ee1c23c7c63b0c9250c339ffdc69255f110b298b901b9f6c82547b7b87caaf" dependencies = [ - "fuchsia-zircon", - "fuchsia-zircon-sys", - "iovec", - "kernel32-sys", "libc", "log", - "miow", - "net2", - "slab", - "winapi 0.2.8", + "wasi 0.11.0+wasi-snapshot-preview1", + "windows-sys", ] [[package]] -name = "miow" -version = "0.2.2" +name = "multitask" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebd808424166322d4a38da87083bfddd3ac4c131334ed55856112eb06d46944d" +checksum = "c09c35271e7dcdb5f709779111f2c8e8ab8e06c1b587c1c6a9e179d865aaa5b4" dependencies = [ - "kernel32-sys", - "net2", - "winapi 0.2.8", - "ws2_32-sys", + "async-task", + "concurrent-queue", + "fastrand", ] [[package]] name = "native-tls" -version = "0.2.3" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b2df1a4c22fd44a62147fd8f13dd0f95c9d8ca7b2610299b2a2f9cf8964274e" +checksum = "fd7e2f3618557f980e0b17e8856252eee3c97fa12c54dff0ca290fb6266ca4a9" dependencies = [ "lazy_static", "libc", @@ -924,55 +1028,53 @@ dependencies = [ ] [[package]] -name = "net2" -version = "0.2.37" +name = "num_cpus" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "391630d12b68002ae1e25e8f974306474966550ad82dac6886fb8910c19568ae" +checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" dependencies = [ - "cfg-if 0.1.10", + "hermit-abi", "libc", - "winapi 0.3.8", ] [[package]] -name = "nom" -version = "4.2.3" +name = "once_cell" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ad2a91a8e869eeb30b9cb3119ae87773a8f4ae617f41b1eb9c154b2905f7bd6" -dependencies = [ - "memchr", - "version_check", -] +checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" [[package]] -name = "num_cpus" -version = "1.10.1" +name = "opaque-debug" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcef43580c035376c0705c42792c294b66974abbfd2789b511784023f71f3273" -dependencies = [ - "libc", -] - -[[package]] -name = "once_cell" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" +checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" [[package]] name = "openssl" -version = "0.10.25" +version = "0.10.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f372b2b53ce10fb823a337aaa674e3a7d072b957c6264d0f4ff0bd86e657449" +checksum = "618febf65336490dfcf20b73f885f5651a0c89c64c2d4a8c3662585a70bf5bd0" dependencies = [ "bitflags", - "cfg-if 0.1.10", + "cfg-if 1.0.0", "foreign-types", - "lazy_static", "libc", + "once_cell", + "openssl-macros", "openssl-sys", ] +[[package]] +name = "openssl-macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b501e44f11665960c7e7fcf062c7d96a14ade4aa98116c004b2e37b5be7d736c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "openssl-probe" version = "0.1.2" @@ -981,11 +1083,11 @@ checksum = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de" [[package]] name = "openssl-sys" -version = "0.9.50" +version = "0.9.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c42dcccb832556b5926bc9ae61e8775f2a61e725ab07ab3d1e7fcf8ae62c3b6" +checksum = "e5f9bd0c2710541a3cda73d6f9ac4f1b240de4ae261065d309dbe73d9dceb42f" dependencies = [ - "autocfg 0.1.6", + "autocfg", "cc", "libc", "pkg-config", @@ -993,42 +1095,28 @@ dependencies = [ ] [[package]] -name = "parking_lot" -version = "0.9.0" +name = "parking" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f842b1982eb6c2fe34036a4fbfb06dd185a3f5c8edfaacdf7d1ea10b07de6252" -dependencies = [ - "lock_api", - "parking_lot_core", - "rustc_version", -] +checksum = "6cb300f271742d4a2a66c01b6b2fa0c83dfebd2e0bf11addb879a3547b4ed87c" [[package]] -name = "parking_lot_core" -version = "0.6.2" +name = "parking" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b876b1b9e7ac6e1a74a6da34d25c42e17e8862aa409cbbbdcfc8d86c6f3bc62b" -dependencies = [ - "cfg-if 0.1.10", - "cloudabi", - "libc", - "redox_syscall", - "rustc_version", - "smallvec", - "winapi 0.3.8", -] +checksum = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72" [[package]] name = "percent-encoding" -version = "1.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831" +checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" [[package]] -name = "percent-encoding" -version = "2.1.0" +name = "pin-project-lite" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" +checksum = "257b64915a082f7811703966789728173279bdebb956b143dbcd23f6f970a777" [[package]] name = "pin-project-lite" @@ -1049,49 +1137,47 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72d5370d90f49f70bd033c3d75e87fc529fbfff9d6f7cccef07d6170079d91ea" [[package]] -name = "ppv-lite86" -version = "0.2.5" +name = "polling" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3cbf9f658cdb5000fcf6f362b8ea2ba154b9f146a61c7a20d647034c6b6561b" +checksum = "9e09dffb745feffca5be3dea51c02b7b368c4597ab0219a82acaf9799ab3e0d1" +dependencies = [ + "cfg-if 0.1.10", + "libc", + "wepoll-sys-stjepang", + "winapi", +] [[package]] -name = "proc-macro2" -version = "0.4.30" +name = "polyval" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" +checksum = "eebcc4aa140b9abd2bc40d9c3f7ccec842679cd79045ac3a7ac698c1a064b7cd" dependencies = [ - "unicode-xid", + "cpuid-bool", + "opaque-debug", + "universal-hash", ] [[package]] -name = "proc-macro2" -version = "1.0.39" +name = "ppv-lite86" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c54b25569025b7fc9651de43004ae593a75ad88543b17178aa5e1b9c4f15f56f" -dependencies = [ - "unicode-ident", -] +checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" [[package]] -name = "publicsuffix" -version = "1.5.3" +name = "proc-macro-hack" +version = "0.5.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bf259a81de2b2eb9850ec990ec78e6a25319715584fd7652b9b26f96fcb1510" -dependencies = [ - "error-chain", - "idna 0.2.0", - "lazy_static", - "regex", - "url 2.1.0", -] +checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" [[package]] -name = "quote" -version = "0.6.13" +name = "proc-macro2" +version = "1.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" +checksum = "c54b25569025b7fc9651de43004ae593a75ad88543b17178aa5e1b9c4f15f56f" dependencies = [ - "proc-macro2 0.4.30", + "unicode-ident", ] [[package]] @@ -1100,163 +1186,78 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" dependencies = [ - "proc-macro2 1.0.39", -] - -[[package]] -name = "rand" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca" -dependencies = [ - "autocfg 0.1.6", - "libc", - "rand_chacha 0.1.1", - "rand_core 0.4.2", - "rand_hc 0.1.0", - "rand_isaac", - "rand_jitter", - "rand_os", - "rand_pcg", - "rand_xorshift", - "winapi 0.3.8", + "proc-macro2", ] [[package]] name = "rand" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ae1b169243eaf61759b8475a998f0a385e42042370f3a7dbaf35246eacc8412" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" dependencies = [ - "getrandom", + "getrandom 0.1.12", "libc", "rand_chacha 0.2.1", "rand_core 0.5.1", - "rand_hc 0.2.0", -] - -[[package]] -name = "rand_chacha" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef" -dependencies = [ - "autocfg 0.1.6", - "rand_core 0.3.1", -] - -[[package]] -name = "rand_chacha" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03a2a90da8c7523f554344f921aa97283eadf6ac484a6d2a7d0212fa7f8d6853" -dependencies = [ - "c2-chacha", - "rand_core 0.5.1", -] - -[[package]] -name = "rand_core" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" -dependencies = [ - "rand_core 0.4.2", -] - -[[package]] -name = "rand_core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" - -[[package]] -name = "rand_core" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rand_hc" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4" -dependencies = [ - "rand_core 0.3.1", -] - -[[package]] -name = "rand_hc" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" -dependencies = [ - "rand_core 0.5.1", + "rand_hc", ] [[package]] -name = "rand_isaac" -version = "0.1.1" +name = "rand" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ - "rand_core 0.3.1", + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.3", ] [[package]] -name = "rand_jitter" -version = "0.1.4" +name = "rand_chacha" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b" +checksum = "03a2a90da8c7523f554344f921aa97283eadf6ac484a6d2a7d0212fa7f8d6853" dependencies = [ - "libc", - "rand_core 0.4.2", - "winapi 0.3.8", + "c2-chacha", + "rand_core 0.5.1", ] [[package]] -name = "rand_os" -version = "0.1.3" +name = "rand_chacha" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ - "cloudabi", - "fuchsia-cprng", - "libc", - "rand_core 0.4.2", - "rdrand", - "winapi 0.3.8", + "ppv-lite86", + "rand_core 0.6.3", ] [[package]] -name = "rand_pcg" -version = "0.1.2" +name = "rand_core" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" dependencies = [ - "autocfg 0.1.6", - "rand_core 0.4.2", + "getrandom 0.1.12", ] [[package]] -name = "rand_xorshift" -version = "0.1.1" +name = "rand_core" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" +checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" dependencies = [ - "rand_core 0.3.1", + "getrandom 0.2.7", ] [[package]] -name = "rdrand" -version = "0.4.0" +name = "rand_hc" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" dependencies = [ - "rand_core 0.3.1", + "rand_core 0.5.1", ] [[package]] @@ -1289,49 +1290,46 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a83fa3702a688b9359eccba92d153ac33fd2e8462f9e0e3fdf155239ea7792e" dependencies = [ - "winapi 0.3.8", + "winapi", ] [[package]] name = "reqwest" -version = "0.9.21" +version = "0.11.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02b7e953e14c6f3102b7e8d1f1ee3abf5ecee80b427f5565c9389835cecae95c" +checksum = "b75aa69a3f06bbcc66ede33af2af253c6f7a86b1ca0033f60c580a27074fbf92" dependencies = [ "base64", - "bytes", - "cookie", - "cookie_store", + "bytes 1.2.1", "encoding_rs", - "flate2", - "futures 0.1.29", + "futures-core", + "futures-util", + "h2", "http", + "http-body", "hyper", "hyper-tls", + "ipnet", + "js-sys", + "lazy_static", "log", "mime", - "mime_guess", "native-tls", + "percent-encoding", + "pin-project-lite 0.2.9", "serde", "serde_json", - "serde_urlencoded 0.5.5", - "time", + "serde_urlencoded", "tokio", - "tokio-executor", - "tokio-io", - "tokio-threadpool", - "tokio-timer", - "url 1.7.2", - "uuid", + "tokio-native-tls", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", "winreg", ] -[[package]] -name = "rustc-demangle" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" - [[package]] name = "rustc_version" version = "0.2.3" @@ -1349,26 +1347,27 @@ checksum = "c92464b447c0ee8c4fb3824ecc8383b81717b9f1e74ba2e72540aef7b9f82997" [[package]] name = "schannel" -version = "0.1.16" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f550b06b6cba9c8b8be3ee73f391990116bf527450d2556e9b9ce263b9a021" +checksum = "88d6731146462ea25d9244b2ed5fd1d716d25c52e4d54aa4fb0f3c4e9854dbe2" dependencies = [ "lazy_static", - "winapi 0.3.8", + "windows-sys", ] [[package]] -name = "scopeguard" +name = "scoped-tls" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b42e15e59b18a828bbf5c58ea01debb36b9b096346de35d941dcb89009f24a0d" +checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" [[package]] name = "security-framework" -version = "0.3.1" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eee63d0f4a9ec776eeb30e220f0bc1e092c3ad744b2a379e3993070364d3adc2" +checksum = "2dc14f172faf8a0194a3aded622712b0de276821addc574fa54fc0a1167e10dc" dependencies = [ + "bitflags", "core-foundation", "core-foundation-sys", "libc", @@ -1377,11 +1376,12 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "0.3.1" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9636f8989cbf61385ae4824b98c1aaa54c994d7d8b41f11c601ed799f0549a56" +checksum = "0160a13a177a45bfb43ce71c01580998474f556ad854dcbca936dd2841a5c556" dependencies = [ "core-foundation-sys", + "libc", ] [[package]] @@ -1401,29 +1401,29 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" [[package]] name = "serde" -version = "1.0.101" +version = "1.0.141" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9796c9b7ba2ffe7a9ce53c2287dfc48080f4b2b362fcc245a259b3a7201119dd" +checksum = "7af873f2c95b99fcb0bd0fe622a43e29514658873c8ceba88c4cb88833a22500" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.101" +version = "1.0.141" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b133a43a1ecd55d4086bd5b4dc6c1751c68b1bfbeba7a5040442022c7e7c02e" +checksum = "75743a150d003dd863b51dc809bcad0d73f2102c53632f1e954e738192a3413f" dependencies = [ - "proc-macro2 1.0.39", - "quote 1.0.2", - "syn 1.0.96", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "serde_json" -version = "1.0.41" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f72eb2a68a7dc3f9a691bfda9305a1c017a6215e5a4545c258500d2099a37c2" +checksum = "82c2c1fdcd807d1098552c5b9a36e425e42e9fbd7c6a37a8425f390f781f7fa7" dependencies = [ "itoa", "ryu", @@ -1431,27 +1431,54 @@ dependencies = [ ] [[package]] -name = "serde_urlencoded" -version = "0.5.5" +name = "serde_qs" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "642dd69105886af2efd227f75a520ec9b44a820d65bc133a9131f7d229fd165a" +checksum = "c7715380eec75f029a4ef7de39a9200e0a63823176b759d055b613f5a87df6a6" dependencies = [ - "dtoa", - "itoa", + "percent-encoding", "serde", - "url 1.7.2", + "thiserror", ] [[package]] name = "serde_urlencoded" -version = "0.6.1" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ec5d77e2d4c73717816afac02670d5c4f534ea95ed430442cad02e7a6e32c97" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" dependencies = [ - "dtoa", + "form_urlencoded", "itoa", + "ryu", "serde", - "url 2.1.0", +] + +[[package]] +name = "sha1" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" +dependencies = [ + "sha1_smol", +] + +[[package]] +name = "sha1_smol" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" + +[[package]] +name = "sha2" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" +dependencies = [ + "block-buffer", + "cfg-if 1.0.0", + "cpufeatures", + "digest", + "opaque-debug", ] [[package]] @@ -1462,13 +1489,13 @@ checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" [[package]] name = "sluice" -version = "0.4.2" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a7d06dfb3e8743bc19e6de8a302277471d08077d68946b307280496dc5a3531" +checksum = "6d7400c0eff44aa2fcb5e31a5f24ba9716ed90138769e4977a2ba6014ae63eb5" dependencies = [ - "futures-channel-preview", - "futures-core-preview", - "futures-io-preview", + "async-channel", + "futures-core", + "futures-io", ] [[package]] @@ -1488,78 +1515,115 @@ checksum = "122e570113d28d773067fab24266b66753f6ea915758651696b6e35e49f88d6e" dependencies = [ "cfg-if 1.0.0", "libc", - "winapi 0.3.8", + "winapi", ] [[package]] -name = "sourcefile" -version = "0.1.4" +name = "socket2" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bf77cb82ba8453b42b6ae1d692e4cdc92f9a47beaf89a847c8be83f4e328ad3" +checksum = "66d72b759436ae32898a2af0a14218dbf55efde3feeb170eb623637db85ee1e0" +dependencies = [ + "libc", + "winapi", +] [[package]] -name = "string" -version = "0.2.1" +name = "standback" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d24114bfcceb867ca7f71a0d3fe45d45619ec47a6fbfa98cb14e14250bfa5d6d" +checksum = "e113fb6f3de07a243d434a56ec6f186dfd51cb08448239fe7bcae73f87ff28ff" dependencies = [ - "bytes", + "version_check 0.9.4", ] [[package]] -name = "surf" -version = "1.0.3" +name = "stdweb" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "741a8008f8a833ef16f47df94a30754478fb2c2bf822b9c2e6f7f09203b97ace" +checksum = "d022496b16281348b52d0e30ae99e01a73d737b2f45d38fed4edf79f9325a1d5" dependencies = [ - "futures-preview", - "http", - "isahc", - "js-sys", - "log", - "mime", - "mime_guess", - "serde", - "serde_json", - "serde_urlencoded 0.6.1", - "url 2.1.0", + "discard", + "rustc_version", + "stdweb-derive", + "stdweb-internal-macros", + "stdweb-internal-runtime", "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", ] [[package]] -name = "syn" -version = "0.15.44" +name = "stdweb-derive" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" +checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef" dependencies = [ - "proc-macro2 0.4.30", - "quote 0.6.13", - "unicode-xid", + "proc-macro2", + "quote", + "serde", + "serde_derive", + "syn", ] [[package]] -name = "syn" -version = "1.0.96" +name = "stdweb-internal-macros" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0748dd251e24453cb8717f0354206b91557e4ec8703673a4b30208f2abaf1ebf" +checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11" dependencies = [ - "proc-macro2 1.0.39", - "quote 1.0.2", - "unicode-ident", + "base-x", + "proc-macro2", + "quote", + "serde", + "serde_derive", + "serde_json", + "sha1", + "syn", ] [[package]] -name = "synstructure" -version = "0.10.2" +name = "stdweb-internal-runtime" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0" + +[[package]] +name = "subtle" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" + +[[package]] +name = "surf" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "718b1ae6b50351982dedff021db0def601677f2120938b070eadb10ba4038dd7" +dependencies = [ + "async-std", + "async-trait", + "cfg-if 1.0.0", + "encoding_rs", + "futures-util", + "getrandom 0.2.7", + "http-client", + "http-types", + "log", + "mime_guess", + "once_cell", + "pin-project-lite 0.2.9", + "serde", + "serde_json", + "web-sys", +] + +[[package]] +name = "syn" +version = "1.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02353edf96d6e4dc81aea2d8490a7e9db177bf8acb0e951c24940bf866cb313f" +checksum = "0748dd251e24453cb8717f0354206b91557e4ec8703673a4b30208f2abaf1ebf" dependencies = [ - "proc-macro2 0.4.30", - "quote 0.6.13", - "syn 0.15.44", - "unicode-xid", + "proc-macro2", + "quote", + "unicode-ident", ] [[package]] @@ -1570,163 +1634,145 @@ checksum = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9" dependencies = [ "cfg-if 0.1.10", "libc", - "rand 0.7.2", + "rand 0.7.3", "redox_syscall", "remove_dir_all", - "winapi 0.3.8", + "winapi", ] [[package]] -name = "thread_local" -version = "1.1.4" +name = "thiserror" +version = "1.0.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5516c27b78311c50bf42c071425c560ac799b11c30b31f87e3081965fe5e0180" +checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a" dependencies = [ - "once_cell", + "thiserror-impl", ] [[package]] -name = "time" -version = "0.1.42" +name = "thiserror-impl" +version = "1.0.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db8dcfca086c1143c9270ac42a2bbd8a7ee477b78ac8e45b19abfb0cbede4b6f" +checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a" dependencies = [ - "libc", - "redox_syscall", - "winapi 0.3.8", + "proc-macro2", + "quote", + "syn", ] [[package]] -name = "tokio" -version = "0.1.22" +name = "thread_local" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a09c0b5bb588872ab2f09afa13ee6e9dac11e10a0ec9e8e3ba39a5a5d530af6" +checksum = "5516c27b78311c50bf42c071425c560ac799b11c30b31f87e3081965fe5e0180" dependencies = [ - "bytes", - "futures 0.1.29", - "mio", - "num_cpus", - "tokio-current-thread", - "tokio-executor", - "tokio-io", - "tokio-reactor", - "tokio-tcp", - "tokio-threadpool", - "tokio-timer", + "once_cell", ] [[package]] -name = "tokio-buf" -version = "0.1.1" +name = "time" +version = "0.2.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fb220f46c53859a4b7ec083e41dec9778ff0b1851c0942b211edb89e0ccdc46" +checksum = "4752a97f8eebd6854ff91f1c1824cd6160626ac4bd44287f7f4ea2035a02a242" dependencies = [ - "bytes", - "either", - "futures 0.1.29", + "const_fn", + "libc", + "standback", + "stdweb", + "time-macros", + "version_check 0.9.4", + "winapi", ] [[package]] -name = "tokio-current-thread" -version = "0.1.6" +name = "time-macros" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d16217cad7f1b840c5a97dfb3c43b0c871fef423a6e8d2118c604e843662a443" +checksum = "957e9c6e26f12cb6d0dd7fc776bb67a706312e7299aed74c8dd5b17ebb27e2f1" dependencies = [ - "futures 0.1.29", - "tokio-executor", + "proc-macro-hack", + "time-macros-impl", ] [[package]] -name = "tokio-executor" -version = "0.1.8" +name = "time-macros-impl" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f27ee0e6db01c5f0b2973824547ce7e637b2ed79b891a9677b0de9bd532b6ac" +checksum = "fd3c141a1b43194f3f56a1411225df8646c55781d5f26db825b3d98507eb482f" dependencies = [ - "crossbeam-utils 0.6.6", - "futures 0.1.29", + "proc-macro-hack", + "proc-macro2", + "quote", + "standback", + "syn", ] [[package]] -name = "tokio-io" -version = "0.1.12" +name = "tokio" +version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5090db468dad16e1a7a54c8c67280c5e4b544f3d3e018f0b913b400261f85926" +checksum = "7a8325f63a7d4774dd041e363b2409ed1c5cbbd0f867795e661df066b2b0a581" dependencies = [ - "bytes", - "futures 0.1.29", - "log", + "autocfg", + "bytes 1.2.1", + "libc", + "memchr", + "mio", + "num_cpus", + "once_cell", + "pin-project-lite 0.2.9", + "socket2 0.4.4", + "winapi", ] [[package]] -name = "tokio-reactor" -version = "0.1.10" +name = "tokio-native-tls" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56391be9805bc80163151c0b9e5164ee64f4b0200962c346fea12773158f22d" +checksum = "f7d995660bd2b7f8c1568414c1126076c13fbb725c40112dc0120b78eb9b717b" dependencies = [ - "crossbeam-utils 0.6.6", - "futures 0.1.29", - "lazy_static", - "log", - "mio", - "num_cpus", - "parking_lot", - "slab", - "tokio-executor", - "tokio-io", - "tokio-sync", + "native-tls", + "tokio", ] [[package]] -name = "tokio-sync" -version = "0.1.6" +name = "tokio-util" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2162248ff317e2bc713b261f242b69dbb838b85248ed20bb21df56d60ea4cae7" +checksum = "cc463cd8deddc3770d20f9852143d50bf6094e640b485cb2e189a2099085ff45" dependencies = [ - "fnv", - "futures 0.1.29", + "bytes 1.2.1", + "futures-core", + "futures-sink", + "pin-project-lite 0.2.9", + "tokio", + "tracing", ] [[package]] -name = "tokio-tcp" -version = "0.1.3" +name = "tower-service" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d14b10654be682ac43efee27401d792507e30fd8d26389e1da3b185de2e4119" -dependencies = [ - "bytes", - "futures 0.1.29", - "iovec", - "mio", - "tokio-io", - "tokio-reactor", -] +checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] -name = "tokio-threadpool" -version = "0.1.16" +name = "tracing" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bd2c6a3885302581f4401c82af70d792bb9df1700e7437b0aeb4ada94d5388c" +checksum = "2fce9567bd60a67d08a16488756721ba392f24f29006402881e43b19aac64307" dependencies = [ - "crossbeam-deque", - "crossbeam-queue", - "crossbeam-utils 0.6.6", - "futures 0.1.29", - "lazy_static", - "log", - "num_cpus", - "slab", - "tokio-executor", + "cfg-if 1.0.0", + "pin-project-lite 0.2.9", + "tracing-core", ] [[package]] -name = "tokio-timer" -version = "0.2.11" +name = "tracing-core" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2106812d500ed25a4f38235b9cae8f78a09edf43203e16e59c3b769a342a60e" +checksum = "5aeea4303076558a00714b823f9ad67d58a3bbda1df83d8827d21193156e22f7" dependencies = [ - "crossbeam-utils 0.6.6", - "futures 0.1.29", - "slab", - "tokio-executor", + "once_cell", ] [[package]] @@ -1736,13 +1782,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e604eb7b43c06650e854be16a2a03155743d3752dd1c943f6829e26b7a36e382" [[package]] -name = "try_from" -version = "0.3.2" +name = "typenum" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "283d3b89e1368717881a9d51dad843cc435380d8109c9e47d38780a324698d8b" -dependencies = [ - "cfg-if 0.1.10", -] +checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" [[package]] name = "unicase" @@ -1750,7 +1793,7 @@ version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e2e6bd1e59e56598518beb94fd6db628ded570326f0a98c679a304bd9f00150" dependencies = [ - "version_check", + "version_check 0.1.5", ] [[package]] @@ -1778,53 +1821,39 @@ dependencies = [ ] [[package]] -name = "unicode-segmentation" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e83e153d1053cbb5a118eeff7fd5be06ed99153f00dbcd8ae310c5fb2b22edc0" - -[[package]] -name = "unicode-xid" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" - -[[package]] -name = "url" -version = "1.7.2" +name = "universal-hash" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd4e7c0d531266369519a4aa4f399d748bd37043b00bde1e4ff1f60a120b355a" +checksum = "9f214e8f697e925001e66ec2c6e37a4ef93f0f78c2eed7814394e10c62025b05" dependencies = [ - "idna 0.1.5", - "matches", - "percent-encoding 1.0.1", + "generic-array", + "subtle", ] [[package]] name = "url" -version = "2.1.0" +version = "2.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75b414f6c464c879d7f9babf951f23bc3743fb7313c081b2e6ca719067ea9d61" +checksum = "a507c383b2d33b5fc35d1861e77e6b383d158b2da5e14fe51b83dfedf6fd578c" dependencies = [ - "idna 0.2.0", + "form_urlencoded", + "idna", "matches", - "percent-encoding 2.1.0", + "percent-encoding", + "serde", ] [[package]] -name = "uuid" -version = "0.7.4" +name = "vcpkg" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90dbc611eb48397705a6b0f6e917da23ae517e4d127123d2cf7674206627d32a" -dependencies = [ - "rand 0.6.5", -] +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" [[package]] -name = "vcpkg" -version = "0.2.7" +name = "vec-arena" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33dd455d0f96e90a75803cfeb7f948768c08d70a6de9a8d2362461935698bf95" +checksum = "8cb18268690309760d59ee1a9b21132c126ba384f374c59a94db4bc03adeb561" [[package]] name = "version_check" @@ -1832,13 +1861,24 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "waker-fn" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca" + [[package]] name = "want" -version = "0.2.0" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6395efa4784b027708f7451087e647ec73cc74f5d9bc2e418404248d679a230" +checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" dependencies = [ - "futures 0.1.29", "log", "try-lock", ] @@ -1849,136 +1889,107 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b89c3ce4ce14bdc6fb6beaf9ec7928ca331de5df7e5ea278375642a2f478570d" +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + [[package]] name = "wasm-bindgen" -version = "0.2.58" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5205e9afdf42282b192e2310a5b463a6d1c1d774e30dc3c791ac37ab42d2616c" +checksum = "fc7652e3f6c4706c8d9cd54832c4a4ccb9b5336e2c3bd154d5cccfbf1c1f5f7d" dependencies = [ - "cfg-if 0.1.10", + "cfg-if 1.0.0", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" -version = "0.2.58" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11cdb95816290b525b32587d76419facd99662a07e59d3cdb560488a819d9a45" +checksum = "662cd44805586bd52971b9586b1df85cdbbd9112e4ef4d8f41559c334dc6ac3f" dependencies = [ "bumpalo", - "lazy_static", "log", - "proc-macro2 1.0.39", - "quote 1.0.2", - "syn 1.0.96", + "once_cell", + "proc-macro2", + "quote", + "syn", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.3.27" +version = "0.4.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83420b37346c311b9ed822af41ec2e82839bfe99867ec6c54e2da43b7538771c" +checksum = "fa76fb221a1f8acddf5b54ace85912606980ad661ac7a503b4570ffd3a624dad" dependencies = [ - "cfg-if 0.1.10", - "futures 0.1.29", - "futures-channel-preview", - "futures-util-preview", + "cfg-if 1.0.0", "js-sys", - "lazy_static", "wasm-bindgen", "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.58" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "574094772ce6921576fb6f2e3f7497b8a76273b6db092be18fc48a082de09dc3" +checksum = "b260f13d3012071dfb1512849c033b1925038373aea48ced3012c09df952c602" dependencies = [ - "quote 1.0.2", + "quote", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.58" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e85031354f25eaebe78bb7db1c3d86140312a911a106b2e29f9cc440ce3e7668" +checksum = "5be8e654bdd9b79216c2929ab90721aa82faf65c48cdf08bdc4e7f51357b80da" dependencies = [ - "proc-macro2 1.0.39", - "quote 1.0.2", - "syn 1.0.96", + "proc-macro2", + "quote", + "syn", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.58" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5e7e61fc929f4c0dddb748b102ebf9f632e2b8d739f2016542b4de2965a9601" - -[[package]] -name = "wasm-bindgen-webidl" -version = "0.2.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef012a0d93fc0432df126a8eaf547b2dce25a8ce9212e1d3cbeef5c11157975d" -dependencies = [ - "anyhow", - "heck", - "log", - "proc-macro2 1.0.39", - "quote 1.0.2", - "syn 1.0.96", - "wasm-bindgen-backend", - "weedle", -] +checksum = "6598dd0bd3c7d51095ff6531a5b23e02acdc81804e30d8f07afb77b7215a140a" [[package]] name = "web-sys" -version = "0.3.35" +version = "0.3.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaf97caf6aa8c2b1dac90faf0db529d9d63c93846cca4911856f78a83cebf53b" +checksum = "ed055ab27f941423197eb86b2035720b1a3ce40504df082cac2ecc6ed73335a1" dependencies = [ - "anyhow", "js-sys", - "sourcefile", "wasm-bindgen", - "wasm-bindgen-webidl", ] [[package]] -name = "weedle" -version = "0.10.0" +name = "wepoll-sys-stjepang" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bb43f70885151e629e2a19ce9e50bd730fd436cfd4b666894c9ce4de9141164" +checksum = "1fdfbb03f290ca0b27922e8d48a0997b4ceea12df33269b9f75e713311eb178d" dependencies = [ - "nom", + "cc", ] [[package]] name = "winapi" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" - -[[package]] -name = "winapi" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] -[[package]] -name = "winapi-build" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" - [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" @@ -1992,20 +2003,53 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] -name = "winreg" -version = "0.6.2" +name = "windows-sys" +version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2986deb581c4fe11b621998a5e53361efe6b48a151178d0cd9eeffa4dc6acc9" +checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" dependencies = [ - "winapi 0.3.8", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_msvc", ] [[package]] -name = "ws2_32-sys" -version = "0.2.1" +name = "windows_aarch64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" + +[[package]] +name = "windows_i686_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" + +[[package]] +name = "windows_i686_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" + +[[package]] +name = "winreg" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" dependencies = [ - "winapi 0.2.8", - "winapi-build", + "winapi", ] diff --git a/Cargo.toml b/Cargo.toml index 9fdbe995..338e45f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,18 +1,18 @@ [package] name = "leetcode-rust" version = "0.1.0" -authors = ["alei "] +authors = ["lidongjies "] edition = "2018" [dependencies] -reqwest = "0.9.8" +reqwest = { version = "0.11.11", features = ["json", "blocking"] } serde = "1.0" serde_json = "1.0" serde_derive = "1.0" -rand = "0.6.5" +rand = "0.8.5" regex = "1.3.4" -futures = { version = "0.3.3", features = ["thread-pool"] } -surf = "1.0.3" +futures = { version = "0.3.21", features = ["thread-pool"] } +surf = "2.3.2" [lib] doctest = false diff --git a/README.md b/README.md index 587b18a2..d3ee5438 100644 --- a/README.md +++ b/README.md @@ -4,15 +4,6 @@ Run `cargo run {id}` to initialize the template submission file of "question #id Run `cargo test test_{id}` to test the solution for "question #id". -对于大部分难度为 Hard 的问题, 会有中文的思路注释 - -Working in progress, to do: - -- [ ] auto generation of solution list (when 100 problems solved) - -## Usage - -* Remove all the solution .rs -* Clean lib.rs file -* Start your leetcode journey in rust by typing `cargo run {question_id}` +## 常用链接 +- [String,&str,Vec 和&[u8]的惯用转换](https://zhuanlan.zhihu.com/p/372082802) \ No newline at end of file diff --git a/src/fetcher.rs b/src/fetcher.rs index c356dee8..e30dc87c 100644 --- a/src/fetcher.rs +++ b/src/fetcher.rs @@ -26,7 +26,7 @@ pub fn get_problem(frontend_question_id: u32) -> Option { return None; } - let client = reqwest::Client::new(); + let client = reqwest::blocking::Client::new(); let resp: RawProblem = client .post(GRAPHQL_URL) .json(&Query::question_query( @@ -97,7 +97,10 @@ pub async fn get_problem_async(problem_stat: StatWithStatus) -> Option } pub fn get_problems() -> Option { - reqwest::get(PROBLEMS_URL).unwrap().json().unwrap() + reqwest::blocking::get(PROBLEMS_URL) + .unwrap() + .json() + .unwrap() } #[derive(Serialize, Deserialize)] diff --git a/src/lib.rs b/src/lib.rs index 55b0298f..ac9c5c95 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,5 @@ #[macro_use] pub mod util; -pub mod solution; pub mod problem; +pub mod solution; diff --git a/src/main.rs b/src/main.rs index 6fecf106..f4a21d38 100644 --- a/src/main.rs +++ b/src/main.rs @@ -152,7 +152,7 @@ fn generate_random_id(except_ids: &[u32]) -> u32 { use std::fs; let mut rng = rand::thread_rng(); loop { - let res: u32 = rng.gen_range(1, 1106); + let res: u32 = rng.gen_range(1..1106); if !except_ids.contains(&res) { return res; } diff --git a/src/problem/p0100_same_tree.rs b/src/problem/p0100_same_tree.rs new file mode 100644 index 00000000..29c694bf --- /dev/null +++ b/src/problem/p0100_same_tree.rs @@ -0,0 +1,72 @@ +/** + * [100] Same Tree + * + * Given the roots of two binary trees p and q, write a function to check if they are the same or not. + * Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. + * + * Example 1: + * + * Input: p = [1,2,3], q = [1,2,3] + * Output: true + * + * Example 2: + * + * Input: p = [1,2], q = [1,null,2] + * Output: false + * + * Example 3: + * + * Input: p = [1,2,1], q = [1,1,2] + * Output: false + * + * + * Constraints: + * + * The number of nodes in both trees is in the range [0, 100]. + * -10^4 <= Node.val <= 10^4 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/same-tree/ +// discuss: https://leetcode.com/problems/same-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn is_same_tree(p: Option>>, q: Option>>) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_100() { + } +} diff --git a/src/problem/p0101_symmetric_tree.rs b/src/problem/p0101_symmetric_tree.rs new file mode 100644 index 00000000..8400b03e --- /dev/null +++ b/src/problem/p0101_symmetric_tree.rs @@ -0,0 +1,68 @@ +/** + * [101] Symmetric Tree + * + * Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). + * + * Example 1: + * + * Input: root = [1,2,2,3,4,4,3] + * Output: true + * + * Example 2: + * + * Input: root = [1,2,2,null,3,null,3] + * Output: false + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 1000]. + * -100 <= Node.val <= 100 + * + * + * Follow up: Could you solve it both recursively and iteratively? + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/symmetric-tree/ +// discuss: https://leetcode.com/problems/symmetric-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn is_symmetric(root: Option>>) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_101() { + } +} diff --git a/src/problem/p0102_binary_tree_level_order_traversal.rs b/src/problem/p0102_binary_tree_level_order_traversal.rs new file mode 100644 index 00000000..c8242f9f --- /dev/null +++ b/src/problem/p0102_binary_tree_level_order_traversal.rs @@ -0,0 +1,71 @@ +/** + * [102] Binary Tree Level Order Traversal + * + * Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). + * + * Example 1: + * + * Input: root = [3,9,20,null,null,15,7] + * Output: [[3],[9,20],[15,7]] + * + * Example 2: + * + * Input: root = [1] + * Output: [[1]] + * + * Example 3: + * + * Input: root = [] + * Output: [] + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 2000]. + * -1000 <= Node.val <= 1000 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/binary-tree-level-order-traversal/ +// discuss: https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn level_order(root: Option>>) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_102() { + } +} diff --git a/src/problem/p0103_binary_tree_zigzag_level_order_traversal.rs b/src/problem/p0103_binary_tree_zigzag_level_order_traversal.rs new file mode 100644 index 00000000..84b01ed0 --- /dev/null +++ b/src/problem/p0103_binary_tree_zigzag_level_order_traversal.rs @@ -0,0 +1,71 @@ +/** + * [103] Binary Tree Zigzag Level Order Traversal + * + * Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between). + * + * Example 1: + * + * Input: root = [3,9,20,null,null,15,7] + * Output: [[3],[20,9],[15,7]] + * + * Example 2: + * + * Input: root = [1] + * Output: [[1]] + * + * Example 3: + * + * Input: root = [] + * Output: [] + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 2000]. + * -100 <= Node.val <= 100 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ +// discuss: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn zigzag_level_order(root: Option>>) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_103() { + } +} diff --git a/src/problem/p0104_maximum_depth_of_binary_tree.rs b/src/problem/p0104_maximum_depth_of_binary_tree.rs new file mode 100644 index 00000000..7b589b88 --- /dev/null +++ b/src/problem/p0104_maximum_depth_of_binary_tree.rs @@ -0,0 +1,67 @@ +/** + * [104] Maximum Depth of Binary Tree + * + * Given the root of a binary tree, return its maximum depth. + * A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. + * + * Example 1: + * + * Input: root = [3,9,20,null,null,15,7] + * Output: 3 + * + * Example 2: + * + * Input: root = [1,null,2] + * Output: 2 + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 10^4]. + * -100 <= Node.val <= 100 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/maximum-depth-of-binary-tree/ +// discuss: https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn max_depth(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_104() { + } +} diff --git a/src/problem/p0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs b/src/problem/p0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs new file mode 100644 index 00000000..0a9e671c --- /dev/null +++ b/src/problem/p0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs @@ -0,0 +1,71 @@ +/** + * [105] Construct Binary Tree from Preorder and Inorder Traversal + * + * Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. + * + * Example 1: + * + * Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] + * Output: [3,9,20,null,null,15,7] + * + * Example 2: + * + * Input: preorder = [-1], inorder = [-1] + * Output: [-1] + * + * + * Constraints: + * + * 1 <= preorder.length <= 3000 + * inorder.length == preorder.length + * -3000 <= preorder[i], inorder[i] <= 3000 + * preorder and inorder consist of unique values. + * Each value of inorder also appears in preorder. + * preorder is guaranteed to be the preorder traversal of the tree. + * inorder is guaranteed to be the inorder traversal of the tree. + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ +// discuss: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn build_tree(preorder: Vec, inorder: Vec) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_105() { + } +} diff --git a/src/problem/p0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs b/src/problem/p0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs new file mode 100644 index 00000000..3e35c37d --- /dev/null +++ b/src/problem/p0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs @@ -0,0 +1,71 @@ +/** + * [106] Construct Binary Tree from Inorder and Postorder Traversal + * + * Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree. + * + * Example 1: + * + * Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] + * Output: [3,9,20,null,null,15,7] + * + * Example 2: + * + * Input: inorder = [-1], postorder = [-1] + * Output: [-1] + * + * + * Constraints: + * + * 1 <= inorder.length <= 3000 + * postorder.length == inorder.length + * -3000 <= inorder[i], postorder[i] <= 3000 + * inorder and postorder consist of unique values. + * Each value of postorder also appears in inorder. + * inorder is guaranteed to be the inorder traversal of the tree. + * postorder is guaranteed to be the postorder traversal of the tree. + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ +// discuss: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn build_tree(inorder: Vec, postorder: Vec) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_106() { + } +} diff --git a/src/problem/p0108_convert_sorted_array_to_binary_search_tree.rs b/src/problem/p0108_convert_sorted_array_to_binary_search_tree.rs new file mode 100644 index 00000000..5cf5fb7c --- /dev/null +++ b/src/problem/p0108_convert_sorted_array_to_binary_search_tree.rs @@ -0,0 +1,71 @@ +/** + * [108] Convert Sorted Array to Binary Search Tree + * + * Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. + * A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. + * + * Example 1: + * + * Input: nums = [-10,-3,0,5,9] + * Output: [0,-3,9,-10,null,5] + * Explanation: [0,-10,5,null,-3,null,9] is also accepted: + * + * + * Example 2: + * + * Input: nums = [1,3] + * Output: [3,1] + * Explanation: [1,null,3] and [3,1] are both height-balanced BSTs. + * + * + * Constraints: + * + * 1 <= nums.length <= 10^4 + * -10^4 <= nums[i] <= 10^4 + * nums is sorted in a strictly increasing order. + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ +// discuss: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn sorted_array_to_bst(nums: Vec) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_108() { + } +} diff --git a/src/problem/p0109_convert_sorted_list_to_binary_search_tree.rs b/src/problem/p0109_convert_sorted_list_to_binary_search_tree.rs new file mode 100644 index 00000000..d4736422 --- /dev/null +++ b/src/problem/p0109_convert_sorted_list_to_binary_search_tree.rs @@ -0,0 +1,85 @@ +/** + * [109] Convert Sorted List to Binary Search Tree + * + * Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. + * For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. + * + * Example 1: + * + * Input: head = [-10,-3,0,5,9] + * Output: [0,-3,9,-10,null,5] + * Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. + * + * Example 2: + * + * Input: head = [] + * Output: [] + * + * + * Constraints: + * + * The number of nodes in head is in the range [0, 2 * 10^4]. + * -10^5 <= Node.val <= 10^5 + * + */ +pub struct Solution {} +use crate::util::linked_list::{ListNode, to_list}; +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ +// discuss: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn sorted_list_to_bst(head: Option>) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_109() { + } +} diff --git a/src/problem/p0110_balanced_binary_tree.rs b/src/problem/p0110_balanced_binary_tree.rs new file mode 100644 index 00000000..ed306121 --- /dev/null +++ b/src/problem/p0110_balanced_binary_tree.rs @@ -0,0 +1,75 @@ +/** + * [110] Balanced Binary Tree + * + * Given a binary tree, determine if it is height-balanced. + * For this problem, a height-balanced binary tree is defined as: + *
+ * a binary tree in which the left and right subtrees of every node differ in height by no more than 1. + *
+ * + * Example 1: + * + * Input: root = [3,9,20,null,null,15,7] + * Output: true + * + * Example 2: + * + * Input: root = [1,2,2,3,3,null,null,4,4] + * Output: false + * + * Example 3: + * + * Input: root = [] + * Output: true + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 5000]. + * -10^4 <= Node.val <= 10^4 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/balanced-binary-tree/ +// discuss: https://leetcode.com/problems/balanced-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn is_balanced(root: Option>>) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_110() { + } +} diff --git a/src/problem/p0111_minimum_depth_of_binary_tree.rs b/src/problem/p0111_minimum_depth_of_binary_tree.rs new file mode 100644 index 00000000..38c5d896 --- /dev/null +++ b/src/problem/p0111_minimum_depth_of_binary_tree.rs @@ -0,0 +1,68 @@ +/** + * [111] Minimum Depth of Binary Tree + * + * Given a binary tree, find its minimum depth. + * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. + * Note: A leaf is a node with no children. + * + * Example 1: + * + * Input: root = [3,9,20,null,null,15,7] + * Output: 2 + * + * Example 2: + * + * Input: root = [2,null,3,null,4,null,5,null,6] + * Output: 5 + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 10^5]. + * -1000 <= Node.val <= 1000 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/minimum-depth-of-binary-tree/ +// discuss: https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn min_depth(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_111() { + } +} diff --git a/src/problem/p0112_path_sum.rs b/src/problem/p0112_path_sum.rs new file mode 100644 index 00000000..db7f94cd --- /dev/null +++ b/src/problem/p0112_path_sum.rs @@ -0,0 +1,79 @@ +/** + * [112] Path Sum + * + * Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. + * A leaf is a node with no children. + * + * Example 1: + * + * Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 + * Output: true + * Explanation: The root-to-leaf path with the target sum is shown. + * + * Example 2: + * + * Input: root = [1,2,3], targetSum = 5 + * Output: false + * Explanation: There two root-to-leaf paths in the tree: + * (1 --> 2): The sum is 3. + * (1 --> 3): The sum is 4. + * There is no root-to-leaf path with sum = 5. + * + * Example 3: + * + * Input: root = [], targetSum = 0 + * Output: false + * Explanation: Since the tree is empty, there are no root-to-leaf paths. + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 5000]. + * -1000 <= Node.val <= 1000 + * -1000 <= targetSum <= 1000 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/path-sum/ +// discuss: https://leetcode.com/problems/path-sum/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn has_path_sum(root: Option>>, target_sum: i32) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_112() { + } +} diff --git a/src/problem/p0113_path_sum_ii.rs b/src/problem/p0113_path_sum_ii.rs new file mode 100644 index 00000000..bfa172f3 --- /dev/null +++ b/src/problem/p0113_path_sum_ii.rs @@ -0,0 +1,76 @@ +/** + * [113] Path Sum II + * + * Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references. + * A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. + * + * Example 1: + * + * Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 + * Output: [[5,4,11,2],[5,8,4,5]] + * Explanation: There are two paths whose sum equals targetSum: + * 5 + 4 + 11 + 2 = 22 + * 5 + 8 + 4 + 5 = 22 + * + * Example 2: + * + * Input: root = [1,2,3], targetSum = 5 + * Output: [] + * + * Example 3: + * + * Input: root = [1,2], targetSum = 0 + * Output: [] + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 5000]. + * -1000 <= Node.val <= 1000 + * -1000 <= targetSum <= 1000 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/path-sum-ii/ +// discuss: https://leetcode.com/problems/path-sum-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn path_sum(root: Option>>, target_sum: i32) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_113() { + } +} diff --git a/src/problem/p0114_flatten_binary_tree_to_linked_list.rs b/src/problem/p0114_flatten_binary_tree_to_linked_list.rs new file mode 100644 index 00000000..a5d0e574 --- /dev/null +++ b/src/problem/p0114_flatten_binary_tree_to_linked_list.rs @@ -0,0 +1,77 @@ +/** + * [114] Flatten Binary Tree to Linked List + * + * Given the root of a binary tree, flatten the tree into a "linked list": + * + * The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. + * The "linked list" should be in the same order as a pre-order traversal of the binary tree. + * + * + * Example 1: + * + * Input: root = [1,2,5,3,4,null,6] + * Output: [1,null,2,null,3,null,4,null,5,null,6] + * + * Example 2: + * + * Input: root = [] + * Output: [] + * + * Example 3: + * + * Input: root = [0] + * Output: [0] + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 2000]. + * -100 <= Node.val <= 100 + * + * + * Follow up: Can you flatten the tree in-place (with O(1) extra space)? + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ +// discuss: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn flatten(root: &mut Option>>) { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_114() { + } +} diff --git a/src/problem/p0115_distinct_subsequences.rs b/src/problem/p0115_distinct_subsequences.rs new file mode 100644 index 00000000..532beb69 --- /dev/null +++ b/src/problem/p0115_distinct_subsequences.rs @@ -0,0 +1,58 @@ +/** + * [115] Distinct Subsequences + * + * Given two strings s and t, return the number of distinct subsequences of s which equals t. + * A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not). + * The test cases are generated so that the answer fits on a 32-bit signed integer. + * + * Example 1: + * + * Input: s = "rabbbit", t = "rabbit" + * Output: 3 + * Explanation: + * As shown below, there are 3 ways you can generate "rabbit" from S. + * rabbbit + * rabbbit + * rabbbit + * + * Example 2: + * + * Input: s = "babgbag", t = "bag" + * Output: 5 + * Explanation: + * As shown below, there are 5 ways you can generate "bag" from S. + * babgbag + * babgbag + * babgbag + * babgbag + * babgbag + * + * Constraints: + * + * 1 <= s.length, t.length <= 1000 + * s and t consist of English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/distinct-subsequences/ +// discuss: https://leetcode.com/problems/distinct-subsequences/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_distinct(s: String, t: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_115() { + } +} diff --git a/src/problem/p0118_pascals_triangle.rs b/src/problem/p0118_pascals_triangle.rs new file mode 100644 index 00000000..05232b72 --- /dev/null +++ b/src/problem/p0118_pascals_triangle.rs @@ -0,0 +1,42 @@ +/** + * [118] Pascal's Triangle + * + * Given an integer numRows, return the first numRows of Pascal's triangle. + * In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: + * + * + * Example 1: + * Input: numRows = 5 + * Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] + * Example 2: + * Input: numRows = 1 + * Output: [[1]] + * + * Constraints: + * + * 1 <= numRows <= 30 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/pascals-triangle/ +// discuss: https://leetcode.com/problems/pascals-triangle/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn generate(num_rows: i32) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_118() { + } +} diff --git a/src/problem/p0119_pascals_triangle_ii.rs b/src/problem/p0119_pascals_triangle_ii.rs new file mode 100644 index 00000000..8b0ad12c --- /dev/null +++ b/src/problem/p0119_pascals_triangle_ii.rs @@ -0,0 +1,48 @@ +/** + * [119] Pascal's Triangle II + * + * Given an integer rowIndex, return the rowIndex^th (0-indexed) row of the Pascal's triangle. + * In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: + * + * + * Example 1: + * Input: rowIndex = 3 + * Output: [1,3,3,1] + * Example 2: + * Input: rowIndex = 0 + * Output: [1] + * Example 3: + * Input: rowIndex = 1 + * Output: [1,1] + * + * Constraints: + * + * 0 <= rowIndex <= 33 + * + * + * Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space? + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/pascals-triangle-ii/ +// discuss: https://leetcode.com/problems/pascals-triangle-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn get_row(row_index: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_119() { + } +} diff --git a/src/problem/p0120_triangle.rs b/src/problem/p0120_triangle.rs new file mode 100644 index 00000000..54fa0e0d --- /dev/null +++ b/src/problem/p0120_triangle.rs @@ -0,0 +1,56 @@ +/** + * [120] Triangle + * + * Given a triangle array, return the minimum path sum from top to bottom. + * For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row. + * + * Example 1: + * + * Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] + * Output: 11 + * Explanation: The triangle looks like: + * 2 + * 3 4 + * 6 5 7 + * 4 1 8 3 + * The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). + * + * Example 2: + * + * Input: triangle = [[-10]] + * Output: -10 + * + * + * Constraints: + * + * 1 <= triangle.length <= 200 + * triangle[0].length == 1 + * triangle[i].length == triangle[i - 1].length + 1 + * -10^4 <= triangle[i][j] <= 10^4 + * + * + * Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle? + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/triangle/ +// discuss: https://leetcode.com/problems/triangle/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn minimum_total(triangle: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_120() { + } +} diff --git a/src/problem/p0121_best_time_to_buy_and_sell_stock.rs b/src/problem/p0121_best_time_to_buy_and_sell_stock.rs new file mode 100644 index 00000000..2bd3a249 --- /dev/null +++ b/src/problem/p0121_best_time_to_buy_and_sell_stock.rs @@ -0,0 +1,50 @@ +/** + * [121] Best Time to Buy and Sell Stock + * + * You are given an array prices where prices[i] is the price of a given stock on the i^th day. + * You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. + * Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. + * + * Example 1: + * + * Input: prices = [7,1,5,3,6,4] + * Output: 5 + * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. + * Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. + * + * Example 2: + * + * Input: prices = [7,6,4,3,1] + * Output: 0 + * Explanation: In this case, no transactions are done and the max profit = 0. + * + * + * Constraints: + * + * 1 <= prices.length <= 10^5 + * 0 <= prices[i] <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ +// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_121() { + } +} diff --git a/src/problem/p0122_best_time_to_buy_and_sell_stock_ii.rs b/src/problem/p0122_best_time_to_buy_and_sell_stock_ii.rs new file mode 100644 index 00000000..61d46653 --- /dev/null +++ b/src/problem/p0122_best_time_to_buy_and_sell_stock_ii.rs @@ -0,0 +1,58 @@ +/** + * [122] Best Time to Buy and Sell Stock II + * + * You are given an integer array prices where prices[i] is the price of a given stock on the i^th day. + * On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. + * Find and return the maximum profit you can achieve. + * + * Example 1: + * + * Input: prices = [7,1,5,3,6,4] + * Output: 7 + * Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. + * Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. + * Total profit is 4 + 3 = 7. + * + * Example 2: + * + * Input: prices = [1,2,3,4,5] + * Output: 4 + * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. + * Total profit is 4. + * + * Example 3: + * + * Input: prices = [7,6,4,3,1] + * Output: 0 + * Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. + * + * + * Constraints: + * + * 1 <= prices.length <= 3 * 10^4 + * 0 <= prices[i] <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ +// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_122() { + } +} diff --git a/src/problem/p0123_best_time_to_buy_and_sell_stock_iii.rs b/src/problem/p0123_best_time_to_buy_and_sell_stock_iii.rs new file mode 100644 index 00000000..0c57ab5a --- /dev/null +++ b/src/problem/p0123_best_time_to_buy_and_sell_stock_iii.rs @@ -0,0 +1,56 @@ +/** + * [123] Best Time to Buy and Sell Stock III + * + * You are given an array prices where prices[i] is the price of a given stock on the i^th day. + * Find the maximum profit you can achieve. You may complete at most two transactions. + * Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). + * + * Example 1: + * + * Input: prices = [3,3,5,0,0,3,1,4] + * Output: 6 + * Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. + * Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. + * Example 2: + * + * Input: prices = [1,2,3,4,5] + * Output: 4 + * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. + * Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. + * + * Example 3: + * + * Input: prices = [7,6,4,3,1] + * Output: 0 + * Explanation: In this case, no transaction is done, i.e. max profit = 0. + * + * + * Constraints: + * + * 1 <= prices.length <= 10^5 + * 0 <= prices[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ +// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_123() { + } +} diff --git a/src/problem/p0125_valid_palindrome.rs b/src/problem/p0125_valid_palindrome.rs new file mode 100644 index 00000000..21eee09f --- /dev/null +++ b/src/problem/p0125_valid_palindrome.rs @@ -0,0 +1,55 @@ +/** + * [125] Valid Palindrome + * + * A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. + * Given a string s, return true if it is a palindrome, or false otherwise. + * + * Example 1: + * + * Input: s = "A man, a plan, a canal: Panama" + * Output: true + * Explanation: "amanaplanacanalpanama" is a palindrome. + * + * Example 2: + * + * Input: s = "race a car" + * Output: false + * Explanation: "raceacar" is not a palindrome. + * + * Example 3: + * + * Input: s = " " + * Output: true + * Explanation: s is an empty string "" after removing non-alphanumeric characters. + * Since an empty string reads the same forward and backward, it is a palindrome. + * + * + * Constraints: + * + * 1 <= s.length <= 2 * 10^5 + * s consists only of printable ASCII characters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/valid-palindrome/ +// discuss: https://leetcode.com/problems/valid-palindrome/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_palindrome(s: String) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_125() { + } +} diff --git a/src/problem/p0126_word_ladder_ii.rs b/src/problem/p0126_word_ladder_ii.rs new file mode 100644 index 00000000..b67a180d --- /dev/null +++ b/src/problem/p0126_word_ladder_ii.rs @@ -0,0 +1,60 @@ +/** + * [126] Word Ladder II + * + * A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: + * + * Every adjacent pair of words differs by a single letter. + * Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. + * sk == endWord + * + * Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk]. + * + * Example 1: + * + * Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] + * Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] + * Explanation: There are 2 shortest transformation sequences: + * "hit" -> "hot" -> "dot" -> "dog" -> "cog" + * "hit" -> "hot" -> "lot" -> "log" -> "cog" + * + * Example 2: + * + * Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] + * Output: [] + * Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. + * + * + * Constraints: + * + * 1 <= beginWord.length <= 5 + * endWord.length == beginWord.length + * 1 <= wordList.length <= 500 + * wordList[i].length == beginWord.length + * beginWord, endWord, and wordList[i] consist of lowercase English letters. + * beginWord != endWord + * All the words in wordList are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/word-ladder-ii/ +// discuss: https://leetcode.com/problems/word-ladder-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_ladders(begin_word: String, end_word: String, word_list: Vec) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_126() { + } +} diff --git a/src/problem/p0127_word_ladder.rs b/src/problem/p0127_word_ladder.rs new file mode 100644 index 00000000..12409c63 --- /dev/null +++ b/src/problem/p0127_word_ladder.rs @@ -0,0 +1,58 @@ +/** + * [127] Word Ladder + * + * A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: + * + * Every adjacent pair of words differs by a single letter. + * Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. + * sk == endWord + * + * Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. + * + * Example 1: + * + * Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] + * Output: 5 + * Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. + * + * Example 2: + * + * Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] + * Output: 0 + * Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. + * + * + * Constraints: + * + * 1 <= beginWord.length <= 10 + * endWord.length == beginWord.length + * 1 <= wordList.length <= 5000 + * wordList[i].length == beginWord.length + * beginWord, endWord, and wordList[i] consist of lowercase English letters. + * beginWord != endWord + * All the words in wordList are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/word-ladder/ +// discuss: https://leetcode.com/problems/word-ladder/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn ladder_length(begin_word: String, end_word: String, word_list: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_127() { + } +} diff --git a/src/problem/p0128_longest_consecutive_sequence.rs b/src/problem/p0128_longest_consecutive_sequence.rs new file mode 100644 index 00000000..4dacbf2c --- /dev/null +++ b/src/problem/p0128_longest_consecutive_sequence.rs @@ -0,0 +1,47 @@ +/** + * [128] Longest Consecutive Sequence + * + * Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. + * You must write an algorithm that runs in O(n) time. + * + * Example 1: + * + * Input: nums = [100,4,200,1,3,2] + * Output: 4 + * Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. + * + * Example 2: + * + * Input: nums = [0,3,7,2,5,8,4,6,0,1] + * Output: 9 + * + * + * Constraints: + * + * 0 <= nums.length <= 10^5 + * -10^9 <= nums[i] <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-consecutive-sequence/ +// discuss: https://leetcode.com/problems/longest-consecutive-sequence/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn longest_consecutive(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_128() { + } +} diff --git a/src/problem/p0129_sum_root_to_leaf_numbers.rs b/src/problem/p0129_sum_root_to_leaf_numbers.rs new file mode 100644 index 00000000..9c39f045 --- /dev/null +++ b/src/problem/p0129_sum_root_to_leaf_numbers.rs @@ -0,0 +1,82 @@ +/** + * [129] Sum Root to Leaf Numbers + * + * You are given the root of a binary tree containing digits from 0 to 9 only. + * Each root-to-leaf path in the tree represents a number. + * + * For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123. + * + * Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. + * A leaf node is a node with no children. + * + * Example 1: + * + * Input: root = [1,2,3] + * Output: 25 + * Explanation: + * The root-to-leaf path 1->2 represents the number 12. + * The root-to-leaf path 1->3 represents the number 13. + * Therefore, sum = 12 + 13 = 25. + * + * Example 2: + * + * Input: root = [4,9,0,5,1] + * Output: 1026 + * Explanation: + * The root-to-leaf path 4->9->5 represents the number 495. + * The root-to-leaf path 4->9->1 represents the number 491. + * The root-to-leaf path 4->0 represents the number 40. + * Therefore, sum = 495 + 491 + 40 = 1026. + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 1000]. + * 0 <= Node.val <= 9 + * The depth of the tree will not exceed 10. + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/sum-root-to-leaf-numbers/ +// discuss: https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn sum_numbers(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_129() { + } +} diff --git a/src/problem/p0130_surrounded_regions.rs b/src/problem/p0130_surrounded_regions.rs new file mode 100644 index 00000000..7232d4a7 --- /dev/null +++ b/src/problem/p0130_surrounded_regions.rs @@ -0,0 +1,53 @@ +/** + * [130] Surrounded Regions + * + * Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'. + * A region is captured by flipping all 'O's into 'X's in that surrounded region. + * + * Example 1: + * + * Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] + * Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]] + * Explanation: Notice that an 'O' should not be flipped if: + * - It is on the border, or + * - It is adjacent to an 'O' that should not be flipped. + * The bottom 'O' is on the border, so it is not flipped. + * The other three 'O' form a surrounded region, so they are flipped. + * + * Example 2: + * + * Input: board = [["X"]] + * Output: [["X"]] + * + * + * Constraints: + * + * m == board.length + * n == board[i].length + * 1 <= m, n <= 200 + * board[i][j] is 'X' or 'O'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/surrounded-regions/ +// discuss: https://leetcode.com/problems/surrounded-regions/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn solve(board: &mut Vec>) { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_130() { + } +} diff --git a/src/problem/p0137_single_number_ii.rs b/src/problem/p0137_single_number_ii.rs new file mode 100644 index 00000000..12804c11 --- /dev/null +++ b/src/problem/p0137_single_number_ii.rs @@ -0,0 +1,43 @@ +/** + * [137] Single Number II + * + * Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it. + * You must implement a solution with a linear runtime complexity and use only constant extra space. + * + * Example 1: + * Input: nums = [2,2,3,2] + * Output: 3 + * Example 2: + * Input: nums = [0,1,0,1,0,1,99] + * Output: 99 + * + * Constraints: + * + * 1 <= nums.length <= 3 * 10^4 + * -2^31 <= nums[i] <= 2^31 - 1 + * Each element in nums appears exactly three times except for one element which appears once. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/single-number-ii/ +// discuss: https://leetcode.com/problems/single-number-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn single_number(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_137() { + } +} diff --git a/src/problem/p0139_word_break.rs b/src/problem/p0139_word_break.rs new file mode 100644 index 00000000..db5c27ec --- /dev/null +++ b/src/problem/p0139_word_break.rs @@ -0,0 +1,57 @@ +/** + * [139] Word Break + * + * Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. + * Note that the same word in the dictionary may be reused multiple times in the segmentation. + * + * Example 1: + * + * Input: s = "leetcode", wordDict = ["leet","code"] + * Output: true + * Explanation: Return true because "leetcode" can be segmented as "leet code". + * + * Example 2: + * + * Input: s = "applepenapple", wordDict = ["apple","pen"] + * Output: true + * Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". + * Note that you are allowed to reuse a dictionary word. + * + * Example 3: + * + * Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] + * Output: false + * + * + * Constraints: + * + * 1 <= s.length <= 300 + * 1 <= wordDict.length <= 1000 + * 1 <= wordDict[i].length <= 20 + * s and wordDict[i] consist of only lowercase English letters. + * All the strings of wordDict are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/word-break/ +// discuss: https://leetcode.com/problems/word-break/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn word_break(s: String, word_dict: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_139() { + } +} diff --git a/src/problem/p0143_reorder_list.rs b/src/problem/p0143_reorder_list.rs new file mode 100644 index 00000000..ce7d6b94 --- /dev/null +++ b/src/problem/p0143_reorder_list.rs @@ -0,0 +1,70 @@ +/** + * [143] Reorder List + * + * You are given the head of a singly linked-list. The list can be represented as: + * + * L0 → L1 → … → Ln - 1 → Ln + * + * Reorder the list to be on the following form: + * + * L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … + * + * You may not modify the values in the list's nodes. Only nodes themselves may be changed. + * + * Example 1: + * + * Input: head = [1,2,3,4] + * Output: [1,4,2,3] + * + * Example 2: + * + * Input: head = [1,2,3,4,5] + * Output: [1,5,2,4,3] + * + * + * Constraints: + * + * The number of nodes in the list is in the range [1, 5 * 10^4]. + * 1 <= Node.val <= 1000 + * + */ +pub struct Solution {} +use crate::util::linked_list::{ListNode, to_list}; + +// problem: https://leetcode.com/problems/reorder-list/ +// discuss: https://leetcode.com/problems/reorder-list/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn reorder_list(head: &mut Option>) { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_143() { + } +} diff --git a/src/problem/p0148_sort_list.rs b/src/problem/p0148_sort_list.rs new file mode 100644 index 00000000..19e3c2c5 --- /dev/null +++ b/src/problem/p0148_sort_list.rs @@ -0,0 +1,70 @@ +/** + * [148] Sort List + * + * Given the head of a linked list, return the list after sorting it in ascending order. + * + * Example 1: + * + * Input: head = [4,2,1,3] + * Output: [1,2,3,4] + * + * Example 2: + * + * Input: head = [-1,5,3,4,0] + * Output: [-1,0,3,4,5] + * + * Example 3: + * + * Input: head = [] + * Output: [] + * + * + * Constraints: + * + * The number of nodes in the list is in the range [0, 5 * 10^4]. + * -10^5 <= Node.val <= 10^5 + * + * + * Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)? + * + */ +pub struct Solution {} +use crate::util::linked_list::{ListNode, to_list}; + +// problem: https://leetcode.com/problems/sort-list/ +// discuss: https://leetcode.com/problems/sort-list/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn sort_list(head: Option>) -> Option> { + Some(Box::new(ListNode::new(0))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_148() { + } +} diff --git a/src/problem/p0151_reverse_words_in_a_string.rs b/src/problem/p0151_reverse_words_in_a_string.rs new file mode 100644 index 00000000..8049b9a4 --- /dev/null +++ b/src/problem/p0151_reverse_words_in_a_string.rs @@ -0,0 +1,59 @@ +/** + * [151] Reverse Words in a String + * + * Given an input string s, reverse the order of the words. + * A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. + * Return a string of the words in reverse order concatenated by a single space. + * Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. + * + * Example 1: + * + * Input: s = "the sky is blue" + * Output: "blue is sky the" + * + * Example 2: + * + * Input: s = " hello world " + * Output: "world hello" + * Explanation: Your reversed string should not contain leading or trailing spaces. + * + * Example 3: + * + * Input: s = "a good example" + * Output: "example good a" + * Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. + * + * + * Constraints: + * + * 1 <= s.length <= 10^4 + * s contains English letters (upper-case and lower-case), digits, and spaces ' '. + * There is at least one word in s. + * + * + * Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space? + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/reverse-words-in-a-string/ +// discuss: https://leetcode.com/problems/reverse-words-in-a-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn reverse_words(s: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_151() { + } +} diff --git a/src/problem/p0153_find_minimum_in_rotated_sorted_array.rs b/src/problem/p0153_find_minimum_in_rotated_sorted_array.rs new file mode 100644 index 00000000..e6031669 --- /dev/null +++ b/src/problem/p0153_find_minimum_in_rotated_sorted_array.rs @@ -0,0 +1,63 @@ +/** + * [153] Find Minimum in Rotated Sorted Array + * + * Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: + * + * [4,5,6,7,0,1,2] if it was rotated 4 times. + * [0,1,2,4,5,6,7] if it was rotated 7 times. + * + * Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. + * Given the sorted rotated array nums of unique elements, return the minimum element of this array. + * You must write an algorithm that runs in O(log n) time. + * + * Example 1: + * + * Input: nums = [3,4,5,1,2] + * Output: 1 + * Explanation: The original array was [1,2,3,4,5] rotated 3 times. + * + * Example 2: + * + * Input: nums = [4,5,6,7,0,1,2] + * Output: 0 + * Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. + * + * Example 3: + * + * Input: nums = [11,13,15,17] + * Output: 11 + * Explanation: The original array was [11,13,15,17] and it was rotated 4 times. + * + * + * Constraints: + * + * n == nums.length + * 1 <= n <= 5000 + * -5000 <= nums[i] <= 5000 + * All the integers of nums are unique. + * nums is sorted and rotated between 1 and n times. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ +// discuss: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_min(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_153() { + } +} diff --git a/src/problem/p0154_find_minimum_in_rotated_sorted_array_ii.rs b/src/problem/p0154_find_minimum_in_rotated_sorted_array_ii.rs new file mode 100644 index 00000000..7511d2c1 --- /dev/null +++ b/src/problem/p0154_find_minimum_in_rotated_sorted_array_ii.rs @@ -0,0 +1,54 @@ +/** + * [154] Find Minimum in Rotated Sorted Array II + * + * Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: + * + * [4,5,6,7,0,1,4] if it was rotated 4 times. + * [0,1,4,4,5,6,7] if it was rotated 7 times. + * + * Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. + * Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array. + * You must decrease the overall operation steps as much as possible. + * + * Example 1: + * Input: nums = [1,3,5] + * Output: 1 + * Example 2: + * Input: nums = [2,2,2,0,1] + * Output: 0 + * + * Constraints: + * + * n == nums.length + * 1 <= n <= 5000 + * -5000 <= nums[i] <= 5000 + * nums is sorted and rotated between 1 and n times. + * + * + * Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why? + * + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ +// discuss: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_min(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_154() { + } +} diff --git a/src/problem/p0162_find_peak_element.rs b/src/problem/p0162_find_peak_element.rs new file mode 100644 index 00000000..9164d7fe --- /dev/null +++ b/src/problem/p0162_find_peak_element.rs @@ -0,0 +1,49 @@ +/** + * [162] Find Peak Element + * + * A peak element is an element that is strictly greater than its neighbors. + * Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. + * You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. + * You must write an algorithm that runs in O(log n) time. + * + * Example 1: + * + * Input: nums = [1,2,3,1] + * Output: 2 + * Explanation: 3 is a peak element and your function should return the index number 2. + * Example 2: + * + * Input: nums = [1,2,1,3,5,6,4] + * Output: 5 + * Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. + * + * Constraints: + * + * 1 <= nums.length <= 1000 + * -2^31 <= nums[i] <= 2^31 - 1 + * nums[i] != nums[i + 1] for all valid i. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-peak-element/ +// discuss: https://leetcode.com/problems/find-peak-element/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_peak_element(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_162() { + } +} diff --git a/src/solution/s0166_fraction_to_recurring_decimal.rs b/src/problem/p0166_fraction_to_recurring_decimal.rs similarity index 67% rename from src/solution/s0166_fraction_to_recurring_decimal.rs rename to src/problem/p0166_fraction_to_recurring_decimal.rs index 4585738f..d8aef8b6 100644 --- a/src/solution/s0166_fraction_to_recurring_decimal.rs +++ b/src/problem/p0166_fraction_to_recurring_decimal.rs @@ -2,29 +2,31 @@ * [166] Fraction to Recurring Decimal * * Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. - * * If the fractional part is repeating, enclose the repeating part in parentheses. - * + * If multiple answers are possible, return any of them. + * It is guaranteed that the length of the answer string is less than 10^4 for all the given inputs. + * * Example 1: - * - * + * * Input: numerator = 1, denominator = 2 * Output: "0.5" - * - * + * * Example 2: - * - * + * * Input: numerator = 2, denominator = 1 * Output: "2" - * + * * Example 3: - * - * - * Input: numerator = 2, denominator = 3 - * Output: "0.(6)" - * - * + * + * Input: numerator = 4, denominator = 333 + * Output: "0.(012)" + * + * + * Constraints: + * + * -2^31 <= numerator, denominator <= 2^31 - 1 + * denominator != 0 + * */ pub struct Solution {} @@ -33,10 +35,9 @@ pub struct Solution {} // submission codes start here -// TODO impl Solution { pub fn fraction_to_decimal(numerator: i32, denominator: i32) -> String { - "".to_owned() + String::new() } } @@ -47,5 +48,6 @@ mod tests { use super::*; #[test] - fn test_166() {} + fn test_166() { + } } diff --git a/src/problem/p0167_two_sum_ii_input_array_is_sorted.rs b/src/problem/p0167_two_sum_ii_input_array_is_sorted.rs new file mode 100644 index 00000000..50c9c02a --- /dev/null +++ b/src/problem/p0167_two_sum_ii_input_array_is_sorted.rs @@ -0,0 +1,59 @@ +/** + * [167] Two Sum II - Input Array Is Sorted + * + * Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. + * Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. + * The tests are generated such that there is exactly one solution. You may not use the same element twice. + * Your solution must use only constant extra space. + * + * Example 1: + * + * Input: numbers = [2,7,11,15], target = 9 + * Output: [1,2] + * Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. + * + * Example 2: + * + * Input: numbers = [2,3,4], target = 6 + * Output: [1,3] + * Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. + * + * Example 3: + * + * Input: numbers = [-1,0], target = -1 + * Output: [1,2] + * Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. + * + * + * Constraints: + * + * 2 <= numbers.length <= 3 * 10^4 + * -1000 <= numbers[i] <= 1000 + * numbers is sorted in non-decreasing order. + * -1000 <= target <= 1000 + * The tests are generated such that there is exactly one solution. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ +// discuss: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn two_sum(numbers: Vec, target: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_167() { + } +} diff --git a/src/problem/p0169_majority_element.rs b/src/problem/p0169_majority_element.rs new file mode 100644 index 00000000..c92595aa --- /dev/null +++ b/src/problem/p0169_majority_element.rs @@ -0,0 +1,45 @@ +/** + * [169] Majority Element + * + * Given an array nums of size n, return the majority element. + * The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. + * + * Example 1: + * Input: nums = [3,2,3] + * Output: 3 + * Example 2: + * Input: nums = [2,2,1,1,1,2,2] + * Output: 2 + * + * Constraints: + * + * n == nums.length + * 1 <= n <= 5 * 10^4 + * -10^9 <= nums[i] <= 10^9 + * + * + * Follow-up: Could you solve the problem in linear time and in O(1) space? + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/majority-element/ +// discuss: https://leetcode.com/problems/majority-element/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn majority_element(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_169() { + } +} diff --git a/src/problem/p0171_excel_sheet_column_number.rs b/src/problem/p0171_excel_sheet_column_number.rs new file mode 100644 index 00000000..c5861e3c --- /dev/null +++ b/src/problem/p0171_excel_sheet_column_number.rs @@ -0,0 +1,62 @@ +/** + * [171] Excel Sheet Column Number + * + * Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number. + * For example: + * + * A -> 1 + * B -> 2 + * C -> 3 + * ... + * Z -> 26 + * AA -> 27 + * AB -> 28 + * ... + * + * + * Example 1: + * + * Input: columnTitle = "A" + * Output: 1 + * + * Example 2: + * + * Input: columnTitle = "AB" + * Output: 28 + * + * Example 3: + * + * Input: columnTitle = "ZY" + * Output: 701 + * + * + * Constraints: + * + * 1 <= columnTitle.length <= 7 + * columnTitle consists only of uppercase English letters. + * columnTitle is in the range ["A", "FXSHRXW"]. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/excel-sheet-column-number/ +// discuss: https://leetcode.com/problems/excel-sheet-column-number/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn title_to_number(column_title: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_171() { + } +} diff --git a/src/problem/p0173_binary_search_tree_iterator.rs b/src/problem/p0173_binary_search_tree_iterator.rs new file mode 100644 index 00000000..2ee502fe --- /dev/null +++ b/src/problem/p0173_binary_search_tree_iterator.rs @@ -0,0 +1,111 @@ +/** + * [173] Binary Search Tree Iterator + * + * Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): + * + * BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST. + * boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false. + * int next() Moves the pointer to the right, then returns the number at the pointer. + * + * Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST. + * You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called. + * + * Example 1: + * + * Input + * ["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"] + * [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] + * Output + * [null, 3, 7, true, 9, true, 15, true, 20, false] + * Explanation + * BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); + * bSTIterator.next(); // return 3 + * bSTIterator.next(); // return 7 + * bSTIterator.hasNext(); // return True + * bSTIterator.next(); // return 9 + * bSTIterator.hasNext(); // return True + * bSTIterator.next(); // return 15 + * bSTIterator.hasNext(); // return True + * bSTIterator.next(); // return 20 + * bSTIterator.hasNext(); // return False + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 10^5]. + * 0 <= Node.val <= 10^6 + * At most 10^5 calls will be made to hasNext, and next. + * + * + * Follow up: + * + * Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree? + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/binary-search-tree-iterator/ +// discuss: https://leetcode.com/problems/binary-search-tree-iterator/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +struct BSTIterator { + vec![] + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl BSTIterator { + + fn new(root: Option>>) -> Self { + + } + + fn next(&self) -> i32 { + + } + + fn has_next(&self) -> bool { + + } +} + +/** + * Your BSTIterator object will be instantiated and called as such: + * let obj = BSTIterator::new(root); + * let ret_1: i32 = obj.next(); + * let ret_2: bool = obj.has_next(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_173() { + } +} diff --git a/src/problem/p0199_binary_tree_right_side_view.rs b/src/problem/p0199_binary_tree_right_side_view.rs new file mode 100644 index 00000000..2c167c82 --- /dev/null +++ b/src/problem/p0199_binary_tree_right_side_view.rs @@ -0,0 +1,71 @@ +/** + * [199] Binary Tree Right Side View + * + * Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. + * + * Example 1: + * + * Input: root = [1,2,3,null,5,null,4] + * Output: [1,3,4] + * + * Example 2: + * + * Input: root = [1,null,3] + * Output: [1,3] + * + * Example 3: + * + * Input: root = [] + * Output: [] + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 100]. + * -100 <= Node.val <= 100 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/binary-tree-right-side-view/ +// discuss: https://leetcode.com/problems/binary-tree-right-side-view/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn right_side_view(root: Option>>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_199() { + } +} diff --git a/src/problem/p0203_remove_linked_list_elements.rs b/src/problem/p0203_remove_linked_list_elements.rs new file mode 100644 index 00000000..0b66cf1e --- /dev/null +++ b/src/problem/p0203_remove_linked_list_elements.rs @@ -0,0 +1,68 @@ +/** + * [203] Remove Linked List Elements + * + * Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head. + * + * Example 1: + * + * Input: head = [1,2,6,3,4,5,6], val = 6 + * Output: [1,2,3,4,5] + * + * Example 2: + * + * Input: head = [], val = 1 + * Output: [] + * + * Example 3: + * + * Input: head = [7,7,7,7], val = 7 + * Output: [] + * + * + * Constraints: + * + * The number of nodes in the list is in the range [0, 10^4]. + * 1 <= Node.val <= 50 + * 0 <= val <= 50 + * + */ +pub struct Solution {} +use crate::util::linked_list::{ListNode, to_list}; + +// problem: https://leetcode.com/problems/remove-linked-list-elements/ +// discuss: https://leetcode.com/problems/remove-linked-list-elements/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn remove_elements(head: Option>, val: i32) -> Option> { + Some(Box::new(ListNode::new(0))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_203() { + } +} diff --git a/src/problem/p0204_count_primes.rs b/src/problem/p0204_count_primes.rs new file mode 100644 index 00000000..339fed8f --- /dev/null +++ b/src/problem/p0204_count_primes.rs @@ -0,0 +1,50 @@ +/** + * [204] Count Primes + * + * Given an integer n, return the number of prime numbers that are strictly less than n. + * + * Example 1: + * + * Input: n = 10 + * Output: 4 + * Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. + * + * Example 2: + * + * Input: n = 0 + * Output: 0 + * + * Example 3: + * + * Input: n = 1 + * Output: 0 + * + * + * Constraints: + * + * 0 <= n <= 5 * 10^6 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-primes/ +// discuss: https://leetcode.com/problems/count-primes/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_primes(n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_204() { + } +} diff --git a/src/problem/p0205_isomorphic_strings.rs b/src/problem/p0205_isomorphic_strings.rs new file mode 100644 index 00000000..db84a5ec --- /dev/null +++ b/src/problem/p0205_isomorphic_strings.rs @@ -0,0 +1,47 @@ +/** + * [205] Isomorphic Strings + * + * Given two strings s and t, determine if they are isomorphic. + * Two strings s and t are isomorphic if the characters in s can be replaced to get t. + * All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. + * + * Example 1: + * Input: s = "egg", t = "add" + * Output: true + * Example 2: + * Input: s = "foo", t = "bar" + * Output: false + * Example 3: + * Input: s = "paper", t = "title" + * Output: true + * + * Constraints: + * + * 1 <= s.length <= 5 * 10^4 + * t.length == s.length + * s and t consist of any valid ascii character. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/isomorphic-strings/ +// discuss: https://leetcode.com/problems/isomorphic-strings/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_isomorphic(s: String, t: String) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_205() { + } +} diff --git a/src/problem/p0207_course_schedule.rs b/src/problem/p0207_course_schedule.rs new file mode 100644 index 00000000..097fe84f --- /dev/null +++ b/src/problem/p0207_course_schedule.rs @@ -0,0 +1,56 @@ +/** + * [207] Course Schedule + * + * There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. + * + * For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. + * + * Return true if you can finish all courses. Otherwise, return false. + * + * Example 1: + * + * Input: numCourses = 2, prerequisites = [[1,0]] + * Output: true + * Explanation: There are a total of 2 courses to take. + * To take course 1 you should have finished course 0. So it is possible. + * + * Example 2: + * + * Input: numCourses = 2, prerequisites = [[1,0],[0,1]] + * Output: false + * Explanation: There are a total of 2 courses to take. + * To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. + * + * + * Constraints: + * + * 1 <= numCourses <= 2000 + * 0 <= prerequisites.length <= 5000 + * prerequisites[i].length == 2 + * 0 <= ai, bi < numCourses + * All the pairs prerequisites[i] are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/course-schedule/ +// discuss: https://leetcode.com/problems/course-schedule/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn can_finish(num_courses: i32, prerequisites: Vec>) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_207() { + } +} diff --git a/src/problem/p0208_implement_trie_prefix_tree.rs b/src/problem/p0208_implement_trie_prefix_tree.rs new file mode 100644 index 00000000..fc8b146c --- /dev/null +++ b/src/problem/p0208_implement_trie_prefix_tree.rs @@ -0,0 +1,89 @@ +/** + * [208] Implement Trie (Prefix Tree) + * + * A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. + * Implement the Trie class: + * + * Trie() Initializes the trie object. + * void insert(String word) Inserts the string word into the trie. + * boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise. + * boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise. + * + * + * Example 1: + * + * Input + * ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] + * [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] + * Output + * [null, null, true, false, true, null, true] + * Explanation + * Trie trie = new Trie(); + * trie.insert("apple"); + * trie.search("apple"); // return True + * trie.search("app"); // return False + * trie.startsWith("app"); // return True + * trie.insert("app"); + * trie.search("app"); // return True + * + * + * Constraints: + * + * 1 <= word.length, prefix.length <= 2000 + * word and prefix consist only of lowercase English letters. + * At most 3 * 10^4 calls in total will be made to insert, search, and startsWith. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/implement-trie-prefix-tree/ +// discuss: https://leetcode.com/problems/implement-trie-prefix-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct Trie { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl Trie { + + fn new() -> Self { + + } + + fn insert(&self, word: String) { + + } + + fn search(&self, word: String) -> bool { + + } + + fn starts_with(&self, prefix: String) -> bool { + + } +} + +/** + * Your Trie object will be instantiated and called as such: + * let obj = Trie::new(); + * obj.insert(word); + * let ret_2: bool = obj.search(word); + * let ret_3: bool = obj.starts_with(prefix); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_208() { + } +} diff --git a/src/problem/p0209_minimum_size_subarray_sum.rs b/src/problem/p0209_minimum_size_subarray_sum.rs new file mode 100644 index 00000000..bf682063 --- /dev/null +++ b/src/problem/p0209_minimum_size_subarray_sum.rs @@ -0,0 +1,54 @@ +/** + * [209] Minimum Size Subarray Sum + * + * Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead. + * + * Example 1: + * + * Input: target = 7, nums = [2,3,1,2,4,3] + * Output: 2 + * Explanation: The subarray [4,3] has the minimal length under the problem constraint. + * + * Example 2: + * + * Input: target = 4, nums = [1,4,4] + * Output: 1 + * + * Example 3: + * + * Input: target = 11, nums = [1,1,1,1,1,1,1,1] + * Output: 0 + * + * + * Constraints: + * + * 1 <= target <= 10^9 + * 1 <= nums.length <= 10^5 + * 1 <= nums[i] <= 10^4 + * + * + * Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)). + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-size-subarray-sum/ +// discuss: https://leetcode.com/problems/minimum-size-subarray-sum/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_sub_array_len(target: i32, nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_209() { + } +} diff --git a/src/problem/p0210_course_schedule_ii.rs b/src/problem/p0210_course_schedule_ii.rs new file mode 100644 index 00000000..b7224583 --- /dev/null +++ b/src/problem/p0210_course_schedule_ii.rs @@ -0,0 +1,61 @@ +/** + * [210] Course Schedule II + * + * There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. + * + * For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. + * + * Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. + * + * Example 1: + * + * Input: numCourses = 2, prerequisites = [[1,0]] + * Output: [0,1] + * Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. + * + * Example 2: + * + * Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] + * Output: [0,2,1,3] + * Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. + * So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. + * + * Example 3: + * + * Input: numCourses = 1, prerequisites = [] + * Output: [0] + * + * + * Constraints: + * + * 1 <= numCourses <= 2000 + * 0 <= prerequisites.length <= numCourses * (numCourses - 1) + * prerequisites[i].length == 2 + * 0 <= ai, bi < numCourses + * ai != bi + * All the pairs [ai, bi] are distinct. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/course-schedule-ii/ +// discuss: https://leetcode.com/problems/course-schedule-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_order(num_courses: i32, prerequisites: Vec>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_210() { + } +} diff --git a/src/problem/p0211_design_add_and_search_words_data_structure.rs b/src/problem/p0211_design_add_and_search_words_data_structure.rs new file mode 100644 index 00000000..a0a50562 --- /dev/null +++ b/src/problem/p0211_design_add_and_search_words_data_structure.rs @@ -0,0 +1,86 @@ +/** + * [211] Design Add and Search Words Data Structure + * + * Design a data structure that supports adding new words and finding if a string matches any previously added string. + * Implement the WordDictionary class: + * + * WordDictionary() Initializes the object. + * void addWord(word) Adds word to the data structure, it can be matched later. + * bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter. + * + * + * Example: + * + * Input + * ["WordDictionary","addWord","addWord","addWord","search","search","search","search"] + * [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] + * Output + * [null,null,null,null,false,true,true,true] + * Explanation + * WordDictionary wordDictionary = new WordDictionary(); + * wordDictionary.addWord("bad"); + * wordDictionary.addWord("dad"); + * wordDictionary.addWord("mad"); + * wordDictionary.search("pad"); // return False + * wordDictionary.search("bad"); // return True + * wordDictionary.search(".ad"); // return True + * wordDictionary.search("b.."); // return True + * + * + * Constraints: + * + * 1 <= word.length <= 25 + * word in addWord consists of lowercase English letters. + * word in search consist of '.' or lowercase English letters. + * There will be at most 3 dots in word for search queries. + * At most 10^4 calls will be made to addWord and search. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/design-add-and-search-words-data-structure/ +// discuss: https://leetcode.com/problems/design-add-and-search-words-data-structure/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct WordDictionary { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl WordDictionary { + + fn new() -> Self { + + } + + fn add_word(&self, word: String) { + + } + + fn search(&self, word: String) -> bool { + + } +} + +/** + * Your WordDictionary object will be instantiated and called as such: + * let obj = WordDictionary::new(); + * obj.add_word(word); + * let ret_2: bool = obj.search(word); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_211() { + } +} diff --git a/src/problem/p0212_word_search_ii.rs b/src/problem/p0212_word_search_ii.rs new file mode 100644 index 00000000..3e06983b --- /dev/null +++ b/src/problem/p0212_word_search_ii.rs @@ -0,0 +1,52 @@ +/** + * [212] Word Search II + * + * Given an m x n board of characters and a list of strings words, return all words on the board. + * Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. + * + * Example 1: + * + * Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] + * Output: ["eat","oath"] + * + * Example 2: + * + * Input: board = [["a","b"],["c","d"]], words = ["abcb"] + * Output: [] + * + * + * Constraints: + * + * m == board.length + * n == board[i].length + * 1 <= m, n <= 12 + * board[i][j] is a lowercase English letter. + * 1 <= words.length <= 3 * 10^4 + * 1 <= words[i].length <= 10 + * words[i] consists of lowercase English letters. + * All the strings of words are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/word-search-ii/ +// discuss: https://leetcode.com/problems/word-search-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_words(board: Vec>, words: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_212() { + } +} diff --git a/src/problem/p0216_combination_sum_iii.rs b/src/problem/p0216_combination_sum_iii.rs new file mode 100644 index 00000000..b56e8c34 --- /dev/null +++ b/src/problem/p0216_combination_sum_iii.rs @@ -0,0 +1,64 @@ +/** + * [216] Combination Sum III + * + * Find all valid combinations of k numbers that sum up to n such that the following conditions are true: + * + * Only numbers 1 through 9 are used. + * Each number is used at most once. + * + * Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order. + * + * Example 1: + * + * Input: k = 3, n = 7 + * Output: [[1,2,4]] + * Explanation: + * 1 + 2 + 4 = 7 + * There are no other valid combinations. + * Example 2: + * + * Input: k = 3, n = 9 + * Output: [[1,2,6],[1,3,5],[2,3,4]] + * Explanation: + * 1 + 2 + 6 = 9 + * 1 + 3 + 5 = 9 + * 2 + 3 + 4 = 9 + * There are no other valid combinations. + * + * Example 3: + * + * Input: k = 4, n = 1 + * Output: [] + * Explanation: There are no valid combinations. + * Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. + * + * + * Constraints: + * + * 2 <= k <= 9 + * 1 <= n <= 60 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/combination-sum-iii/ +// discuss: https://leetcode.com/problems/combination-sum-iii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn combination_sum3(k: i32, n: i32) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_216() { + } +} diff --git a/src/problem/p0218_the_skyline_problem.rs b/src/problem/p0218_the_skyline_problem.rs new file mode 100644 index 00000000..e8a76606 --- /dev/null +++ b/src/problem/p0218_the_skyline_problem.rs @@ -0,0 +1,59 @@ +/** + * [218] The Skyline Problem + * + * A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. + * The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]: + * + * lefti is the x coordinate of the left edge of the i^th building. + * righti is the x coordinate of the right edge of the i^th building. + * heighti is the height of the i^th building. + * + * You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. + * The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. + * Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...] + * + * Example 1: + * + * Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]] + * Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]] + * Explanation: + * Figure A shows the buildings of the input. + * Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. + * + * Example 2: + * + * Input: buildings = [[0,2,3],[2,5,3]] + * Output: [[0,3],[5,0]] + * + * + * Constraints: + * + * 1 <= buildings.length <= 10^4 + * 0 <= lefti < righti <= 2^31 - 1 + * 1 <= heighti <= 2^31 - 1 + * buildings is sorted by lefti in non-decreasing order. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/the-skyline-problem/ +// discuss: https://leetcode.com/problems/the-skyline-problem/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn get_skyline(buildings: Vec>) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_218() { + } +} diff --git a/src/problem/p0226_invert_binary_tree.rs b/src/problem/p0226_invert_binary_tree.rs new file mode 100644 index 00000000..2ef1a316 --- /dev/null +++ b/src/problem/p0226_invert_binary_tree.rs @@ -0,0 +1,71 @@ +/** + * [226] Invert Binary Tree + * + * Given the root of a binary tree, invert the tree, and return its root. + * + * Example 1: + * + * Input: root = [4,2,7,1,3,6,9] + * Output: [4,7,2,9,6,3,1] + * + * Example 2: + * + * Input: root = [2,1,3] + * Output: [2,3,1] + * + * Example 3: + * + * Input: root = [] + * Output: [] + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 100]. + * -100 <= Node.val <= 100 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/invert-binary-tree/ +// discuss: https://leetcode.com/problems/invert-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn invert_tree(root: Option>>) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_226() { + } +} diff --git a/src/problem/p0228_summary_ranges.rs b/src/problem/p0228_summary_ranges.rs new file mode 100644 index 00000000..68f7db76 --- /dev/null +++ b/src/problem/p0228_summary_ranges.rs @@ -0,0 +1,63 @@ +/** + * [228] Summary Ranges + * + * You are given a sorted unique integer array nums. + * A range [a,b] is the set of all integers from a to b (inclusive). + * Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums. + * Each range [a,b] in the list should be output as: + * + * "a->b" if a != b + * "a" if a == b + * + * + * Example 1: + * + * Input: nums = [0,1,2,4,5,7] + * Output: ["0->2","4->5","7"] + * Explanation: The ranges are: + * [0,2] --> "0->2" + * [4,5] --> "4->5" + * [7,7] --> "7" + * + * Example 2: + * + * Input: nums = [0,2,3,4,6,8,9] + * Output: ["0","2->4","6","8->9"] + * Explanation: The ranges are: + * [0,0] --> "0" + * [2,4] --> "2->4" + * [6,6] --> "6" + * [8,9] --> "8->9" + * + * + * Constraints: + * + * 0 <= nums.length <= 20 + * -2^31 <= nums[i] <= 2^31 - 1 + * All the values of nums are unique. + * nums is sorted in ascending order. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/summary-ranges/ +// discuss: https://leetcode.com/problems/summary-ranges/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn summary_ranges(nums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_228() { + } +} diff --git a/src/problem/p0229_majority_element_ii.rs b/src/problem/p0229_majority_element_ii.rs new file mode 100644 index 00000000..a701d717 --- /dev/null +++ b/src/problem/p0229_majority_element_ii.rs @@ -0,0 +1,53 @@ +/** + * [229] Majority Element II + * + * Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. + * + * Example 1: + * + * Input: nums = [3,2,3] + * Output: [3] + * + * Example 2: + * + * Input: nums = [1] + * Output: [1] + * + * Example 3: + * + * Input: nums = [1,2] + * Output: [1,2] + * + * + * Constraints: + * + * 1 <= nums.length <= 5 * 10^4 + * -10^9 <= nums[i] <= 10^9 + * + * + * Follow up: Could you solve the problem in linear time and in O(1) space? + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/majority-element-ii/ +// discuss: https://leetcode.com/problems/majority-element-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn majority_element(nums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_229() { + } +} diff --git a/src/problem/p0230_kth_smallest_element_in_a_bst.rs b/src/problem/p0230_kth_smallest_element_in_a_bst.rs new file mode 100644 index 00000000..7cbebcb4 --- /dev/null +++ b/src/problem/p0230_kth_smallest_element_in_a_bst.rs @@ -0,0 +1,70 @@ +/** + * [230] Kth Smallest Element in a BST + * + * Given the root of a binary search tree, and an integer k, return the k^th smallest value (1-indexed) of all the values of the nodes in the tree. + * + * Example 1: + * + * Input: root = [3,1,4,null,2], k = 1 + * Output: 1 + * + * Example 2: + * + * Input: root = [5,3,6,2,4,null,null,1], k = 3 + * Output: 3 + * + * + * Constraints: + * + * The number of nodes in the tree is n. + * 1 <= k <= n <= 10^4 + * 0 <= Node.val <= 10^4 + * + * + * Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize? + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/kth-smallest-element-in-a-bst/ +// discuss: https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn kth_smallest(root: Option>>, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_230() { + } +} diff --git a/src/solution/s0231_power_of_two.rs b/src/problem/p0231_power_of_two.rs similarity index 56% rename from src/solution/s0231_power_of_two.rs rename to src/problem/p0231_power_of_two.rs index 334fc314..7ca2d762 100644 --- a/src/solution/s0231_power_of_two.rs +++ b/src/problem/p0231_power_of_two.rs @@ -1,29 +1,33 @@ /** * [231] Power of Two * - * Given an integer, write a function to determine if it is a power of two. - * + * Given an integer n, return true if it is a power of two. Otherwise, return false. + * An integer n is a power of two, if there exists an integer x such that n == 2^x. + * * Example 1: - * - * - * Input: 1 + * + * Input: n = 1 * Output: true * Explanation: 2^0 = 1 - * - * + * * Example 2: - * - * - * Input: 16 + * + * Input: n = 16 * Output: true * Explanation: 2^4 = 16 - * + * * Example 3: - * - * - * Input: 218 + * + * Input: n = 3 * Output: false - * + * + * + * Constraints: + * + * -2^31 <= n <= 2^31 - 1 + * + * + * Follow up: Could you solve it without loops/recursion? */ pub struct Solution {} @@ -34,8 +38,7 @@ pub struct Solution {} impl Solution { pub fn is_power_of_two(n: i32) -> bool { - let results: Vec = (0..31).map(|x| 2_i32.pow(x)).collect(); - results.binary_search(&n).is_ok() + false } } @@ -47,8 +50,5 @@ mod tests { #[test] fn test_231() { - assert_eq!(Solution::is_power_of_two(-1), false); - assert_eq!(Solution::is_power_of_two(1), true); - assert_eq!(Solution::is_power_of_two(1024), true); } } diff --git a/src/solution/s0233_number_of_digit_one.rs b/src/problem/p0233_number_of_digit_one.rs similarity index 77% rename from src/solution/s0233_number_of_digit_one.rs rename to src/problem/p0233_number_of_digit_one.rs index 60097ed0..931d41b8 100644 --- a/src/solution/s0233_number_of_digit_one.rs +++ b/src/problem/p0233_number_of_digit_one.rs @@ -2,15 +2,22 @@ * [233] Number of Digit One * * Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. - * - * Example: - * - * - * Input: 13 + * + * Example 1: + * + * Input: n = 13 * Output: 6 - * Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. - * - * + * + * Example 2: + * + * Input: n = 0 + * Output: 0 + * + * + * Constraints: + * + * 0 <= n <= 10^9 + * */ pub struct Solution {} @@ -32,5 +39,6 @@ mod tests { use super::*; #[test] - fn test_233() {} + fn test_233() { + } } diff --git a/src/problem/p0235_lowest_common_ancestor_of_a_binary_search_tree.rs b/src/problem/p0235_lowest_common_ancestor_of_a_binary_search_tree.rs new file mode 100644 index 00000000..49b377b6 --- /dev/null +++ b/src/problem/p0235_lowest_common_ancestor_of_a_binary_search_tree.rs @@ -0,0 +1,77 @@ +/** + * [235] Lowest Common Ancestor of a Binary Search Tree + * + * Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. + * According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” + * + * Example 1: + * + * Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 + * Output: 6 + * Explanation: The LCA of nodes 2 and 8 is 6. + * + * Example 2: + * + * Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 + * Output: 2 + * Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. + * + * Example 3: + * + * Input: root = [2,1], p = 2, q = 1 + * Output: 2 + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [2, 10^5]. + * -10^9 <= Node.val <= 10^9 + * All Node.val are unique. + * p != q + * p and q will exist in the BST. + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ +// discuss: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn lowest_common_ancestor(root: Option>>, p: Option>>, q: Option>>) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_235() { + } +} diff --git a/src/problem/p0239_sliding_window_maximum.rs b/src/problem/p0239_sliding_window_maximum.rs new file mode 100644 index 00000000..991f59f0 --- /dev/null +++ b/src/problem/p0239_sliding_window_maximum.rs @@ -0,0 +1,56 @@ +/** + * [239] Sliding Window Maximum + * + * You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. + * Return the max sliding window. + * + * Example 1: + * + * Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 + * Output: [3,3,5,5,6,7] + * Explanation: + * Window position Max + * --------------- ----- + * [1 3 -1] -3 5 3 6 7 3 + * 1 [3 -1 -3] 5 3 6 7 3 + * 1 3 [-1 -3 5] 3 6 7 5 + * 1 3 -1 [-3 5 3] 6 7 5 + * 1 3 -1 -3 [5 3 6] 7 6 + * 1 3 -1 -3 5 [3 6 7] 7 + * + * Example 2: + * + * Input: nums = [1], k = 1 + * Output: [1] + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * -10^4 <= nums[i] <= 10^4 + * 1 <= k <= nums.length + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/sliding-window-maximum/ +// discuss: https://leetcode.com/problems/sliding-window-maximum/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_sliding_window(nums: Vec, k: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_239() { + } +} diff --git a/src/problem/p0258_add_digits.rs b/src/problem/p0258_add_digits.rs new file mode 100644 index 00000000..06735cff --- /dev/null +++ b/src/problem/p0258_add_digits.rs @@ -0,0 +1,51 @@ +/** + * [258] Add Digits + * + * Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. + * + * Example 1: + * + * Input: num = 38 + * Output: 2 + * Explanation: The process is + * 38 --> 3 + 8 --> 11 + * 11 --> 1 + 1 --> 2 + * Since 2 has only one digit, return it. + * + * Example 2: + * + * Input: num = 0 + * Output: 0 + * + * + * Constraints: + * + * 0 <= num <= 2^31 - 1 + * + * + * Follow up: Could you do it without any loop/recursion in O(1) runtime? + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/add-digits/ +// discuss: https://leetcode.com/problems/add-digits/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn add_digits(num: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_258() { + } +} diff --git a/src/problem/p0260_single_number_iii.rs b/src/problem/p0260_single_number_iii.rs new file mode 100644 index 00000000..9becb3f2 --- /dev/null +++ b/src/problem/p0260_single_number_iii.rs @@ -0,0 +1,53 @@ +/** + * [260] Single Number III + * + * Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order. + * You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. + * + * Example 1: + * + * Input: nums = [1,2,1,3,2,5] + * Output: [3,5] + * Explanation: [5, 3] is also a valid answer. + * + * Example 2: + * + * Input: nums = [-1,0] + * Output: [-1,0] + * + * Example 3: + * + * Input: nums = [0,1] + * Output: [1,0] + * + * + * Constraints: + * + * 2 <= nums.length <= 3 * 10^4 + * -2^31 <= nums[i] <= 2^31 - 1 + * Each integer in nums will appear twice, only two integers will appear once. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/single-number-iii/ +// discuss: https://leetcode.com/problems/single-number-iii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn single_number(nums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_260() { + } +} diff --git a/src/problem/p0263_ugly_number.rs b/src/problem/p0263_ugly_number.rs new file mode 100644 index 00000000..b68a630a --- /dev/null +++ b/src/problem/p0263_ugly_number.rs @@ -0,0 +1,53 @@ +/** + * [263] Ugly Number + * + * An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. + * Given an integer n, return true if n is an ugly number. + * + * Example 1: + * + * Input: n = 6 + * Output: true + * Explanation: 6 = 2 × 3 + * + * Example 2: + * + * Input: n = 1 + * Output: true + * Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. + * + * Example 3: + * + * Input: n = 14 + * Output: false + * Explanation: 14 is not ugly since it includes the prime factor 7. + * + * + * Constraints: + * + * -2^31 <= n <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/ugly-number/ +// discuss: https://leetcode.com/problems/ugly-number/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_ugly(n: i32) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_263() { + } +} diff --git a/src/problem/p0268_missing_number.rs b/src/problem/p0268_missing_number.rs new file mode 100644 index 00000000..c3336902 --- /dev/null +++ b/src/problem/p0268_missing_number.rs @@ -0,0 +1,58 @@ +/** + * [268] Missing Number + * + * Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. + * + * Example 1: + * + * Input: nums = [3,0,1] + * Output: 2 + * Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. + * + * Example 2: + * + * Input: nums = [0,1] + * Output: 2 + * Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. + * + * Example 3: + * + * Input: nums = [9,6,4,2,3,5,7,0,1] + * Output: 8 + * Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. + * + * + * Constraints: + * + * n == nums.length + * 1 <= n <= 10^4 + * 0 <= nums[i] <= n + * All the numbers of nums are unique. + * + * + * Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/missing-number/ +// discuss: https://leetcode.com/problems/missing-number/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn missing_number(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_268() { + } +} diff --git a/src/problem/p0275_h_index_ii.rs b/src/problem/p0275_h_index_ii.rs new file mode 100644 index 00000000..ba28f02a --- /dev/null +++ b/src/problem/p0275_h_index_ii.rs @@ -0,0 +1,52 @@ +/** + * [275] H-Index II + * + * Given an array of integers citations where citations[i] is the number of citations a researcher received for their i^th paper and citations is sorted in an ascending order, return compute the researcher's h-index. + * According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n - h papers have no more than h citations each. + * If there are several possible values for h, the maximum one is taken as the h-index. + * You must write an algorithm that runs in logarithmic time. + * + * Example 1: + * + * Input: citations = [0,1,3,5,6] + * Output: 3 + * Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. + * Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. + * + * Example 2: + * + * Input: citations = [1,2,100] + * Output: 2 + * + * + * Constraints: + * + * n == citations.length + * 1 <= n <= 10^5 + * 0 <= citations[i] <= 1000 + * citations is sorted in ascending order. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/h-index-ii/ +// discuss: https://leetcode.com/problems/h-index-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn h_index(citations: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_275() { + } +} diff --git a/src/problem/p0299_bulls_and_cows.rs b/src/problem/p0299_bulls_and_cows.rs new file mode 100644 index 00000000..387ff3fb --- /dev/null +++ b/src/problem/p0299_bulls_and_cows.rs @@ -0,0 +1,61 @@ +/** + * [299] Bulls and Cows + * + * You are playing the Bulls and Cows game with your friend. + * You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: + * + * The number of "bulls", which are digits in the guess that are in the correct position. + * The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls. + * + * Given the secret number secret and your friend's guess guess, return the hint for your friend's guess. + * The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits. + * + * Example 1: + * + * Input: secret = "1807", guess = "7810" + * Output: "1A3B" + * Explanation: Bulls are connected with a '|' and cows are underlined: + * "1807" + * | + * "7810" + * Example 2: + * + * Input: secret = "1123", guess = "0111" + * Output: "1A1B" + * Explanation: Bulls are connected with a '|' and cows are underlined: + * "1123" "1123" + * | or | + * "0111" "0111" + * Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. + * + * + * Constraints: + * + * 1 <= secret.length, guess.length <= 1000 + * secret.length == guess.length + * secret and guess consist of digits only. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/bulls-and-cows/ +// discuss: https://leetcode.com/problems/bulls-and-cows/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn get_hint(secret: String, guess: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_299() { + } +} diff --git a/src/problem/p0300_longest_increasing_subsequence.rs b/src/problem/p0300_longest_increasing_subsequence.rs new file mode 100644 index 00000000..4bfef300 --- /dev/null +++ b/src/problem/p0300_longest_increasing_subsequence.rs @@ -0,0 +1,55 @@ +/** + * [300] Longest Increasing Subsequence + * + * Given an integer array nums, return the length of the longest strictly increasing subsequence. + * A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. + * + * Example 1: + * + * Input: nums = [10,9,2,5,3,7,101,18] + * Output: 4 + * Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. + * + * Example 2: + * + * Input: nums = [0,1,0,3,2,3] + * Output: 4 + * + * Example 3: + * + * Input: nums = [7,7,7,7,7,7,7] + * Output: 1 + * + * + * Constraints: + * + * 1 <= nums.length <= 2500 + * -10^4 <= nums[i] <= 10^4 + * + * + * Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity? + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-increasing-subsequence/ +// discuss: https://leetcode.com/problems/longest-increasing-subsequence/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn length_of_lis(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_300() { + } +} diff --git a/src/problem/p0303_range_sum_query_immutable.rs b/src/problem/p0303_range_sum_query_immutable.rs new file mode 100644 index 00000000..ca7f830d --- /dev/null +++ b/src/problem/p0303_range_sum_query_immutable.rs @@ -0,0 +1,78 @@ +/** + * [303] Range Sum Query - Immutable + * + * Given an integer array nums, handle multiple queries of the following type: + *
    + * Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. + *
+ * Implement the NumArray class: + * + * NumArray(int[] nums) Initializes the object with the integer array nums. + * int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]). + * + * + * Example 1: + * + * Input + * ["NumArray", "sumRange", "sumRange", "sumRange"] + * [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] + * Output + * [null, 1, -1, -3] + * Explanation + * NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); + * numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 + * numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 + * numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 + * + * + * Constraints: + * + * 1 <= nums.length <= 10^4 + * -10^5 <= nums[i] <= 10^5 + * 0 <= left <= right < nums.length + * At most 10^4 calls will be made to sumRange. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/range-sum-query-immutable/ +// discuss: https://leetcode.com/problems/range-sum-query-immutable/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct NumArray { + vec![] + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl NumArray { + + fn new(nums: Vec) -> Self { + + } + + fn sum_range(&self, left: i32, right: i32) -> i32 { + + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * let obj = NumArray::new(nums); + * let ret_1: i32 = obj.sum_range(left, right); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_303() { + } +} diff --git a/src/problem/p0304_range_sum_query_2d_immutable.rs b/src/problem/p0304_range_sum_query_2d_immutable.rs new file mode 100644 index 00000000..dd8751d8 --- /dev/null +++ b/src/problem/p0304_range_sum_query_2d_immutable.rs @@ -0,0 +1,81 @@ +/** + * [304] Range Sum Query 2D - Immutable + * + * Given a 2D matrix matrix, handle multiple queries of the following type: + * + * Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). + * + * Implement the NumMatrix class: + * + * NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix. + * int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). + * + * + * Example 1: + * + * Input + * ["NumMatrix", "sumRegion", "sumRegion", "sumRegion"] + * [[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]] + * Output + * [null, 8, 11, 12] + * Explanation + * NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]); + * numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) + * numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) + * numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) + * + * + * Constraints: + * + * m == matrix.length + * n == matrix[i].length + * 1 <= m, n <= 200 + * -10^4 <= matrix[i][j] <= 10^4 + * 0 <= row1 <= row2 < m + * 0 <= col1 <= col2 < n + * At most 10^4 calls will be made to sumRegion. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/range-sum-query-2d-immutable/ +// discuss: https://leetcode.com/problems/range-sum-query-2d-immutable/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct NumMatrix { + vec![] + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl NumMatrix { + + fn new(matrix: Vec>) -> Self { + + } + + fn sum_region(&self, row1: i32, col1: i32, row2: i32, col2: i32) -> i32 { + + } +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * let obj = NumMatrix::new(matrix); + * let ret_1: i32 = obj.sum_region(row1, col1, row2, col2); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_304() { + } +} diff --git a/src/problem/p0309_best_time_to_buy_and_sell_stock_with_cooldown.rs b/src/problem/p0309_best_time_to_buy_and_sell_stock_with_cooldown.rs new file mode 100644 index 00000000..31d6d9fa --- /dev/null +++ b/src/problem/p0309_best_time_to_buy_and_sell_stock_with_cooldown.rs @@ -0,0 +1,51 @@ +/** + * [309] Best Time to Buy and Sell Stock with Cooldown + * + * You are given an array prices where prices[i] is the price of a given stock on the i^th day. + * Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: + * + * After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). + * + * Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). + * + * Example 1: + * + * Input: prices = [1,2,3,0,2] + * Output: 3 + * Explanation: transactions = [buy, sell, cooldown, buy, sell] + * + * Example 2: + * + * Input: prices = [1] + * Output: 0 + * + * + * Constraints: + * + * 1 <= prices.length <= 5000 + * 0 <= prices[i] <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ +// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_309() { + } +} diff --git a/src/problem/p0310_minimum_height_trees.rs b/src/problem/p0310_minimum_height_trees.rs new file mode 100644 index 00000000..73c39aec --- /dev/null +++ b/src/problem/p0310_minimum_height_trees.rs @@ -0,0 +1,53 @@ +/** + * [310] Minimum Height Trees + * + * A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. + * Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs). + * Return a list of all MHTs' root labels. You can return the answer in any order. + * The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. + * + * Example 1: + * + * Input: n = 4, edges = [[1,0],[1,2],[1,3]] + * Output: [1] + * Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT. + * + * Example 2: + * + * Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]] + * Output: [3,4] + * + * + * Constraints: + * + * 1 <= n <= 2 * 10^4 + * edges.length == n - 1 + * 0 <= ai, bi < n + * ai != bi + * All the pairs (ai, bi) are distinct. + * The given input is guaranteed to be a tree and there will be no repeated edges. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-height-trees/ +// discuss: https://leetcode.com/problems/minimum-height-trees/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_min_height_trees(n: i32, edges: Vec>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_310() { + } +} diff --git a/src/problem/p0312_burst_balloons.rs b/src/problem/p0312_burst_balloons.rs new file mode 100644 index 00000000..f8fc11e7 --- /dev/null +++ b/src/problem/p0312_burst_balloons.rs @@ -0,0 +1,50 @@ +/** + * [312] Burst Balloons + * + * You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. + * If you burst the i^th balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it. + * Return the maximum coins you can collect by bursting the balloons wisely. + * + * Example 1: + * + * Input: nums = [3,1,5,8] + * Output: 167 + * Explanation: + * nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] + * coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 + * Example 2: + * + * Input: nums = [1,5] + * Output: 10 + * + * + * Constraints: + * + * n == nums.length + * 1 <= n <= 300 + * 0 <= nums[i] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/burst-balloons/ +// discuss: https://leetcode.com/problems/burst-balloons/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_coins(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_312() { + } +} diff --git a/src/problem/p0313_super_ugly_number.rs b/src/problem/p0313_super_ugly_number.rs new file mode 100644 index 00000000..25fac33f --- /dev/null +++ b/src/problem/p0313_super_ugly_number.rs @@ -0,0 +1,52 @@ +/** + * [313] Super Ugly Number + * + * A super ugly number is a positive integer whose prime factors are in the array primes. + * Given an integer n and an array of integers primes, return the n^th super ugly number. + * The n^th super ugly number is guaranteed to fit in a 32-bit signed integer. + * + * Example 1: + * + * Input: n = 12, primes = [2,7,13,19] + * Output: 32 + * Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19]. + * + * Example 2: + * + * Input: n = 1, primes = [2,3,5] + * Output: 1 + * Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5]. + * + * + * Constraints: + * + * 1 <= n <= 10^5 + * 1 <= primes.length <= 100 + * 2 <= primes[i] <= 1000 + * primes[i] is guaranteed to be a prime number. + * All the values of primes are unique and sorted in ascending order. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/super-ugly-number/ +// discuss: https://leetcode.com/problems/super-ugly-number/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn nth_super_ugly_number(n: i32, primes: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_313() { + } +} diff --git a/src/problem/p0318_maximum_product_of_word_lengths.rs b/src/problem/p0318_maximum_product_of_word_lengths.rs new file mode 100644 index 00000000..a107ba1f --- /dev/null +++ b/src/problem/p0318_maximum_product_of_word_lengths.rs @@ -0,0 +1,54 @@ +/** + * [318] Maximum Product of Word Lengths + * + * Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0. + * + * Example 1: + * + * Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"] + * Output: 16 + * Explanation: The two words can be "abcw", "xtfn". + * + * Example 2: + * + * Input: words = ["a","ab","abc","d","cd","bcd","abcd"] + * Output: 4 + * Explanation: The two words can be "ab", "cd". + * + * Example 3: + * + * Input: words = ["a","aa","aaa","aaaa"] + * Output: 0 + * Explanation: No such pair of words. + * + * + * Constraints: + * + * 2 <= words.length <= 1000 + * 1 <= words[i].length <= 1000 + * words[i] consists only of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-product-of-word-lengths/ +// discuss: https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_product(words: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_318() { + } +} diff --git a/src/problem/p0319_bulb_switcher.rs b/src/problem/p0319_bulb_switcher.rs new file mode 100644 index 00000000..886ea693 --- /dev/null +++ b/src/problem/p0319_bulb_switcher.rs @@ -0,0 +1,55 @@ +/** + * [319] Bulb Switcher + * + * There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. + * On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i^th round, you toggle every i bulb. For the n^th round, you only toggle the last bulb. + * Return the number of bulbs that are on after n rounds. + * + * Example 1: + * + * Input: n = 3 + * Output: 1 + * Explanation: At first, the three bulbs are [off, off, off]. + * After the first round, the three bulbs are [on, on, on]. + * After the second round, the three bulbs are [on, off, on]. + * After the third round, the three bulbs are [on, off, off]. + * So you should return 1 because there is only one bulb is on. + * Example 2: + * + * Input: n = 0 + * Output: 0 + * + * Example 3: + * + * Input: n = 1 + * Output: 1 + * + * + * Constraints: + * + * 0 <= n <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/bulb-switcher/ +// discuss: https://leetcode.com/problems/bulb-switcher/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn bulb_switch(n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_319() { + } +} diff --git a/src/problem/p0327_count_of_range_sum.rs b/src/problem/p0327_count_of_range_sum.rs new file mode 100644 index 00000000..c140cb8f --- /dev/null +++ b/src/problem/p0327_count_of_range_sum.rs @@ -0,0 +1,49 @@ +/** + * [327] Count of Range Sum + * + * Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive. + * Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j. + * + * Example 1: + * + * Input: nums = [-2,5,-1], lower = -2, upper = 2 + * Output: 3 + * Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. + * + * Example 2: + * + * Input: nums = [0], lower = 0, upper = 0 + * Output: 1 + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * -2^31 <= nums[i] <= 2^31 - 1 + * -10^5 <= lower <= upper <= 10^5 + * The answer is guaranteed to fit in a 32-bit integer. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-of-range-sum/ +// discuss: https://leetcode.com/problems/count-of-range-sum/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_range_sum(nums: Vec, lower: i32, upper: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_327() { + } +} diff --git a/src/problem/p0329_longest_increasing_path_in_a_matrix.rs b/src/problem/p0329_longest_increasing_path_in_a_matrix.rs new file mode 100644 index 00000000..f788f9ef --- /dev/null +++ b/src/problem/p0329_longest_increasing_path_in_a_matrix.rs @@ -0,0 +1,55 @@ +/** + * [329] Longest Increasing Path in a Matrix + * + * Given an m x n integers matrix, return the length of the longest increasing path in matrix. + * From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed). + * + * Example 1: + * + * Input: matrix = [[9,9,4],[6,6,8],[2,1,1]] + * Output: 4 + * Explanation: The longest increasing path is [1, 2, 6, 9]. + * + * Example 2: + * + * Input: matrix = [[3,4,5],[3,2,6],[2,2,1]] + * Output: 4 + * Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. + * + * Example 3: + * + * Input: matrix = [[1]] + * Output: 1 + * + * + * Constraints: + * + * m == matrix.length + * n == matrix[i].length + * 1 <= m, n <= 200 + * 0 <= matrix[i][j] <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ +// discuss: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn longest_increasing_path(matrix: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_329() { + } +} diff --git a/src/problem/p0330_patching_array.rs b/src/problem/p0330_patching_array.rs new file mode 100644 index 00000000..b50059bb --- /dev/null +++ b/src/problem/p0330_patching_array.rs @@ -0,0 +1,59 @@ +/** + * [330] Patching Array + * + * Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. + * Return the minimum number of patches required. + * + * Example 1: + * + * Input: nums = [1,3], n = 6 + * Output: 1 + * Explanation: + * Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. + * Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. + * Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. + * So we only need 1 patch. + * + * Example 2: + * + * Input: nums = [1,5,10], n = 20 + * Output: 2 + * Explanation: The two patches can be [2, 4]. + * + * Example 3: + * + * Input: nums = [1,2,2], n = 5 + * Output: 0 + * + * + * Constraints: + * + * 1 <= nums.length <= 1000 + * 1 <= nums[i] <= 10^4 + * nums is sorted in ascending order. + * 1 <= n <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/patching-array/ +// discuss: https://leetcode.com/problems/patching-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_patches(nums: Vec, n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_330() { + } +} diff --git a/src/problem/p0336_palindrome_pairs.rs b/src/problem/p0336_palindrome_pairs.rs new file mode 100644 index 00000000..803091da --- /dev/null +++ b/src/problem/p0336_palindrome_pairs.rs @@ -0,0 +1,53 @@ +/** + * [336] Palindrome Pairs + * + * Given a list of unique words, return all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of the two words words[i] + words[j] is a palindrome. + * + * Example 1: + * + * Input: words = ["abcd","dcba","lls","s","sssll"] + * Output: [[0,1],[1,0],[3,2],[2,4]] + * Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"] + * + * Example 2: + * + * Input: words = ["bat","tab","cat"] + * Output: [[0,1],[1,0]] + * Explanation: The palindromes are ["battab","tabbat"] + * + * Example 3: + * + * Input: words = ["a",""] + * Output: [[0,1],[1,0]] + * + * + * Constraints: + * + * 1 <= words.length <= 5000 + * 0 <= words[i].length <= 300 + * words[i] consists of lower-case English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/palindrome-pairs/ +// discuss: https://leetcode.com/problems/palindrome-pairs/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn palindrome_pairs(words: Vec) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_336() { + } +} diff --git a/src/problem/p0341_flatten_nested_list_iterator.rs b/src/problem/p0341_flatten_nested_list_iterator.rs new file mode 100644 index 00000000..09a0d9e8 --- /dev/null +++ b/src/problem/p0341_flatten_nested_list_iterator.rs @@ -0,0 +1,92 @@ +/** + * [341] Flatten Nested List Iterator + * + * You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. + * Implement the NestedIterator class: + * + * NestedIterator(List nestedList) Initializes the iterator with the nested list nestedList. + * int next() Returns the next integer in the nested list. + * boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise. + * + * Your code will be tested with the following pseudocode: + * + * initialize iterator with nestedList + * res = [] + * while iterator.hasNext() + * append iterator.next() to the end of res + * return res + * + * If res matches the expected flattened list, then your code will be judged as correct. + * + * Example 1: + * + * Input: nestedList = [[1,1],2,[1,1]] + * Output: [1,1,2,1,1] + * Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. + * + * Example 2: + * + * Input: nestedList = [1,[4,[6]]] + * Output: [1,4,6] + * Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. + * + * + * Constraints: + * + * 1 <= nestedList.length <= 500 + * The values of the integers in the nested list is in the range [-10^6, 10^6]. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/flatten-nested-list-iterator/ +// discuss: https://leetcode.com/problems/flatten-nested-list-iterator/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// #[derive(Debug, PartialEq, Eq)] +// pub enum NestedInteger { +// Int(i32), +// List(Vec) +// } +struct NestedIterator { + 0 + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl NestedIterator { + + fn new(nestedList: Vec) -> Self { + + } + + fn next(&self) -> i32 { + + } + + fn has_next(&self) -> bool { + + } +} + +/** + * Your NestedIterator object will be instantiated and called as such: + * let obj = NestedIterator::new(nestedList); + * let ret_1: i32 = obj.next(); + * let ret_2: bool = obj.has_next(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_341() { + } +} diff --git a/src/problem/p0342_power_of_four.rs b/src/problem/p0342_power_of_four.rs new file mode 100644 index 00000000..e04a6c84 --- /dev/null +++ b/src/problem/p0342_power_of_four.rs @@ -0,0 +1,46 @@ +/** + * [342] Power of Four + * + * Given an integer n, return true if it is a power of four. Otherwise, return false. + * An integer n is a power of four, if there exists an integer x such that n == 4^x. + * + * Example 1: + * Input: n = 16 + * Output: true + * Example 2: + * Input: n = 5 + * Output: false + * Example 3: + * Input: n = 1 + * Output: true + * + * Constraints: + * + * -2^31 <= n <= 2^31 - 1 + * + * + * Follow up: Could you solve it without loops/recursion? + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/power-of-four/ +// discuss: https://leetcode.com/problems/power-of-four/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_power_of_four(n: i32) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_342() { + } +} diff --git a/src/problem/p0343_integer_break.rs b/src/problem/p0343_integer_break.rs new file mode 100644 index 00000000..d3f4ea0f --- /dev/null +++ b/src/problem/p0343_integer_break.rs @@ -0,0 +1,47 @@ +/** + * [343] Integer Break + * + * Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. + * Return the maximum product you can get. + * + * Example 1: + * + * Input: n = 2 + * Output: 1 + * Explanation: 2 = 1 + 1, 1 × 1 = 1. + * + * Example 2: + * + * Input: n = 10 + * Output: 36 + * Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. + * + * + * Constraints: + * + * 2 <= n <= 58 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/integer-break/ +// discuss: https://leetcode.com/problems/integer-break/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn integer_break(n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_343() { + } +} diff --git a/src/problem/p0350_intersection_of_two_arrays_ii.rs b/src/problem/p0350_intersection_of_two_arrays_ii.rs new file mode 100644 index 00000000..c5175f93 --- /dev/null +++ b/src/problem/p0350_intersection_of_two_arrays_ii.rs @@ -0,0 +1,53 @@ +/** + * [350] Intersection of Two Arrays II + * + * Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. + * + * Example 1: + * + * Input: nums1 = [1,2,2,1], nums2 = [2,2] + * Output: [2,2] + * + * Example 2: + * + * Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] + * Output: [4,9] + * Explanation: [9,4] is also accepted. + * + * + * Constraints: + * + * 1 <= nums1.length, nums2.length <= 1000 + * 0 <= nums1[i], nums2[i] <= 1000 + * + * + * Follow up: + * + * What if the given array is already sorted? How would you optimize your algorithm? + * What if nums1's size is small compared to nums2's size? Which algorithm is better? + * What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/intersection-of-two-arrays-ii/ +// discuss: https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn intersect(nums1: Vec, nums2: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_350() { + } +} diff --git a/src/problem/p0354_russian_doll_envelopes.rs b/src/problem/p0354_russian_doll_envelopes.rs new file mode 100644 index 00000000..b2b0e346 --- /dev/null +++ b/src/problem/p0354_russian_doll_envelopes.rs @@ -0,0 +1,50 @@ +/** + * [354] Russian Doll Envelopes + * + * You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope. + * One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. + * Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other). + * Note: You cannot rotate an envelope. + * + * Example 1: + * + * Input: envelopes = [[5,4],[6,4],[6,7],[2,3]] + * Output: 3 + * Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). + * + * Example 2: + * + * Input: envelopes = [[1,1],[1,1],[1,1]] + * Output: 1 + * + * + * Constraints: + * + * 1 <= envelopes.length <= 10^5 + * envelopes[i].length == 2 + * 1 <= wi, hi <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/russian-doll-envelopes/ +// discuss: https://leetcode.com/problems/russian-doll-envelopes/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_envelopes(envelopes: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_354() { + } +} diff --git a/src/problem/p0355_design_twitter.rs b/src/problem/p0355_design_twitter.rs new file mode 100644 index 00000000..dc50ddbd --- /dev/null +++ b/src/problem/p0355_design_twitter.rs @@ -0,0 +1,97 @@ +/** + * [355] Design Twitter + * + * Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user's news feed. + * Implement the Twitter class: + * + * Twitter() Initializes your twitter object. + * void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId. + * List getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent. + * void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId. + * void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId. + * + * + * Example 1: + * + * Input + * ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] + * [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]] + * Output + * [null, null, [5], null, null, [6, 5], null, [5]] + * Explanation + * Twitter twitter = new Twitter(); + * twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). + * twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5] + * twitter.follow(1, 2); // User 1 follows user 2. + * twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). + * twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. + * twitter.unfollow(1, 2); // User 1 unfollows user 2. + * twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2. + * + * + * Constraints: + * + * 1 <= userId, followerId, followeeId <= 500 + * 0 <= tweetId <= 10^4 + * All the tweets have unique IDs. + * At most 3 * 10^4 calls will be made to postTweet, getNewsFeed, follow, and unfollow. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/design-twitter/ +// discuss: https://leetcode.com/problems/design-twitter/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct Twitter { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl Twitter { + + fn new() -> Self { + + } + + fn post_tweet(&self, user_id: i32, tweet_id: i32) { + + } + + fn get_news_feed(&self, user_id: i32) -> Vec { + + } + + fn follow(&self, follower_id: i32, followee_id: i32) { + + } + + fn unfollow(&self, follower_id: i32, followee_id: i32) { + + } +} + +/** + * Your Twitter object will be instantiated and called as such: + * let obj = Twitter::new(); + * obj.post_tweet(userId, tweetId); + * let ret_2: Vec = obj.get_news_feed(userId); + * obj.follow(followerId, followeeId); + * obj.unfollow(followerId, followeeId); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_355() { + } +} diff --git a/src/problem/p0357_count_numbers_with_unique_digits.rs b/src/problem/p0357_count_numbers_with_unique_digits.rs new file mode 100644 index 00000000..604d7328 --- /dev/null +++ b/src/problem/p0357_count_numbers_with_unique_digits.rs @@ -0,0 +1,45 @@ +/** + * [357] Count Numbers with Unique Digits + * + * Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10^n. + * + * Example 1: + * + * Input: n = 2 + * Output: 91 + * Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99 + * + * Example 2: + * + * Input: n = 0 + * Output: 1 + * + * + * Constraints: + * + * 0 <= n <= 8 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-numbers-with-unique-digits/ +// discuss: https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_numbers_with_unique_digits(n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_357() { + } +} diff --git a/src/problem/p0363_max_sum_of_rectangle_no_larger_than_k.rs b/src/problem/p0363_max_sum_of_rectangle_no_larger_than_k.rs new file mode 100644 index 00000000..b721a719 --- /dev/null +++ b/src/problem/p0363_max_sum_of_rectangle_no_larger_than_k.rs @@ -0,0 +1,53 @@ +/** + * [363] Max Sum of Rectangle No Larger Than K + * + * Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k. + * It is guaranteed that there will be a rectangle with a sum no larger than k. + * + * Example 1: + * + * Input: matrix = [[1,0,1],[0,-2,3]], k = 2 + * Output: 2 + * Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2). + * + * Example 2: + * + * Input: matrix = [[2,2,-1]], k = 3 + * Output: 3 + * + * + * Constraints: + * + * m == matrix.length + * n == matrix[i].length + * 1 <= m, n <= 100 + * -100 <= matrix[i][j] <= 100 + * -10^5 <= k <= 10^5 + * + * + * Follow up: What if the number of rows is much larger than the number of columns? + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/ +// discuss: https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_sum_submatrix(matrix: Vec>, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_363() { + } +} diff --git a/src/problem/p0367_valid_perfect_square.rs b/src/problem/p0367_valid_perfect_square.rs new file mode 100644 index 00000000..194d210a --- /dev/null +++ b/src/problem/p0367_valid_perfect_square.rs @@ -0,0 +1,41 @@ +/** + * [367] Valid Perfect Square + * + * Given a positive integer num, write a function which returns True if num is a perfect square else False. + * Follow up: Do not use any built-in library function such as sqrt. + * + * Example 1: + * Input: num = 16 + * Output: true + * Example 2: + * Input: num = 14 + * Output: false + * + * Constraints: + * + * 1 <= num <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/valid-perfect-square/ +// discuss: https://leetcode.com/problems/valid-perfect-square/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_perfect_square(num: i32) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_367() { + } +} diff --git a/src/problem/p0368_largest_divisible_subset.rs b/src/problem/p0368_largest_divisible_subset.rs new file mode 100644 index 00000000..7d37c8f6 --- /dev/null +++ b/src/problem/p0368_largest_divisible_subset.rs @@ -0,0 +1,52 @@ +/** + * [368] Largest Divisible Subset + * + * Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies: + * + * answer[i] % answer[j] == 0, or + * answer[j] % answer[i] == 0 + * + * If there are multiple solutions, return any of them. + * + * Example 1: + * + * Input: nums = [1,2,3] + * Output: [1,2] + * Explanation: [1,3] is also accepted. + * + * Example 2: + * + * Input: nums = [1,2,4,8] + * Output: [1,2,4,8] + * + * + * Constraints: + * + * 1 <= nums.length <= 1000 + * 1 <= nums[i] <= 2 * 10^9 + * All the integers in nums are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/largest-divisible-subset/ +// discuss: https://leetcode.com/problems/largest-divisible-subset/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn largest_divisible_subset(nums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_368() { + } +} diff --git a/src/problem/p0375_guess_number_higher_or_lower_ii.rs b/src/problem/p0375_guess_number_higher_or_lower_ii.rs new file mode 100644 index 00000000..2373ecb3 --- /dev/null +++ b/src/problem/p0375_guess_number_higher_or_lower_ii.rs @@ -0,0 +1,80 @@ +/** + * [375] Guess Number Higher or Lower II + * + * We are playing the Guessing Game. The game will work as follows: + *
    + * I pick a number between 1 and n. + * You guess a number. + * If you guess the right number, you win the game. + * If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing. + * Every time you guess a wrong number x, you will pay x dollars. If you run out of money, you lose the game. + *
+ * Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick. + * + * Example 1: + * + * Input: n = 10 + * Output: 16 + * Explanation: The winning strategy is as follows: + * - The range is [1,10]. Guess 7. + * - If this is my number, your total is $0. Otherwise, you pay $7. + * - If my number is higher, the range is [8,10]. Guess 9. + * - If this is my number, your total is $7. Otherwise, you pay $9. + * - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16. + * - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16. + * - If my number is lower, the range is [1,6]. Guess 3. + * - If this is my number, your total is $7. Otherwise, you pay $3. + * - If my number is higher, the range is [4,6]. Guess 5. + * - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5. + * - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15. + * - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15. + * - If my number is lower, the range is [1,2]. Guess 1. + * - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1. + * - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11. + * The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win. + * + * Example 2: + * + * Input: n = 1 + * Output: 0 + * Explanation: There is only one possible number, so you can guess 1 and not have to pay anything. + * + * Example 3: + * + * Input: n = 2 + * Output: 1 + * Explanation: There are two possible numbers, 1 and 2. + * - Guess 1. + * - If this is my number, your total is $0. Otherwise, you pay $1. + * - If my number is higher, it must be 2. Guess 2. Your total is $1. + * The worst case is that you pay $1. + * + * + * Constraints: + * + * 1 <= n <= 200 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/guess-number-higher-or-lower-ii/ +// discuss: https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn get_money_amount(n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_375() { + } +} diff --git a/src/problem/p0376_wiggle_subsequence.rs b/src/problem/p0376_wiggle_subsequence.rs new file mode 100644 index 00000000..cb6ab5d9 --- /dev/null +++ b/src/problem/p0376_wiggle_subsequence.rs @@ -0,0 +1,62 @@ +/** + * [376] Wiggle Subsequence + * + * A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. + * + * For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative. + * In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero. + * + * A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. + * Given an integer array nums, return the length of the longest wiggle subsequence of nums. + * + * Example 1: + * + * Input: nums = [1,7,4,9,2,5] + * Output: 6 + * Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). + * + * Example 2: + * + * Input: nums = [1,17,5,10,13,15,10,5,16,8] + * Output: 7 + * Explanation: There are several subsequences that achieve this length. + * One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8). + * + * Example 3: + * + * Input: nums = [1,2,3,4,5,6,7,8,9] + * Output: 2 + * + * + * Constraints: + * + * 1 <= nums.length <= 1000 + * 0 <= nums[i] <= 1000 + * + * + * Follow up: Could you solve this in O(n) time? + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/wiggle-subsequence/ +// discuss: https://leetcode.com/problems/wiggle-subsequence/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn wiggle_max_length(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_376() { + } +} diff --git a/src/problem/p0380_insert_delete_getrandom_o1.rs b/src/problem/p0380_insert_delete_getrandom_o1.rs new file mode 100644 index 00000000..2febd266 --- /dev/null +++ b/src/problem/p0380_insert_delete_getrandom_o1.rs @@ -0,0 +1,90 @@ +/** + * [380] Insert Delete GetRandom O(1) + * + * Implement the RandomizedSet class: + * + * RandomizedSet() Initializes the RandomizedSet object. + * bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. + * bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise. + * int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned. + * + * You must implement the functions of the class such that each function works in average O(1) time complexity. + * + * Example 1: + * + * Input + * ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] + * [[], [1], [2], [2], [], [1], [2], []] + * Output + * [null, true, false, true, 2, true, false, 2] + * Explanation + * RandomizedSet randomizedSet = new RandomizedSet(); + * randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. + * randomizedSet.remove(2); // Returns false as 2 does not exist in the set. + * randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. + * randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. + * randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. + * randomizedSet.insert(2); // 2 was already in the set, so return false. + * randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. + * + * + * Constraints: + * + * -2^31 <= val <= 2^31 - 1 + * At most 2 * 10^5 calls will be made to insert, remove, and getRandom. + * There will be at least one element in the data structure when getRandom is called. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/insert-delete-getrandom-o1/ +// discuss: https://leetcode.com/problems/insert-delete-getrandom-o1/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct RandomizedSet { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl RandomizedSet { + + fn new() -> Self { + + } + + fn insert(&self, val: i32) -> bool { + + } + + fn remove(&self, val: i32) -> bool { + + } + + fn get_random(&self) -> i32 { + + } +} + +/** + * Your RandomizedSet object will be instantiated and called as such: + * let obj = RandomizedSet::new(); + * let ret_1: bool = obj.insert(val); + * let ret_2: bool = obj.remove(val); + * let ret_3: i32 = obj.get_random(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_380() { + } +} diff --git a/src/problem/p0381_insert_delete_getrandom_o1_duplicates_allowed.rs b/src/problem/p0381_insert_delete_getrandom_o1_duplicates_allowed.rs new file mode 100644 index 00000000..e3cc1271 --- /dev/null +++ b/src/problem/p0381_insert_delete_getrandom_o1_duplicates_allowed.rs @@ -0,0 +1,97 @@ +/** + * [381] Insert Delete GetRandom O(1) - Duplicates allowed + * + * RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element. + * Implement the RandomizedCollection class: + * + * RandomizedCollection() Initializes the empty RandomizedCollection object. + * bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise. + * bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them. + * int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of same values the multiset contains. + * + * You must implement the functions of the class such that each function works on average O(1) time complexity. + * Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection. + * + * Example 1: + * + * Input + * ["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] + * [[], [1], [1], [2], [], [1], []] + * Output + * [null, true, false, true, 2, true, 1] + * Explanation + * RandomizedCollection randomizedCollection = new RandomizedCollection(); + * randomizedCollection.insert(1); // return true since the collection does not contain 1. + * // Inserts 1 into the collection. + * randomizedCollection.insert(1); // return false since the collection contains 1. + * // Inserts another 1 into the collection. Collection now contains [1,1]. + * randomizedCollection.insert(2); // return true since the collection does not contain 2. + * // Inserts 2 into the collection. Collection now contains [1,1,2]. + * randomizedCollection.getRandom(); // getRandom should: + * // - return 1 with probability 2/3, or + * // - return 2 with probability 1/3. + * randomizedCollection.remove(1); // return true since the collection contains 1. + * // Removes 1 from the collection. Collection now contains [1,2]. + * randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely. + * + * + * Constraints: + * + * -2^31 <= val <= 2^31 - 1 + * At most 2 * 10^5 calls in total will be made to insert, remove, and getRandom. + * There will be at least one element in the data structure when getRandom is called. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/ +// discuss: https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct RandomizedCollection { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl RandomizedCollection { + + fn new() -> Self { + + } + + fn insert(&self, val: i32) -> bool { + + } + + fn remove(&self, val: i32) -> bool { + + } + + fn get_random(&self) -> i32 { + + } +} + +/** + * Your RandomizedCollection object will be instantiated and called as such: + * let obj = RandomizedCollection::new(); + * let ret_1: bool = obj.insert(val); + * let ret_2: bool = obj.remove(val); + * let ret_3: i32 = obj.get_random(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_381() { + } +} diff --git a/src/problem/p0384_shuffle_an_array.rs b/src/problem/p0384_shuffle_an_array.rs new file mode 100644 index 00000000..66755cf6 --- /dev/null +++ b/src/problem/p0384_shuffle_an_array.rs @@ -0,0 +1,83 @@ +/** + * [384] Shuffle an Array + * + * Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. + * Implement the Solution class: + * + * Solution(int[] nums) Initializes the object with the integer array nums. + * int[] reset() Resets the array to its original configuration and returns it. + * int[] shuffle() Returns a random shuffling of the array. + * + * + * Example 1: + * + * Input + * ["Solution", "shuffle", "reset", "shuffle"] + * [[[1, 2, 3]], [], [], []] + * Output + * [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] + * Explanation + * Solution solution = new Solution([1, 2, 3]); + * solution.shuffle(); // Shuffle the array [1,2,3] and return its result. + * // Any permutation of [1,2,3] must be equally likely to be returned. + * // Example: return [3, 1, 2] + * solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] + * solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] + * + * + * Constraints: + * + * 1 <= nums.length <= 50 + * -10^6 <= nums[i] <= 10^6 + * All the elements of nums are unique. + * At most 10^4 calls in total will be made to reset and shuffle. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/shuffle-an-array/ +// discuss: https://leetcode.com/problems/shuffle-an-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct Solution { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl Solution { + + fn new(nums: Vec) -> Self { + + } + + fn reset(&self) -> Vec { + + } + + fn shuffle(&self) -> Vec { + + } +} + +/** + * Your Solution object will be instantiated and called as such: + * let obj = Solution::new(nums); + * let ret_1: Vec = obj.reset(); + * let ret_2: Vec = obj.shuffle(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_384() { + } +} diff --git a/src/problem/p0385_mini_parser.rs b/src/problem/p0385_mini_parser.rs new file mode 100644 index 00000000..e08caf8c --- /dev/null +++ b/src/problem/p0385_mini_parser.rs @@ -0,0 +1,60 @@ +/** + * [385] Mini Parser + * + * Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger. + * Each element is either an integer or a list whose elements may also be integers or other lists. + * + * Example 1: + * + * Input: s = "324" + * Output: 324 + * Explanation: You should return a NestedInteger object which contains a single integer 324. + * + * Example 2: + * + * Input: s = "[123,[456,[789]]]" + * Output: [123,[456,[789]]] + * Explanation: Return a NestedInteger object containing a nested list with 2 elements: + * 1. An integer containing value 123. + * 2. A nested list containing two elements: + * i. An integer containing value 456. + * ii. A nested list with one element: + * a. An integer containing value 789 + * + * + * Constraints: + * + * 1 <= s.length <= 5 * 10^4 + * s consists of digits, square brackets "[]", negative sign '-', and commas ','. + * s is the serialization of valid NestedInteger. + * All the values in the input are in the range [-10^6, 10^6]. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/mini-parser/ +// discuss: https://leetcode.com/problems/mini-parser/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// #[derive(Debug, PartialEq, Eq)] +// pub enum NestedInteger { +// Int(i32), +// List(Vec) +// } +impl Solution { + pub fn deserialize(s: String) -> NestedInteger { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_385() { + } +} diff --git a/src/problem/p0386_lexicographical_numbers.rs b/src/problem/p0386_lexicographical_numbers.rs new file mode 100644 index 00000000..969e2916 --- /dev/null +++ b/src/problem/p0386_lexicographical_numbers.rs @@ -0,0 +1,41 @@ +/** + * [386] Lexicographical Numbers + * + * Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order. + * You must write an algorithm that runs in O(n) time and uses O(1) extra space. + * + * Example 1: + * Input: n = 13 + * Output: [1,10,11,12,13,2,3,4,5,6,7,8,9] + * Example 2: + * Input: n = 2 + * Output: [1,2] + * + * Constraints: + * + * 1 <= n <= 5 * 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/lexicographical-numbers/ +// discuss: https://leetcode.com/problems/lexicographical-numbers/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn lexical_order(n: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_386() { + } +} diff --git a/src/problem/p0389_find_the_difference.rs b/src/problem/p0389_find_the_difference.rs new file mode 100644 index 00000000..4db06954 --- /dev/null +++ b/src/problem/p0389_find_the_difference.rs @@ -0,0 +1,49 @@ +/** + * [389] Find the Difference + * + * You are given two strings s and t. + * String t is generated by random shuffling string s and then add one more letter at a random position. + * Return the letter that was added to t. + * + * Example 1: + * + * Input: s = "abcd", t = "abcde" + * Output: "e" + * Explanation: 'e' is the letter that was added. + * + * Example 2: + * + * Input: s = "", t = "y" + * Output: "y" + * + * + * Constraints: + * + * 0 <= s.length <= 1000 + * t.length == s.length + 1 + * s and t consist of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-the-difference/ +// discuss: https://leetcode.com/problems/find-the-difference/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_the_difference(s: String, t: String) -> char { + '0' + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_389() { + } +} diff --git a/src/problem/p0391_perfect_rectangle.rs b/src/problem/p0391_perfect_rectangle.rs new file mode 100644 index 00000000..2bf2d210 --- /dev/null +++ b/src/problem/p0391_perfect_rectangle.rs @@ -0,0 +1,55 @@ +/** + * [391] Perfect Rectangle + * + * Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi). + * Return true if all the rectangles together form an exact cover of a rectangular region. + * + * Example 1: + * + * Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] + * Output: true + * Explanation: All 5 rectangles together form an exact cover of a rectangular region. + * + * Example 2: + * + * Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]] + * Output: false + * Explanation: Because there is a gap between the two rectangular regions. + * + * Example 3: + * + * Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]] + * Output: false + * Explanation: Because two of the rectangles overlap with each other. + * + * + * Constraints: + * + * 1 <= rectangles.length <= 2 * 10^4 + * rectangles[i].length == 4 + * -10^5 <= xi, yi, ai, bi <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/perfect-rectangle/ +// discuss: https://leetcode.com/problems/perfect-rectangle/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_rectangle_cover(rectangles: Vec>) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_391() { + } +} diff --git a/src/problem/p0400_nth_digit.rs b/src/problem/p0400_nth_digit.rs new file mode 100644 index 00000000..724995e9 --- /dev/null +++ b/src/problem/p0400_nth_digit.rs @@ -0,0 +1,45 @@ +/** + * [400] Nth Digit + * + * Given an integer n, return the n^th digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]. + * + * Example 1: + * + * Input: n = 3 + * Output: 3 + * + * Example 2: + * + * Input: n = 11 + * Output: 0 + * Explanation: The 11^th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. + * + * + * Constraints: + * + * 1 <= n <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/nth-digit/ +// discuss: https://leetcode.com/problems/nth-digit/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_nth_digit(n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_400() { + } +} diff --git a/src/problem/p0401_binary_watch.rs b/src/problem/p0401_binary_watch.rs new file mode 100644 index 00000000..9a6bada6 --- /dev/null +++ b/src/problem/p0401_binary_watch.rs @@ -0,0 +1,53 @@ +/** + * [401] Binary Watch + * + * A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. + * + * For example, the below binary watch reads "4:51". + * + * + * Given an integer turnedOn which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent. You may return the answer in any order. + * The hour must not contain a leading zero. + * + * For example, "01:00" is not valid. It should be "1:00". + * + * The minute must be consist of two digits and may contain a leading zero. + * + * For example, "10:2" is not valid. It should be "10:02". + * + * + * Example 1: + * Input: turnedOn = 1 + * Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] + * Example 2: + * Input: turnedOn = 9 + * Output: [] + * + * Constraints: + * + * 0 <= turnedOn <= 10 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/binary-watch/ +// discuss: https://leetcode.com/problems/binary-watch/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn read_binary_watch(turned_on: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_401() { + } +} diff --git a/src/problem/p0404_sum_of_left_leaves.rs b/src/problem/p0404_sum_of_left_leaves.rs new file mode 100644 index 00000000..289ea2f5 --- /dev/null +++ b/src/problem/p0404_sum_of_left_leaves.rs @@ -0,0 +1,68 @@ +/** + * [404] Sum of Left Leaves + * + * Given the root of a binary tree, return the sum of all left leaves. + * A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. + * + * Example 1: + * + * Input: root = [3,9,20,null,null,15,7] + * Output: 24 + * Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively. + * + * Example 2: + * + * Input: root = [1] + * Output: 0 + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 1000]. + * -1000 <= Node.val <= 1000 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/sum-of-left-leaves/ +// discuss: https://leetcode.com/problems/sum-of-left-leaves/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn sum_of_left_leaves(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_404() { + } +} diff --git a/src/problem/p0407_trapping_rain_water_ii.rs b/src/problem/p0407_trapping_rain_water_ii.rs new file mode 100644 index 00000000..dab57919 --- /dev/null +++ b/src/problem/p0407_trapping_rain_water_ii.rs @@ -0,0 +1,50 @@ +/** + * [407] Trapping Rain Water II + * + * Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining. + * + * Example 1: + * + * Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] + * Output: 4 + * Explanation: After the rain, water is trapped between the blocks. + * We have two small ponds 1 and 3 units trapped. + * The total volume of water trapped is 4. + * + * Example 2: + * + * Input: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]] + * Output: 10 + * + * + * Constraints: + * + * m == heightMap.length + * n == heightMap[i].length + * 1 <= m, n <= 200 + * 0 <= heightMap[i][j] <= 2 * 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/trapping-rain-water-ii/ +// discuss: https://leetcode.com/problems/trapping-rain-water-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn trap_rain_water(height_map: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_407() { + } +} diff --git a/src/problem/p0409_longest_palindrome.rs b/src/problem/p0409_longest_palindrome.rs new file mode 100644 index 00000000..13409b0a --- /dev/null +++ b/src/problem/p0409_longest_palindrome.rs @@ -0,0 +1,48 @@ +/** + * [409] Longest Palindrome + * + * Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. + * Letters are case sensitive, for example, "Aa" is not considered a palindrome here. + * + * Example 1: + * + * Input: s = "abccccdd" + * Output: 7 + * Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. + * + * Example 2: + * + * Input: s = "a" + * Output: 1 + * Explanation: The longest palindrome that can be built is "a", whose length is 1. + * + * + * Constraints: + * + * 1 <= s.length <= 2000 + * s consists of lowercase and/or uppercase English letters only. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-palindrome/ +// discuss: https://leetcode.com/problems/longest-palindrome/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn longest_palindrome(s: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_409() { + } +} diff --git a/src/problem/p0415_add_strings.rs b/src/problem/p0415_add_strings.rs new file mode 100644 index 00000000..de2bb71b --- /dev/null +++ b/src/problem/p0415_add_strings.rs @@ -0,0 +1,52 @@ +/** + * [415] Add Strings + * + * Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. + * You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. + * + * Example 1: + * + * Input: num1 = "11", num2 = "123" + * Output: "134" + * + * Example 2: + * + * Input: num1 = "456", num2 = "77" + * Output: "533" + * + * Example 3: + * + * Input: num1 = "0", num2 = "0" + * Output: "0" + * + * + * Constraints: + * + * 1 <= num1.length, num2.length <= 10^4 + * num1 and num2 consist of only digits. + * num1 and num2 don't have any leading zeros except for the zero itself. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/add-strings/ +// discuss: https://leetcode.com/problems/add-strings/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn add_strings(num1: String, num2: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_415() { + } +} diff --git a/src/problem/p0416_partition_equal_subset_sum.rs b/src/problem/p0416_partition_equal_subset_sum.rs new file mode 100644 index 00000000..a13fcfbf --- /dev/null +++ b/src/problem/p0416_partition_equal_subset_sum.rs @@ -0,0 +1,47 @@ +/** + * [416] Partition Equal Subset Sum + * + * Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. + * + * Example 1: + * + * Input: nums = [1,5,11,5] + * Output: true + * Explanation: The array can be partitioned as [1, 5, 5] and [11]. + * + * Example 2: + * + * Input: nums = [1,2,3,5] + * Output: false + * Explanation: The array cannot be partitioned into equal sum subsets. + * + * + * Constraints: + * + * 1 <= nums.length <= 200 + * 1 <= nums[i] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/partition-equal-subset-sum/ +// discuss: https://leetcode.com/problems/partition-equal-subset-sum/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn can_partition(nums: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_416() { + } +} diff --git a/src/problem/p0417_pacific_atlantic_water_flow.rs b/src/problem/p0417_pacific_atlantic_water_flow.rs new file mode 100644 index 00000000..860ce5ae --- /dev/null +++ b/src/problem/p0417_pacific_atlantic_water_flow.rs @@ -0,0 +1,50 @@ +/** + * [417] Pacific Atlantic Water Flow + * + * There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. + * The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c). + * The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. + * Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans. + * + * Example 1: + * + * Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] + * Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] + * + * Example 2: + * + * Input: heights = [[2,1],[1,2]] + * Output: [[0,0],[0,1],[1,0],[1,1]] + * + * + * Constraints: + * + * m == heights.length + * n == heights[r].length + * 1 <= m, n <= 200 + * 0 <= heights[r][c] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/pacific-atlantic-water-flow/ +// discuss: https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn pacific_atlantic(heights: Vec>) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_417() { + } +} diff --git a/src/problem/p0419_battleships_in_a_board.rs b/src/problem/p0419_battleships_in_a_board.rs new file mode 100644 index 00000000..5e3ced88 --- /dev/null +++ b/src/problem/p0419_battleships_in_a_board.rs @@ -0,0 +1,51 @@ +/** + * [419] Battleships in a Board + * + * Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board. + * Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). + * + * Example 1: + * + * Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]] + * Output: 2 + * + * Example 2: + * + * Input: board = [["."]] + * Output: 0 + * + * + * Constraints: + * + * m == board.length + * n == board[i].length + * 1 <= m, n <= 200 + * board[i][j] is either '.' or 'X'. + * + * + * Follow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board? + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/battleships-in-a-board/ +// discuss: https://leetcode.com/problems/battleships-in-a-board/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_battleships(board: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_419() { + } +} diff --git a/src/problem/p0420_strong_password_checker.rs b/src/problem/p0420_strong_password_checker.rs new file mode 100644 index 00000000..7c69fbc7 --- /dev/null +++ b/src/problem/p0420_strong_password_checker.rs @@ -0,0 +1,56 @@ +/** + * [420] Strong Password Checker + * + * A password is considered strong if the below conditions are all met: + * + * It has at least 6 characters and at most 20 characters. + * It contains at least one lowercase letter, at least one uppercase letter, and at least one digit. + * It does not contain three repeating characters in a row (i.e., "...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met). + * + * Given a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0. + * In one step, you can: + * + * Insert one character to password, + * Delete one character from password, or + * Replace one character of password with another character. + * + * + * Example 1: + * Input: password = "a" + * Output: 5 + * Example 2: + * Input: password = "aA1" + * Output: 3 + * Example 3: + * Input: password = "1337C0d3" + * Output: 0 + * + * Constraints: + * + * 1 <= password.length <= 50 + * password consists of letters, digits, dot '.' or exclamation mark '!'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/strong-password-checker/ +// discuss: https://leetcode.com/problems/strong-password-checker/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn strong_password_checker(password: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_420() { + } +} diff --git a/src/problem/p0421_maximum_xor_of_two_numbers_in_an_array.rs b/src/problem/p0421_maximum_xor_of_two_numbers_in_an_array.rs new file mode 100644 index 00000000..fe52ffb2 --- /dev/null +++ b/src/problem/p0421_maximum_xor_of_two_numbers_in_an_array.rs @@ -0,0 +1,46 @@ +/** + * [421] Maximum XOR of Two Numbers in an Array + * + * Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n. + * + * Example 1: + * + * Input: nums = [3,10,5,25,2,8] + * Output: 28 + * Explanation: The maximum result is 5 XOR 25 = 28. + * + * Example 2: + * + * Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70] + * Output: 127 + * + * + * Constraints: + * + * 1 <= nums.length <= 2 * 10^5 + * 0 <= nums[i] <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/ +// discuss: https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_maximum_xor(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_421() { + } +} diff --git a/src/problem/p0423_reconstruct_original_digits_from_english.rs b/src/problem/p0423_reconstruct_original_digits_from_english.rs new file mode 100644 index 00000000..83c75233 --- /dev/null +++ b/src/problem/p0423_reconstruct_original_digits_from_english.rs @@ -0,0 +1,42 @@ +/** + * [423] Reconstruct Original Digits from English + * + * Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order. + * + * Example 1: + * Input: s = "owoztneoer" + * Output: "012" + * Example 2: + * Input: s = "fviefuro" + * Output: "45" + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s[i] is one of the characters ["e","g","f","i","h","o","n","s","r","u","t","w","v","x","z"]. + * s is guaranteed to be valid. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/reconstruct-original-digits-from-english/ +// discuss: https://leetcode.com/problems/reconstruct-original-digits-from-english/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn original_digits(s: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_423() { + } +} diff --git a/src/problem/p0424_longest_repeating_character_replacement.rs b/src/problem/p0424_longest_repeating_character_replacement.rs new file mode 100644 index 00000000..fba97be0 --- /dev/null +++ b/src/problem/p0424_longest_repeating_character_replacement.rs @@ -0,0 +1,50 @@ +/** + * [424] Longest Repeating Character Replacement + * + * You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. + * Return the length of the longest substring containing the same letter you can get after performing the above operations. + * + * Example 1: + * + * Input: s = "ABAB", k = 2 + * Output: 4 + * Explanation: Replace the two 'A's with two 'B's or vice versa. + * + * Example 2: + * + * Input: s = "AABABBA", k = 1 + * Output: 4 + * Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". + * The substring "BBBB" has the longest repeating letters, which is 4. + * + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s consists of only uppercase English letters. + * 0 <= k <= s.length + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-repeating-character-replacement/ +// discuss: https://leetcode.com/problems/longest-repeating-character-replacement/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn character_replacement(s: String, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_424() { + } +} diff --git a/src/problem/p0432_all_oone_data_structure.rs b/src/problem/p0432_all_oone_data_structure.rs new file mode 100644 index 00000000..9ec2cd55 --- /dev/null +++ b/src/problem/p0432_all_oone_data_structure.rs @@ -0,0 +1,98 @@ +/** + * [432] All O`one Data Structure + * + * Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. + * Implement the AllOne class: + * + * AllOne() Initializes the object of the data structure. + * inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, insert it with count 1. + * dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement. + * getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string "". + * getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string "". + * + * Note that each function must run in O(1) average time complexity. + * + * Example 1: + * + * Input + * ["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"] + * [[], ["hello"], ["hello"], [], [], ["leet"], [], []] + * Output + * [null, null, null, "hello", "hello", null, "hello", "leet"] + * Explanation + * AllOne allOne = new AllOne(); + * allOne.inc("hello"); + * allOne.inc("hello"); + * allOne.getMaxKey(); // return "hello" + * allOne.getMinKey(); // return "hello" + * allOne.inc("leet"); + * allOne.getMaxKey(); // return "hello" + * allOne.getMinKey(); // return "leet" + * + * + * Constraints: + * + * 1 <= key.length <= 10 + * key consists of lowercase English letters. + * It is guaranteed that for each call to dec, key is existing in the data structure. + * At most 5 * 10^4 calls will be made to inc, dec, getMaxKey, and getMinKey. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/all-oone-data-structure/ +// discuss: https://leetcode.com/problems/all-oone-data-structure/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct AllOne { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl AllOne { + + fn new() -> Self { + + } + + fn inc(&self, key: String) { + + } + + fn dec(&self, key: String) { + + } + + fn get_max_key(&self) -> String { + + } + + fn get_min_key(&self) -> String { + + } +} + +/** + * Your AllOne object will be instantiated and called as such: + * let obj = AllOne::new(); + * obj.inc(key); + * obj.dec(key); + * let ret_3: String = obj.get_max_key(); + * let ret_4: String = obj.get_min_key(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_432() { + } +} diff --git a/src/problem/p0435_non_overlapping_intervals.rs b/src/problem/p0435_non_overlapping_intervals.rs new file mode 100644 index 00000000..3112d3e3 --- /dev/null +++ b/src/problem/p0435_non_overlapping_intervals.rs @@ -0,0 +1,54 @@ +/** + * [435] Non-overlapping Intervals + * + * Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. + * + * Example 1: + * + * Input: intervals = [[1,2],[2,3],[3,4],[1,3]] + * Output: 1 + * Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping. + * + * Example 2: + * + * Input: intervals = [[1,2],[1,2],[1,2]] + * Output: 2 + * Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping. + * + * Example 3: + * + * Input: intervals = [[1,2],[2,3]] + * Output: 0 + * Explanation: You don't need to remove any of the intervals since they're already non-overlapping. + * + * + * Constraints: + * + * 1 <= intervals.length <= 10^5 + * intervals[i].length == 2 + * -5 * 10^4 <= starti < endi <= 5 * 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/non-overlapping-intervals/ +// discuss: https://leetcode.com/problems/non-overlapping-intervals/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn erase_overlap_intervals(intervals: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_435() { + } +} diff --git a/src/problem/p0441_arranging_coins.rs b/src/problem/p0441_arranging_coins.rs new file mode 100644 index 00000000..f15315cf --- /dev/null +++ b/src/problem/p0441_arranging_coins.rs @@ -0,0 +1,47 @@ +/** + * [441] Arranging Coins + * + * You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the i^th row has exactly i coins. The last row of the staircase may be incomplete. + * Given the integer n, return the number of complete rows of the staircase you will build. + * + * Example 1: + * + * Input: n = 5 + * Output: 2 + * Explanation: Because the 3^rd row is incomplete, we return 2. + * + * Example 2: + * + * Input: n = 8 + * Output: 3 + * Explanation: Because the 4^th row is incomplete, we return 3. + * + * + * Constraints: + * + * 1 <= n <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/arranging-coins/ +// discuss: https://leetcode.com/problems/arranging-coins/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn arrange_coins(n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_441() { + } +} diff --git a/src/problem/p0450_delete_node_in_a_bst.rs b/src/problem/p0450_delete_node_in_a_bst.rs new file mode 100644 index 00000000..748d6e54 --- /dev/null +++ b/src/problem/p0450_delete_node_in_a_bst.rs @@ -0,0 +1,87 @@ +/** + * [450] Delete Node in a BST + * + * Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. + * Basically, the deletion can be divided into two stages: + *
    + * Search for a node to remove. + * If the node is found, delete the node. + *
+ * + * Example 1: + * + * Input: root = [5,3,6,2,4,null,7], key = 3 + * Output: [5,4,6,2,null,null,7] + * Explanation: Given key to delete is 3. So we find the node with value 3 and delete it. + * One valid answer is [5,4,6,2,null,null,7], shown in the above BST. + * Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted. + * + * + * Example 2: + * + * Input: root = [5,3,6,2,4,null,7], key = 0 + * Output: [5,3,6,2,4,null,7] + * Explanation: The tree does not contain a node with value = 0. + * + * Example 3: + * + * Input: root = [], key = 0 + * Output: [] + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 10^4]. + * -10^5 <= Node.val <= 10^5 + * Each node has a unique value. + * root is a valid binary search tree. + * -10^5 <= key <= 10^5 + * + * + * Follow up: Could you solve it with time complexity O(height of tree)? + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/delete-node-in-a-bst/ +// discuss: https://leetcode.com/problems/delete-node-in-a-bst/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn delete_node(root: Option>>, key: i32) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_450() { + } +} diff --git a/src/problem/p0452_minimum_number_of_arrows_to_burst_balloons.rs b/src/problem/p0452_minimum_number_of_arrows_to_burst_balloons.rs new file mode 100644 index 00000000..e54e0462 --- /dev/null +++ b/src/problem/p0452_minimum_number_of_arrows_to_burst_balloons.rs @@ -0,0 +1,60 @@ +/** + * [452] Minimum Number of Arrows to Burst Balloons + * + * There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. + * Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. + * Given the array points, return the minimum number of arrows that must be shot to burst all balloons. + * + * Example 1: + * + * Input: points = [[10,16],[2,8],[1,6],[7,12]] + * Output: 2 + * Explanation: The balloons can be burst by 2 arrows: + * - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. + * - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. + * + * Example 2: + * + * Input: points = [[1,2],[3,4],[5,6],[7,8]] + * Output: 4 + * Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows. + * + * Example 3: + * + * Input: points = [[1,2],[2,3],[3,4],[4,5]] + * Output: 2 + * Explanation: The balloons can be burst by 2 arrows: + * - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. + * - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. + * + * + * Constraints: + * + * 1 <= points.length <= 10^5 + * points[i].length == 2 + * -2^31 <= xstart < xend <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/ +// discuss: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_min_arrow_shots(points: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_452() { + } +} diff --git a/src/problem/p0456_132_pattern.rs b/src/problem/p0456_132_pattern.rs new file mode 100644 index 00000000..64a5d258 --- /dev/null +++ b/src/problem/p0456_132_pattern.rs @@ -0,0 +1,55 @@ +/** + * [456] 132 Pattern + * + * Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. + * Return true if there is a 132 pattern in nums, otherwise, return false. + * + * Example 1: + * + * Input: nums = [1,2,3,4] + * Output: false + * Explanation: There is no 132 pattern in the sequence. + * + * Example 2: + * + * Input: nums = [3,1,4,2] + * Output: true + * Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. + * + * Example 3: + * + * Input: nums = [-1,3,2,0] + * Output: true + * Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. + * + * + * Constraints: + * + * n == nums.length + * 1 <= n <= 2 * 10^5 + * -10^9 <= nums[i] <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/132-pattern/ +// discuss: https://leetcode.com/problems/132-pattern/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find132pattern(nums: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_456() { + } +} diff --git a/src/problem/p0458_poor_pigs.rs b/src/problem/p0458_poor_pigs.rs new file mode 100644 index 00000000..575e4577 --- /dev/null +++ b/src/problem/p0458_poor_pigs.rs @@ -0,0 +1,53 @@ +/** + * [458] Poor Pigs + * + * There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous. + * You can feed the pigs according to these steps: + *
    + * Choose some live pigs to feed. + * For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. + * Wait for minutesToDie minutes. You may not feed any other pigs during this time. + * After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive. + * Repeat this process until you run out of time. + *
+ * Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time. + * + * Example 1: + * Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60 + * Output: 5 + * Example 2: + * Input: buckets = 4, minutesToDie = 15, minutesToTest = 15 + * Output: 2 + * Example 3: + * Input: buckets = 4, minutesToDie = 15, minutesToTest = 30 + * Output: 2 + * + * Constraints: + * + * 1 <= buckets <= 1000 + * 1 <= minutesToDie <= minutesToTest <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/poor-pigs/ +// discuss: https://leetcode.com/problems/poor-pigs/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn poor_pigs(buckets: i32, minutes_to_die: i32, minutes_to_test: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_458() { + } +} diff --git a/src/problem/p0461_hamming_distance.rs b/src/problem/p0461_hamming_distance.rs new file mode 100644 index 00000000..43f4e667 --- /dev/null +++ b/src/problem/p0461_hamming_distance.rs @@ -0,0 +1,50 @@ +/** + * [461] Hamming Distance + * + * The Hamming distance between two integers is the number of positions at which the corresponding bits are different. + * Given two integers x and y, return the Hamming distance between them. + * + * Example 1: + * + * Input: x = 1, y = 4 + * Output: 2 + * Explanation: + * 1 (0 0 0 1) + * 4 (0 1 0 0) + * ↑ ↑ + * The above arrows point to positions where the corresponding bits are different. + * + * Example 2: + * + * Input: x = 3, y = 1 + * Output: 1 + * + * + * Constraints: + * + * 0 <= x, y <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/hamming-distance/ +// discuss: https://leetcode.com/problems/hamming-distance/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn hamming_distance(x: i32, y: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_461() { + } +} diff --git a/src/problem/p0462_minimum_moves_to_equal_array_elements_ii.rs b/src/problem/p0462_minimum_moves_to_equal_array_elements_ii.rs new file mode 100644 index 00000000..364fba86 --- /dev/null +++ b/src/problem/p0462_minimum_moves_to_equal_array_elements_ii.rs @@ -0,0 +1,51 @@ +/** + * [462] Minimum Moves to Equal Array Elements II + * + * Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. + * In one move, you can increment or decrement an element of the array by 1. + * Test cases are designed so that the answer will fit in a 32-bit integer. + * + * Example 1: + * + * Input: nums = [1,2,3] + * Output: 2 + * Explanation: + * Only two moves are needed (remember each move increments or decrements one element): + * [1,2,3] => [2,2,3] => [2,2,2] + * + * Example 2: + * + * Input: nums = [1,10,2,9] + * Output: 16 + * + * + * Constraints: + * + * n == nums.length + * 1 <= nums.length <= 10^5 + * -10^9 <= nums[i] <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ +// discuss: https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_moves2(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_462() { + } +} diff --git a/src/problem/p0464_can_i_win.rs b/src/problem/p0464_can_i_win.rs new file mode 100644 index 00000000..270d79ef --- /dev/null +++ b/src/problem/p0464_can_i_win.rs @@ -0,0 +1,59 @@ +/** + * [464] Can I Win + * + * In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins. + * What if we change the game so that players cannot re-use integers? + * For example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100. + * Given two integers maxChoosableInteger and desiredTotal, return true if the first player to move can force a win, otherwise, return false. Assume both players play optimally. + * + * Example 1: + * + * Input: maxChoosableInteger = 10, desiredTotal = 11 + * Output: false + * Explanation: + * No matter which integer the first player choose, the first player will lose. + * The first player can choose an integer from 1 up to 10. + * If the first player choose 1, the second player can only choose integers from 2 up to 10. + * The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal. + * Same with other integers chosen by the first player, the second player will always win. + * + * Example 2: + * + * Input: maxChoosableInteger = 10, desiredTotal = 0 + * Output: true + * + * Example 3: + * + * Input: maxChoosableInteger = 10, desiredTotal = 1 + * Output: true + * + * + * Constraints: + * + * 1 <= maxChoosableInteger <= 20 + * 0 <= desiredTotal <= 300 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/can-i-win/ +// discuss: https://leetcode.com/problems/can-i-win/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn can_i_win(max_choosable_integer: i32, desired_total: i32) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_464() { + } +} diff --git a/src/problem/p0467_unique_substrings_in_wraparound_string.rs b/src/problem/p0467_unique_substrings_in_wraparound_string.rs new file mode 100644 index 00000000..2c145d41 --- /dev/null +++ b/src/problem/p0467_unique_substrings_in_wraparound_string.rs @@ -0,0 +1,57 @@ +/** + * [467] Unique Substrings in Wraparound String + * + * We define the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this: + * + * "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". + * + * Given a string p, return the number of unique non-empty substrings of p are present in s. + * + * Example 1: + * + * Input: p = "a" + * Output: 1 + * Explanation: Only the substring "a" of p is in s. + * + * Example 2: + * + * Input: p = "cac" + * Output: 2 + * Explanation: There are two substrings ("a", "c") of p in s. + * + * Example 3: + * + * Input: p = "zab" + * Output: 6 + * Explanation: There are six substrings ("z", "a", "b", "za", "ab", and "zab") of p in s. + * + * + * Constraints: + * + * 1 <= p.length <= 10^5 + * p consists of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/unique-substrings-in-wraparound-string/ +// discuss: https://leetcode.com/problems/unique-substrings-in-wraparound-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_substring_in_wrapround_string(p: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_467() { + } +} diff --git a/src/problem/p0472_concatenated_words.rs b/src/problem/p0472_concatenated_words.rs new file mode 100644 index 00000000..499c6b1c --- /dev/null +++ b/src/problem/p0472_concatenated_words.rs @@ -0,0 +1,51 @@ +/** + * [472] Concatenated Words + * + * Given an array of strings words (without duplicates), return all the concatenated words in the given list of words. + * A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array. + * + * Example 1: + * + * Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] + * Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] + * Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; + * "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; + * "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat". + * Example 2: + * + * Input: words = ["cat","dog","catdog"] + * Output: ["catdog"] + * + * + * Constraints: + * + * 1 <= words.length <= 10^4 + * 1 <= words[i].length <= 30 + * words[i] consists of only lowercase English letters. + * All the strings of words are unique. + * 1 <= sum(words[i].length) <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/concatenated-words/ +// discuss: https://leetcode.com/problems/concatenated-words/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_all_concatenated_words_in_a_dict(words: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_472() { + } +} diff --git a/src/problem/p0473_matchsticks_to_square.rs b/src/problem/p0473_matchsticks_to_square.rs new file mode 100644 index 00000000..255b9e9c --- /dev/null +++ b/src/problem/p0473_matchsticks_to_square.rs @@ -0,0 +1,48 @@ +/** + * [473] Matchsticks to Square + * + * You are given an integer array matchsticks where matchsticks[i] is the length of the i^th matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. + * Return true if you can make this square and false otherwise. + * + * Example 1: + * + * Input: matchsticks = [1,1,2,2,2] + * Output: true + * Explanation: You can form a square with length 2, one side of the square came two sticks with length 1. + * + * Example 2: + * + * Input: matchsticks = [3,3,3,3,4] + * Output: false + * Explanation: You cannot find a way to form a square with all the matchsticks. + * + * + * Constraints: + * + * 1 <= matchsticks.length <= 15 + * 1 <= matchsticks[i] <= 10^8 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/matchsticks-to-square/ +// discuss: https://leetcode.com/problems/matchsticks-to-square/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn makesquare(matchsticks: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_473() { + } +} diff --git a/src/problem/p0474_ones_and_zeroes.rs b/src/problem/p0474_ones_and_zeroes.rs new file mode 100644 index 00000000..8e06100f --- /dev/null +++ b/src/problem/p0474_ones_and_zeroes.rs @@ -0,0 +1,53 @@ +/** + * [474] Ones and Zeroes + * + * You are given an array of binary strings strs and two integers m and n. + * Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset. + * A set x is a subset of a set y if all elements of x are also elements of y. + * + * Example 1: + * + * Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3 + * Output: 4 + * Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4. + * Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}. + * {"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3. + * + * Example 2: + * + * Input: strs = ["10","0","1"], m = 1, n = 1 + * Output: 2 + * Explanation: The largest subset is {"0", "1"}, so the answer is 2. + * + * + * Constraints: + * + * 1 <= strs.length <= 600 + * 1 <= strs[i].length <= 100 + * strs[i] consists only of digits '0' and '1'. + * 1 <= m, n <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/ones-and-zeroes/ +// discuss: https://leetcode.com/problems/ones-and-zeroes/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_max_form(strs: Vec, m: i32, n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_474() { + } +} diff --git a/src/problem/p0475_heaters.rs b/src/problem/p0475_heaters.rs new file mode 100644 index 00000000..410e9df3 --- /dev/null +++ b/src/problem/p0475_heaters.rs @@ -0,0 +1,55 @@ +/** + * [475] Heaters + * + * Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. + * Every house can be warmed, as long as the house is within the heater's warm radius range. + * Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. + * Notice that all the heaters follow your radius standard, and the warm radius will the same. + * + * Example 1: + * + * Input: houses = [1,2,3], heaters = [2] + * Output: 1 + * Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. + * + * Example 2: + * + * Input: houses = [1,2,3,4], heaters = [1,4] + * Output: 1 + * Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed. + * + * Example 3: + * + * Input: houses = [1,5], heaters = [2] + * Output: 3 + * + * + * Constraints: + * + * 1 <= houses.length, heaters.length <= 3 * 10^4 + * 1 <= houses[i], heaters[i] <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/heaters/ +// discuss: https://leetcode.com/problems/heaters/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_radius(houses: Vec, heaters: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_475() { + } +} diff --git a/src/problem/p0476_number_complement.rs b/src/problem/p0476_number_complement.rs new file mode 100644 index 00000000..8b60a42a --- /dev/null +++ b/src/problem/p0476_number_complement.rs @@ -0,0 +1,53 @@ +/** + * [476] Number Complement + * + * The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. + * + * For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. + * + * Given an integer num, return its complement. + * + * Example 1: + * + * Input: num = 5 + * Output: 2 + * Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. + * + * Example 2: + * + * Input: num = 1 + * Output: 0 + * Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. + * + * + * Constraints: + * + * 1 <= num < 2^31 + * + * + * Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/ + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-complement/ +// discuss: https://leetcode.com/problems/number-complement/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_complement(num: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_476() { + } +} diff --git a/src/problem/p0477_total_hamming_distance.rs b/src/problem/p0477_total_hamming_distance.rs new file mode 100644 index 00000000..ff102c51 --- /dev/null +++ b/src/problem/p0477_total_hamming_distance.rs @@ -0,0 +1,51 @@ +/** + * [477] Total Hamming Distance + * + * The Hamming distance between two integers is the number of positions at which the corresponding bits are different. + * Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums. + * + * Example 1: + * + * Input: nums = [4,14,2] + * Output: 6 + * Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just + * showing the four bits relevant in this case). + * The answer will be: + * HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. + * + * Example 2: + * + * Input: nums = [4,14,4] + * Output: 4 + * + * + * Constraints: + * + * 1 <= nums.length <= 10^4 + * 0 <= nums[i] <= 10^9 + * The answer for the given input will fit in a 32-bit integer. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/total-hamming-distance/ +// discuss: https://leetcode.com/problems/total-hamming-distance/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn total_hamming_distance(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_477() { + } +} diff --git a/src/problem/p0478_generate_random_point_in_a_circle.rs b/src/problem/p0478_generate_random_point_in_a_circle.rs new file mode 100644 index 00000000..b8e73829 --- /dev/null +++ b/src/problem/p0478_generate_random_point_in_a_circle.rs @@ -0,0 +1,74 @@ +/** + * [478] Generate Random Point in a Circle + * + * Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle. + * Implement the Solution class: + * + * Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center). + * randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y]. + * + * + * Example 1: + * + * Input + * ["Solution", "randPoint", "randPoint", "randPoint"] + * [[1.0, 0.0, 0.0], [], [], []] + * Output + * [null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]] + * Explanation + * Solution solution = new Solution(1.0, 0.0, 0.0); + * solution.randPoint(); // return [-0.02493, -0.38077] + * solution.randPoint(); // return [0.82314, 0.38945] + * solution.randPoint(); // return [0.36572, 0.17248] + * + * + * Constraints: + * + * 0 < radius <= 10^8 + * -10^7 <= x_center, y_center <= 10^7 + * At most 3 * 10^4 calls will be made to randPoint. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/generate-random-point-in-a-circle/ +// discuss: https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct Solution { + vec![] + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl Solution { + + fn new(radius: f64, x_center: f64, y_center: f64) -> Self { + + } + + fn rand_point(&self) -> Vec { + + } +} + +/** + * Your Solution object will be instantiated and called as such: + * let obj = Solution::new(radius, x_center, y_center); + * let ret_1: Vec = obj.rand_point(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_478() { + } +} diff --git a/src/problem/p0480_sliding_window_median.rs b/src/problem/p0480_sliding_window_median.rs new file mode 100644 index 00000000..eb5c2ced --- /dev/null +++ b/src/problem/p0480_sliding_window_median.rs @@ -0,0 +1,60 @@ +/** + * [480] Sliding Window Median + * + * The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. + * + * For examples, if arr = [2,3,4], the median is 3. + * For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5. + * + * You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. + * Return the median array for each window in the original array. Answers within 10^-5 of the actual value will be accepted. + * + * Example 1: + * + * Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 + * Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000] + * Explanation: + * Window position Median + * --------------- ----- + * [1 3 -1] -3 5 3 6 7 1 + * 1 [3 -1 -3] 5 3 6 7 -1 + * 1 3 [-1 -3 5] 3 6 7 -1 + * 1 3 -1 [-3 5 3] 6 7 3 + * 1 3 -1 -3 [5 3 6] 7 5 + * 1 3 -1 -3 5 [3 6 7] 6 + * + * Example 2: + * + * Input: nums = [1,2,3,4,2,3,1,4,2], k = 3 + * Output: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000] + * + * + * Constraints: + * + * 1 <= k <= nums.length <= 10^5 + * -2^31 <= nums[i] <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/sliding-window-median/ +// discuss: https://leetcode.com/problems/sliding-window-median/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn median_sliding_window(nums: Vec, k: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_480() { + } +} diff --git a/src/problem/p0481_magical_string.rs b/src/problem/p0481_magical_string.rs new file mode 100644 index 00000000..40595f08 --- /dev/null +++ b/src/problem/p0481_magical_string.rs @@ -0,0 +1,50 @@ +/** + * [481] Magical String + * + * A magical string s consists of only '1' and '2' and obeys the following rules: + * + * The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself. + * + * The first few elements of s is s = "1221121221221121122……". If we group the consecutive 1's and 2's in s, it will be "1 22 11 2 1 22 1 22 11 2 11 22 ......" and the occurrences of 1's or 2's in each group are "1 2 2 1 1 2 1 2 2 1 2 2 ......". You can see that the occurrence sequence is s itself. + * Given an integer n, return the number of 1's in the first n number in the magical string s. + * + * Example 1: + * + * Input: n = 6 + * Output: 3 + * Explanation: The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3. + * + * Example 2: + * + * Input: n = 1 + * Output: 1 + * + * + * Constraints: + * + * 1 <= n <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/magical-string/ +// discuss: https://leetcode.com/problems/magical-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn magical_string(n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_481() { + } +} diff --git a/src/problem/p0482_license_key_formatting.rs b/src/problem/p0482_license_key_formatting.rs new file mode 100644 index 00000000..20e2537e --- /dev/null +++ b/src/problem/p0482_license_key_formatting.rs @@ -0,0 +1,51 @@ +/** + * [482] License Key Formatting + * + * You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k. + * We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. + * Return the reformatted license key. + * + * Example 1: + * + * Input: s = "5F3Z-2e-9-w", k = 4 + * Output: "5F3Z-2E9W" + * Explanation: The string s has been split into two parts, each part has 4 characters. + * Note that the two extra dashes are not needed and can be removed. + * + * Example 2: + * + * Input: s = "2-5g-3-J", k = 2 + * Output: "2-5G-3J" + * Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. + * + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s consists of English letters, digits, and dashes '-'. + * 1 <= k <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/license-key-formatting/ +// discuss: https://leetcode.com/problems/license-key-formatting/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn license_key_formatting(s: String, k: i32) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_482() { + } +} diff --git a/src/problem/p0483_smallest_good_base.rs b/src/problem/p0483_smallest_good_base.rs new file mode 100644 index 00000000..4886a4a5 --- /dev/null +++ b/src/problem/p0483_smallest_good_base.rs @@ -0,0 +1,54 @@ +/** + * [483] Smallest Good Base + * + * Given an integer n represented as a string, return the smallest good base of n. + * We call k >= 2 a good base of n, if all digits of n base k are 1's. + * + * Example 1: + * + * Input: n = "13" + * Output: "3" + * Explanation: 13 base 3 is 111. + * + * Example 2: + * + * Input: n = "4681" + * Output: "8" + * Explanation: 4681 base 8 is 11111. + * + * Example 3: + * + * Input: n = "1000000000000000000" + * Output: "999999999999999999" + * Explanation: 1000000000000000000 base 999999999999999999 is 11. + * + * + * Constraints: + * + * n is an integer in the range [3, 10^18]. + * n does not contain any leading zeros. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/smallest-good-base/ +// discuss: https://leetcode.com/problems/smallest-good-base/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn smallest_good_base(n: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_483() { + } +} diff --git a/src/problem/p0485_max_consecutive_ones.rs b/src/problem/p0485_max_consecutive_ones.rs new file mode 100644 index 00000000..9323ff98 --- /dev/null +++ b/src/problem/p0485_max_consecutive_ones.rs @@ -0,0 +1,46 @@ +/** + * [485] Max Consecutive Ones + * + * Given a binary array nums, return the maximum number of consecutive 1's in the array. + * + * Example 1: + * + * Input: nums = [1,1,0,1,1,1] + * Output: 3 + * Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. + * + * Example 2: + * + * Input: nums = [1,0,1,1,0,1] + * Output: 2 + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * nums[i] is either 0 or 1. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/max-consecutive-ones/ +// discuss: https://leetcode.com/problems/max-consecutive-ones/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_max_consecutive_ones(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_485() { + } +} diff --git a/src/problem/p0491_increasing_subsequences.rs b/src/problem/p0491_increasing_subsequences.rs new file mode 100644 index 00000000..a86256f9 --- /dev/null +++ b/src/problem/p0491_increasing_subsequences.rs @@ -0,0 +1,46 @@ +/** + * [491] Increasing Subsequences + * + * Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order. + * The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence. + * + * Example 1: + * + * Input: nums = [4,6,7,7] + * Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]] + * + * Example 2: + * + * Input: nums = [4,4,3,2,1] + * Output: [[4,4]] + * + * + * Constraints: + * + * 1 <= nums.length <= 15 + * -100 <= nums[i] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/increasing-subsequences/ +// discuss: https://leetcode.com/problems/increasing-subsequences/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_subsequences(nums: Vec) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_491() { + } +} diff --git a/src/problem/p0496_next_greater_element_i.rs b/src/problem/p0496_next_greater_element_i.rs new file mode 100644 index 00000000..49e3fb58 --- /dev/null +++ b/src/problem/p0496_next_greater_element_i.rs @@ -0,0 +1,59 @@ +/** + * [496] Next Greater Element I + * + * The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. + * You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. + * For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. + * Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. + * + * Example 1: + * + * Input: nums1 = [4,1,2], nums2 = [1,3,4,2] + * Output: [-1,3,-1] + * Explanation: The next greater element for each value of nums1 is as follows: + * - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. + * - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. + * - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. + * + * Example 2: + * + * Input: nums1 = [2,4], nums2 = [1,2,3,4] + * Output: [3,-1] + * Explanation: The next greater element for each value of nums1 is as follows: + * - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. + * - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1. + * + * + * Constraints: + * + * 1 <= nums1.length <= nums2.length <= 1000 + * 0 <= nums1[i], nums2[i] <= 10^4 + * All integers in nums1 and nums2 are unique. + * All the integers of nums1 also appear in nums2. + * + * + * Follow up: Could you find an O(nums1.length + nums2.length) solution? + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/next-greater-element-i/ +// discuss: https://leetcode.com/problems/next-greater-element-i/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn next_greater_element(nums1: Vec, nums2: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_496() { + } +} diff --git a/src/problem/p0500_keyboard_row.rs b/src/problem/p0500_keyboard_row.rs new file mode 100644 index 00000000..b9171842 --- /dev/null +++ b/src/problem/p0500_keyboard_row.rs @@ -0,0 +1,57 @@ +/** + * [500] Keyboard Row + * + * Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below. + * In the American keyboard: + * + * the first row consists of the characters "qwertyuiop", + * the second row consists of the characters "asdfghjkl", and + * the third row consists of the characters "zxcvbnm". + * + * + * Example 1: + * + * Input: words = ["Hello","Alaska","Dad","Peace"] + * Output: ["Alaska","Dad"] + * + * Example 2: + * + * Input: words = ["omk"] + * Output: [] + * + * Example 3: + * + * Input: words = ["adsdf","sfd"] + * Output: ["adsdf","sfd"] + * + * + * Constraints: + * + * 1 <= words.length <= 20 + * 1 <= words[i].length <= 100 + * words[i] consists of English letters (both lowercase and uppercase). + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/keyboard-row/ +// discuss: https://leetcode.com/problems/keyboard-row/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_words(words: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_500() { + } +} diff --git a/src/problem/p0501_find_mode_in_binary_search_tree.rs b/src/problem/p0501_find_mode_in_binary_search_tree.rs new file mode 100644 index 00000000..e2241b5f --- /dev/null +++ b/src/problem/p0501_find_mode_in_binary_search_tree.rs @@ -0,0 +1,75 @@ +/** + * [501] Find Mode in Binary Search Tree + * + * Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it. + * If the tree has more than one mode, return them in any order. + * Assume a BST is defined as follows: + * + * The left subtree of a node contains only nodes with keys less than or equal to the node's key. + * The right subtree of a node contains only nodes with keys greater than or equal to the node's key. + * Both the left and right subtrees must also be binary search trees. + * + * + * Example 1: + * + * Input: root = [1,null,2,2] + * Output: [2] + * + * Example 2: + * + * Input: root = [0] + * Output: [0] + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 10^4]. + * -10^5 <= Node.val <= 10^5 + * + * + * Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count). + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/find-mode-in-binary-search-tree/ +// discuss: https://leetcode.com/problems/find-mode-in-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn find_mode(root: Option>>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_501() { + } +} diff --git a/src/problem/p0515_find_largest_value_in_each_tree_row.rs b/src/problem/p0515_find_largest_value_in_each_tree_row.rs new file mode 100644 index 00000000..cd100e47 --- /dev/null +++ b/src/problem/p0515_find_largest_value_in_each_tree_row.rs @@ -0,0 +1,66 @@ +/** + * [515] Find Largest Value in Each Tree Row + * + * Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed). + * + * Example 1: + * + * Input: root = [1,3,2,5,3,null,9] + * Output: [1,3,9] + * + * Example 2: + * + * Input: root = [1,2,3] + * Output: [1,3] + * + * + * Constraints: + * + * The number of nodes in the tree will be in the range [0, 10^4]. + * -2^31 <= Node.val <= 2^31 - 1 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/find-largest-value-in-each-tree-row/ +// discuss: https://leetcode.com/problems/find-largest-value-in-each-tree-row/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn largest_values(root: Option>>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_515() { + } +} diff --git a/src/problem/p0519_random_flip_matrix.rs b/src/problem/p0519_random_flip_matrix.rs new file mode 100644 index 00000000..02cedc90 --- /dev/null +++ b/src/problem/p0519_random_flip_matrix.rs @@ -0,0 +1,83 @@ +/** + * [519] Random Flip Matrix + * + * There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned. + * Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity. + * Implement the Solution class: + * + * Solution(int m, int n) Initializes the object with the size of the binary matrix m and n. + * int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1. + * void reset() Resets all the values of the matrix to be 0. + * + * + * Example 1: + * + * Input + * ["Solution", "flip", "flip", "flip", "reset", "flip"] + * [[3, 1], [], [], [], [], []] + * Output + * [null, [1, 0], [2, 0], [0, 0], null, [2, 0]] + * Explanation + * Solution solution = new Solution(3, 1); + * solution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned. + * solution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0] + * solution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned. + * solution.reset(); // All the values are reset to 0 and can be returned. + * solution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned. + * + * + * Constraints: + * + * 1 <= m, n <= 10^4 + * There will be at least one free cell for each call to flip. + * At most 1000 calls will be made to flip and reset. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/random-flip-matrix/ +// discuss: https://leetcode.com/problems/random-flip-matrix/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct Solution { + vec![] + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl Solution { + + fn new(m: i32, n: i32) -> Self { + + } + + fn flip(&self) -> Vec { + + } + + fn reset(&self) { + + } +} + +/** + * Your Solution object will be instantiated and called as such: + * let obj = Solution::new(m, n); + * let ret_1: Vec = obj.flip(); + * obj.reset(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_519() { + } +} diff --git a/src/problem/p0524_longest_word_in_dictionary_through_deleting.rs b/src/problem/p0524_longest_word_in_dictionary_through_deleting.rs new file mode 100644 index 00000000..302ed716 --- /dev/null +++ b/src/problem/p0524_longest_word_in_dictionary_through_deleting.rs @@ -0,0 +1,47 @@ +/** + * [524] Longest Word in Dictionary through Deleting + * + * Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. + * + * Example 1: + * + * Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] + * Output: "apple" + * + * Example 2: + * + * Input: s = "abpcplea", dictionary = ["a","b","c"] + * Output: "a" + * + * + * Constraints: + * + * 1 <= s.length <= 1000 + * 1 <= dictionary.length <= 1000 + * 1 <= dictionary[i].length <= 1000 + * s and dictionary[i] consist of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/ +// discuss: https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_longest_word(s: String, dictionary: Vec) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_524() { + } +} diff --git a/src/problem/p0528_random_pick_with_weight.rs b/src/problem/p0528_random_pick_with_weight.rs new file mode 100644 index 00000000..6ccf5eb9 --- /dev/null +++ b/src/problem/p0528_random_pick_with_weight.rs @@ -0,0 +1,95 @@ +/** + * [528] Random Pick with Weight + * + * You are given a 0-indexed array of positive integers w where w[i] describes the weight of the i^th index. + * You need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w). + * + * For example, if w = [1, 3], the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25%), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%). + * + * + * Example 1: + * + * Input + * ["Solution","pickIndex"] + * [[[1]],[]] + * Output + * [null,0] + * Explanation + * Solution solution = new Solution([1]); + * solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. + * + * Example 2: + * + * Input + * ["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"] + * [[[1,3]],[],[],[],[],[]] + * Output + * [null,1,1,1,1,0] + * Explanation + * Solution solution = new Solution([1, 3]); + * solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. + * solution.pickIndex(); // return 1 + * solution.pickIndex(); // return 1 + * solution.pickIndex(); // return 1 + * solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. + * Since this is a randomization problem, multiple answers are allowed. + * All of the following outputs can be considered correct: + * [null,1,1,1,1,0] + * [null,1,1,1,1,1] + * [null,1,1,1,0,0] + * [null,1,1,1,0,1] + * [null,1,0,1,0,0] + * ...... + * and so on. + * + * + * Constraints: + * + * 1 <= w.length <= 10^4 + * 1 <= w[i] <= 10^5 + * pickIndex will be called at most 10^4 times. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/random-pick-with-weight/ +// discuss: https://leetcode.com/problems/random-pick-with-weight/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct Solution { + vec![] + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl Solution { + + fn new(w: Vec) -> Self { + + } + + fn pick_index(&self) -> i32 { + + } +} + +/** + * Your Solution object will be instantiated and called as such: + * let obj = Solution::new(w); + * let ret_1: i32 = obj.pick_index(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_528() { + } +} diff --git a/src/problem/p0529_minesweeper.rs b/src/problem/p0529_minesweeper.rs new file mode 100644 index 00000000..4273bb24 --- /dev/null +++ b/src/problem/p0529_minesweeper.rs @@ -0,0 +1,67 @@ +/** + * [529] Minesweeper + * + * Let's play the minesweeper game (Wikipedia, online game)! + * You are given an m x n char matrix board representing the game board where: + * + * 'M' represents an unrevealed mine, + * 'E' represents an unrevealed empty square, + * 'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), + * digit ('1' to '8') represents how many mines are adjacent to this revealed square, and + * 'X' represents a revealed mine. + * + * You are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E'). + * Return the board after revealing this position according to the following rules: + *
    + * If a mine 'M' is revealed, then the game is over. You should change it to 'X'. + * If an empty square 'E' with no adjacent mines is revealed, then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively. + * If an empty square 'E' with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines. + * Return the board when no more squares will be revealed. + *
+ * + * Example 1: + * + * Input: board = [["E","E","E","E","E"],["E","E","M","E","E"],["E","E","E","E","E"],["E","E","E","E","E"]], click = [3,0] + * Output: [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]] + * + * Example 2: + * + * Input: board = [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]], click = [1,2] + * Output: [["B","1","E","1","B"],["B","1","X","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]] + * + * + * Constraints: + * + * m == board.length + * n == board[i].length + * 1 <= m, n <= 50 + * board[i][j] is either 'M', 'E', 'B', or a digit from '1' to '8'. + * click.length == 2 + * 0 <= clickr < m + * 0 <= clickc < n + * board[clickr][clickc] is either 'M' or 'E'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minesweeper/ +// discuss: https://leetcode.com/problems/minesweeper/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn update_board(board: Vec>, click: Vec) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_529() { + } +} diff --git a/src/problem/p0540_single_element_in_a_sorted_array.rs b/src/problem/p0540_single_element_in_a_sorted_array.rs new file mode 100644 index 00000000..a5d74ff6 --- /dev/null +++ b/src/problem/p0540_single_element_in_a_sorted_array.rs @@ -0,0 +1,43 @@ +/** + * [540] Single Element in a Sorted Array + * + * You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. + * Return the single element that appears only once. + * Your solution must run in O(log n) time and O(1) space. + * + * Example 1: + * Input: nums = [1,1,2,3,3,4,4,8,8] + * Output: 2 + * Example 2: + * Input: nums = [3,3,7,7,10,11,11] + * Output: 10 + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * 0 <= nums[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/single-element-in-a-sorted-array/ +// discuss: https://leetcode.com/problems/single-element-in-a-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn single_non_duplicate(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_540() { + } +} diff --git a/src/problem/p0541_reverse_string_ii.rs b/src/problem/p0541_reverse_string_ii.rs new file mode 100644 index 00000000..3d012233 --- /dev/null +++ b/src/problem/p0541_reverse_string_ii.rs @@ -0,0 +1,43 @@ +/** + * [541] Reverse String II + * + * Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string. + * If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original. + * + * Example 1: + * Input: s = "abcdefg", k = 2 + * Output: "bacdfeg" + * Example 2: + * Input: s = "abcd", k = 2 + * Output: "bacd" + * + * Constraints: + * + * 1 <= s.length <= 10^4 + * s consists of only lowercase English letters. + * 1 <= k <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/reverse-string-ii/ +// discuss: https://leetcode.com/problems/reverse-string-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn reverse_str(s: String, k: i32) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_541() { + } +} diff --git a/src/problem/p0543_diameter_of_binary_tree.rs b/src/problem/p0543_diameter_of_binary_tree.rs new file mode 100644 index 00000000..6c52dc53 --- /dev/null +++ b/src/problem/p0543_diameter_of_binary_tree.rs @@ -0,0 +1,69 @@ +/** + * [543] Diameter of Binary Tree + * + * Given the root of a binary tree, return the length of the diameter of the tree. + * The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. + * The length of a path between two nodes is represented by the number of edges between them. + * + * Example 1: + * + * Input: root = [1,2,3,4,5] + * Output: 3 + * Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. + * + * Example 2: + * + * Input: root = [1,2] + * Output: 1 + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 10^4]. + * -100 <= Node.val <= 100 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/diameter-of-binary-tree/ +// discuss: https://leetcode.com/problems/diameter-of-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn diameter_of_binary_tree(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_543() { + } +} diff --git a/src/problem/p0546_remove_boxes.rs b/src/problem/p0546_remove_boxes.rs new file mode 100644 index 00000000..ed884990 --- /dev/null +++ b/src/problem/p0546_remove_boxes.rs @@ -0,0 +1,58 @@ +/** + * [546] Remove Boxes + * + * You are given several boxes with different colors represented by different positive numbers. + * You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points. + * Return the maximum points you can get. + * + * Example 1: + * + * Input: boxes = [1,3,2,2,2,3,4,3,1] + * Output: 23 + * Explanation: + * [1, 3, 2, 2, 2, 3, 4, 3, 1] + * ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) + * ----> [1, 3, 3, 3, 1] (1*1=1 points) + * ----> [1, 1] (3*3=9 points) + * ----> [] (2*2=4 points) + * + * Example 2: + * + * Input: boxes = [1,1,1] + * Output: 9 + * + * Example 3: + * + * Input: boxes = [1] + * Output: 1 + * + * + * Constraints: + * + * 1 <= boxes.length <= 100 + * 1 <= boxes[i] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/remove-boxes/ +// discuss: https://leetcode.com/problems/remove-boxes/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn remove_boxes(boxes: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_546() { + } +} diff --git a/src/problem/p0553_optimal_division.rs b/src/problem/p0553_optimal_division.rs new file mode 100644 index 00000000..6d4f9ce9 --- /dev/null +++ b/src/problem/p0553_optimal_division.rs @@ -0,0 +1,65 @@ +/** + * [553] Optimal Division + * + * You are given an integer array nums. The adjacent integers in nums will perform the float division. + * + * For example, for nums = [2,3,4], we will evaluate the expression "2/3/4". + * + * However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. + * Return the corresponding expression that has the maximum value in string format. + * Note: your expression should not contain redundant parenthesis. + * + * Example 1: + * + * Input: nums = [1000,100,10,2] + * Output: "1000/(100/10/2)" + * Explanation: + * 1000/(100/10/2) = 1000/((100/10)/2) = 200 + * However, the bold parenthesis in "1000/((100/10)/2)" are redundant, since they don't influence the operation priority. So you should return "1000/(100/10/2)". + * Other cases: + * 1000/(100/10)/2 = 50 + * 1000/(100/(10/2)) = 50 + * 1000/100/10/2 = 0.5 + * 1000/100/(10/2) = 2 + * + * Example 2: + * + * Input: nums = [2,3,4] + * Output: "2/(3/4)" + * + * Example 3: + * + * Input: nums = [2] + * Output: "2" + * + * + * Constraints: + * + * 1 <= nums.length <= 10 + * 2 <= nums[i] <= 1000 + * There is only one optimal division for the given iput. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/optimal-division/ +// discuss: https://leetcode.com/problems/optimal-division/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn optimal_division(nums: Vec) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_553() { + } +} diff --git a/src/problem/p0554_brick_wall.rs b/src/problem/p0554_brick_wall.rs new file mode 100644 index 00000000..2d0a36d2 --- /dev/null +++ b/src/problem/p0554_brick_wall.rs @@ -0,0 +1,51 @@ +/** + * [554] Brick Wall + * + * There is a rectangular brick wall in front of you with n rows of bricks. The i^th row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. + * Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. + * Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line. + * + * Example 1: + * + * Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] + * Output: 2 + * + * Example 2: + * + * Input: wall = [[1],[1],[1]] + * Output: 3 + * + * + * Constraints: + * + * n == wall.length + * 1 <= n <= 10^4 + * 1 <= wall[i].length <= 10^4 + * 1 <= sum(wall[i].length) <= 2 * 10^4 + * sum(wall[i]) is the same for each row i. + * 1 <= wall[i][j] <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/brick-wall/ +// discuss: https://leetcode.com/problems/brick-wall/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn least_bricks(wall: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_554() { + } +} diff --git a/src/problem/p0565_array_nesting.rs b/src/problem/p0565_array_nesting.rs new file mode 100644 index 00000000..f34ce52e --- /dev/null +++ b/src/problem/p0565_array_nesting.rs @@ -0,0 +1,57 @@ +/** + * [565] Array Nesting + * + * You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1]. + * You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: + * + * The first element in s[k] starts with the selection of the element nums[k] of index = k. + * The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on. + * We stop adding right before a duplicate element occurs in s[k]. + * + * Return the longest length of a set s[k]. + * + * Example 1: + * + * Input: nums = [5,4,0,3,1,6,2] + * Output: 4 + * Explanation: + * nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2. + * One of the longest sets s[k]: + * s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0} + * + * Example 2: + * + * Input: nums = [0,1,2] + * Output: 1 + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * 0 <= nums[i] < nums.length + * All the values of nums are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/array-nesting/ +// discuss: https://leetcode.com/problems/array-nesting/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn array_nesting(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_565() { + } +} diff --git a/src/problem/p0567_permutation_in_string.rs b/src/problem/p0567_permutation_in_string.rs new file mode 100644 index 00000000..fbd4a724 --- /dev/null +++ b/src/problem/p0567_permutation_in_string.rs @@ -0,0 +1,47 @@ +/** + * [567] Permutation in String + * + * Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. + * In other words, return true if one of s1's permutations is the substring of s2. + * + * Example 1: + * + * Input: s1 = "ab", s2 = "eidbaooo" + * Output: true + * Explanation: s2 contains one permutation of s1 ("ba"). + * + * Example 2: + * + * Input: s1 = "ab", s2 = "eidboaoo" + * Output: false + * + * + * Constraints: + * + * 1 <= s1.length, s2.length <= 10^4 + * s1 and s2 consist of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/permutation-in-string/ +// discuss: https://leetcode.com/problems/permutation-in-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn check_inclusion(s1: String, s2: String) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_567() { + } +} diff --git a/src/problem/p0576_out_of_boundary_paths.rs b/src/problem/p0576_out_of_boundary_paths.rs new file mode 100644 index 00000000..6ba3ba9e --- /dev/null +++ b/src/problem/p0576_out_of_boundary_paths.rs @@ -0,0 +1,48 @@ +/** + * [576] Out of Boundary Paths + * + * There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball. + * Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 10^9 + 7. + * + * Example 1: + * + * Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 + * Output: 6 + * + * Example 2: + * + * Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 + * Output: 12 + * + * + * Constraints: + * + * 1 <= m, n <= 50 + * 0 <= maxMove <= 50 + * 0 <= startRow < m + * 0 <= startColumn < n + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/out-of-boundary-paths/ +// discuss: https://leetcode.com/problems/out-of-boundary-paths/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_paths(m: i32, n: i32, max_move: i32, start_row: i32, start_column: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_576() { + } +} diff --git a/src/problem/p0581_shortest_unsorted_continuous_subarray.rs b/src/problem/p0581_shortest_unsorted_continuous_subarray.rs new file mode 100644 index 00000000..804d8a38 --- /dev/null +++ b/src/problem/p0581_shortest_unsorted_continuous_subarray.rs @@ -0,0 +1,54 @@ +/** + * [581] Shortest Unsorted Continuous Subarray + * + * Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. + * Return the shortest such subarray and output its length. + * + * Example 1: + * + * Input: nums = [2,6,4,8,10,9,15] + * Output: 5 + * Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. + * + * Example 2: + * + * Input: nums = [1,2,3,4] + * Output: 0 + * + * Example 3: + * + * Input: nums = [1] + * Output: 0 + * + * + * Constraints: + * + * 1 <= nums.length <= 10^4 + * -10^5 <= nums[i] <= 10^5 + * + * + * Follow up: Can you solve it in O(n) time complexity? + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/ +// discuss: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_unsorted_subarray(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_581() { + } +} diff --git a/src/problem/p0587_erect_the_fence.rs b/src/problem/p0587_erect_the_fence.rs new file mode 100644 index 00000000..91200ef0 --- /dev/null +++ b/src/problem/p0587_erect_the_fence.rs @@ -0,0 +1,49 @@ +/** + * [587] Erect the Fence + * + * You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden. + * You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed. + * Return the coordinates of trees that are exactly located on the fence perimeter. + * + * Example 1: + * + * Input: points = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] + * Output: [[1,1],[2,0],[3,3],[2,4],[4,2]] + * + * Example 2: + * + * Input: points = [[1,2],[2,2],[4,2]] + * Output: [[4,2],[2,2],[1,2]] + * + * + * Constraints: + * + * 1 <= points.length <= 3000 + * points[i].length == 2 + * 0 <= xi, yi <= 100 + * All the given points are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/erect-the-fence/ +// discuss: https://leetcode.com/problems/erect-the-fence/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn outer_trees(trees: Vec>) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_587() { + } +} diff --git a/src/problem/p0591_tag_validator.rs b/src/problem/p0591_tag_validator.rs new file mode 100644 index 00000000..ed4f82f2 --- /dev/null +++ b/src/problem/p0591_tag_validator.rs @@ -0,0 +1,77 @@ +/** + * [591] Tag Validator + * + * Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. + * A code snippet is valid if all the following rules hold: + *
    + * The code must be wrapped in a valid closed tag. Otherwise, the code is invalid. + * A closed tag (not necessarily valid) has exactly the following format : TAG_CONTENT. Among them, is the start tag, and is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid. + * A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid. + * A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid. + * A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. + * A < is unmatched if you cannot find a subsequent >. And when you find a < or should be parsed as TAG_NAME (not necessarily valid). + * The cdata has the following format : . The range of CDATA_CONTENT is defined as the characters between . + * CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters. + *
+ * + * Example 1: + * + * Input: code = "
This is the first line ]]>
" + * Output: true + * Explanation: + * The code is wrapped in a closed tag :
and
. + * The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. + * Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. + * So TAG_CONTENT is valid, and then the code is valid. Thus return true. + * + * Example 2: + * + * Input: code = "
>> ![cdata[]] ]>]]>]]>>]
" + * Output: true + * Explanation: + * We first separate the code into : start_tag|tag_content|end_tag. + * start_tag -> "
" + * end_tag -> "
" + * tag_content could also be separated into : text1|cdata|text2. + * text1 -> ">> ![cdata[]] " + * cdata -> "]>]]>", where the CDATA_CONTENT is "
]>" + * text2 -> "]]>>]" + * The reason why start_tag is NOT "
>>" is because of the rule 6. + * The reason why cdata is NOT "]>]]>]]>" is because of the rule 7. + * + * Example 3: + * + * Input: code = " " + * Output: false + * Explanation: Unbalanced. If "" is closed, then "" must be unmatched, and vice versa. + * + * + * Constraints: + * + * 1 <= code.length <= 500 + * code consists of English letters, digits, '<', '>', '/', '!', '[', ']', '.', and ' '. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/tag-validator/ +// discuss: https://leetcode.com/problems/tag-validator/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_valid(code: String) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_591() { + } +} diff --git a/src/problem/p0592_fraction_addition_and_subtraction.rs b/src/problem/p0592_fraction_addition_and_subtraction.rs new file mode 100644 index 00000000..c66f6b56 --- /dev/null +++ b/src/problem/p0592_fraction_addition_and_subtraction.rs @@ -0,0 +1,54 @@ +/** + * [592] Fraction Addition and Subtraction + * + * Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. + * The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1. + * + * Example 1: + * + * Input: expression = "-1/2+1/2" + * Output: "0/1" + * + * Example 2: + * + * Input: expression = "-1/2+1/2+1/3" + * Output: "1/3" + * + * Example 3: + * + * Input: expression = "1/3-1/2" + * Output: "-1/6" + * + * + * Constraints: + * + * The input string only contains '0' to '9', '/', '+' and '-'. So does the output. + * Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted. + * The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above. + * The number of given fractions will be in the range [1, 10]. + * The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/fraction-addition-and-subtraction/ +// discuss: https://leetcode.com/problems/fraction-addition-and-subtraction/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn fraction_addition(expression: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_592() { + } +} diff --git a/src/problem/p0600_non_negative_integers_without_consecutive_ones.rs b/src/problem/p0600_non_negative_integers_without_consecutive_ones.rs new file mode 100644 index 00000000..738f3f27 --- /dev/null +++ b/src/problem/p0600_non_negative_integers_without_consecutive_ones.rs @@ -0,0 +1,58 @@ +/** + * [600] Non-negative Integers without Consecutive Ones + * + * Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones. + * + * Example 1: + * + * Input: n = 5 + * Output: 5 + * Explanation: + * Here are the non-negative integers <= 5 with their corresponding binary representations: + * 0 : 0 + * 1 : 1 + * 2 : 10 + * 3 : 11 + * 4 : 100 + * 5 : 101 + * Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. + * + * Example 2: + * + * Input: n = 1 + * Output: 2 + * + * Example 3: + * + * Input: n = 2 + * Output: 3 + * + * + * Constraints: + * + * 1 <= n <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/ +// discuss: https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_integers(n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_600() { + } +} diff --git a/src/problem/p0611_valid_triangle_number.rs b/src/problem/p0611_valid_triangle_number.rs new file mode 100644 index 00000000..06f1a32f --- /dev/null +++ b/src/problem/p0611_valid_triangle_number.rs @@ -0,0 +1,49 @@ +/** + * [611] Valid Triangle Number + * + * Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. + * + * Example 1: + * + * Input: nums = [2,2,3,4] + * Output: 3 + * Explanation: Valid combinations are: + * 2,3,4 (using the first 2) + * 2,3,4 (using the second 2) + * 2,2,3 + * + * Example 2: + * + * Input: nums = [4,2,3,4] + * Output: 4 + * + * + * Constraints: + * + * 1 <= nums.length <= 1000 + * 0 <= nums[i] <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/valid-triangle-number/ +// discuss: https://leetcode.com/problems/valid-triangle-number/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn triangle_number(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_611() { + } +} diff --git a/src/problem/p0617_merge_two_binary_trees.rs b/src/problem/p0617_merge_two_binary_trees.rs new file mode 100644 index 00000000..7b3e5ac4 --- /dev/null +++ b/src/problem/p0617_merge_two_binary_trees.rs @@ -0,0 +1,69 @@ +/** + * [617] Merge Two Binary Trees + * + * You are given two binary trees root1 and root2. + * Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree. + * Return the merged tree. + * Note: The merging process must start from the root nodes of both trees. + * + * Example 1: + * + * Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] + * Output: [3,4,5,5,4,null,7] + * + * Example 2: + * + * Input: root1 = [1], root2 = [1,2] + * Output: [2,2] + * + * + * Constraints: + * + * The number of nodes in both trees is in the range [0, 2000]. + * -10^4 <= Node.val <= 10^4 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/merge-two-binary-trees/ +// discuss: https://leetcode.com/problems/merge-two-binary-trees/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn merge_trees(root1: Option>>, root2: Option>>) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_617() { + } +} diff --git a/src/problem/p0629_k_inverse_pairs_array.rs b/src/problem/p0629_k_inverse_pairs_array.rs new file mode 100644 index 00000000..19831681 --- /dev/null +++ b/src/problem/p0629_k_inverse_pairs_array.rs @@ -0,0 +1,48 @@ +/** + * [629] K Inverse Pairs Array + * + * For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j]. + * Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 10^9 + 7. + * + * Example 1: + * + * Input: n = 3, k = 0 + * Output: 1 + * Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. + * + * Example 2: + * + * Input: n = 3, k = 1 + * Output: 2 + * Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. + * + * + * Constraints: + * + * 1 <= n <= 1000 + * 0 <= k <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/k-inverse-pairs-array/ +// discuss: https://leetcode.com/problems/k-inverse-pairs-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn k_inverse_pairs(n: i32, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_629() { + } +} diff --git a/src/problem/p0630_course_schedule_iii.rs b/src/problem/p0630_course_schedule_iii.rs new file mode 100644 index 00000000..af32d39d --- /dev/null +++ b/src/problem/p0630_course_schedule_iii.rs @@ -0,0 +1,58 @@ +/** + * [630] Course Schedule III + * + * There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the i^th course should be taken continuously for durationi days and must be finished before or on lastDayi. + * You will start on the 1^st day and you cannot take two or more courses simultaneously. + * Return the maximum number of courses that you can take. + * + * Example 1: + * + * Input: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]] + * Output: 3 + * Explanation: + * There are totally 4 courses, but you can take 3 courses at most: + * First, take the 1^st course, it costs 100 days so you will finish it on the 100^th day, and ready to take the next course on the 101^st day. + * Second, take the 3^rd course, it costs 1000 days so you will finish it on the 1100^th day, and ready to take the next course on the 1101^st day. + * Third, take the 2^nd course, it costs 200 days so you will finish it on the 1300^th day. + * The 4^th course cannot be taken now, since you will finish it on the 3300^th day, which exceeds the closed date. + * + * Example 2: + * + * Input: courses = [[1,2]] + * Output: 1 + * + * Example 3: + * + * Input: courses = [[3,2],[4,3]] + * Output: 0 + * + * + * Constraints: + * + * 1 <= courses.length <= 10^4 + * 1 <= durationi, lastDayi <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/course-schedule-iii/ +// discuss: https://leetcode.com/problems/course-schedule-iii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn schedule_course(courses: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_630() { + } +} diff --git a/src/problem/p0637_average_of_levels_in_binary_tree.rs b/src/problem/p0637_average_of_levels_in_binary_tree.rs new file mode 100644 index 00000000..af91144e --- /dev/null +++ b/src/problem/p0637_average_of_levels_in_binary_tree.rs @@ -0,0 +1,68 @@ +/** + * [637] Average of Levels in Binary Tree + * + * Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10^-5 of the actual answer will be accepted. + * + * Example 1: + * + * Input: root = [3,9,20,null,null,15,7] + * Output: [3.00000,14.50000,11.00000] + * Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. + * Hence return [3, 14.5, 11]. + * + * Example 2: + * + * Input: root = [3,9,20,15,7] + * Output: [3.00000,14.50000,11.00000] + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 10^4]. + * -2^31 <= Node.val <= 2^31 - 1 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/average-of-levels-in-binary-tree/ +// discuss: https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn average_of_levels(root: Option>>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_637() { + } +} diff --git a/src/problem/p0638_shopping_offers.rs b/src/problem/p0638_shopping_offers.rs new file mode 100644 index 00000000..30314da3 --- /dev/null +++ b/src/problem/p0638_shopping_offers.rs @@ -0,0 +1,62 @@ +/** + * [638] Shopping Offers + * + * In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. + * You are given an integer array price where price[i] is the price of the i^th item, and an integer array needs where needs[i] is the number of pieces of the i^th item you want to buy. + * You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the j^th item in the i^th offer and special[i][n] (i.e., the last integer in the array) is the price of the i^th offer. + * Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want. + * + * Example 1: + * + * Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2] + * Output: 14 + * Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. + * In special offer 1, you can pay $5 for 3A and 0B + * In special offer 2, you can pay $10 for 1A and 2B. + * You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. + * + * Example 2: + * + * Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1] + * Output: 11 + * Explanation: The price of A is $2, and $3 for B, $4 for C. + * You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. + * You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. + * You cannot add more items, though only $9 for 2A ,2B and 1C. + * + * + * Constraints: + * + * n == price.length + * n == needs.length + * 1 <= n <= 6 + * 0 <= price[i] <= 10 + * 0 <= needs[i] <= 10 + * 1 <= special.length <= 100 + * special[i].length == n + 1 + * 0 <= special[i][j] <= 50 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/shopping-offers/ +// discuss: https://leetcode.com/problems/shopping-offers/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn shopping_offers(price: Vec, special: Vec>, needs: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_638() { + } +} diff --git a/src/problem/p0641_design_circular_deque.rs b/src/problem/p0641_design_circular_deque.rs new file mode 100644 index 00000000..c6eb2d8f --- /dev/null +++ b/src/problem/p0641_design_circular_deque.rs @@ -0,0 +1,122 @@ +/** + * [641] Design Circular Deque + * + * Design your implementation of the circular double-ended queue (deque). + * Implement the MyCircularDeque class: + * + * MyCircularDeque(int k) Initializes the deque with a maximum size of k. + * boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise. + * boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise. + * boolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise. + * boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise. + * int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty. + * int getRear() Returns the last item from Deque. Returns -1 if the deque is empty. + * boolean isEmpty() Returns true if the deque is empty, or false otherwise. + * boolean isFull() Returns true if the deque is full, or false otherwise. + * + * + * Example 1: + * + * Input + * ["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"] + * [[3], [1], [2], [3], [4], [], [], [], [4], []] + * Output + * [null, true, true, true, false, 2, true, true, true, 4] + * Explanation + * MyCircularDeque myCircularDeque = new MyCircularDeque(3); + * myCircularDeque.insertLast(1); // return True + * myCircularDeque.insertLast(2); // return True + * myCircularDeque.insertFront(3); // return True + * myCircularDeque.insertFront(4); // return False, the queue is full. + * myCircularDeque.getRear(); // return 2 + * myCircularDeque.isFull(); // return True + * myCircularDeque.deleteLast(); // return True + * myCircularDeque.insertFront(4); // return True + * myCircularDeque.getFront(); // return 4 + * + * + * Constraints: + * + * 1 <= k <= 1000 + * 0 <= value <= 1000 + * At most 2000 calls will be made to insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, isFull. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/design-circular-deque/ +// discuss: https://leetcode.com/problems/design-circular-deque/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct MyCircularDeque { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl MyCircularDeque { + + fn new(k: i32) -> Self { + + } + + fn insert_front(&self, value: i32) -> bool { + + } + + fn insert_last(&self, value: i32) -> bool { + + } + + fn delete_front(&self) -> bool { + + } + + fn delete_last(&self) -> bool { + + } + + fn get_front(&self) -> i32 { + + } + + fn get_rear(&self) -> i32 { + + } + + fn is_empty(&self) -> bool { + + } + + fn is_full(&self) -> bool { + + } +} + +/** + * Your MyCircularDeque object will be instantiated and called as such: + * let obj = MyCircularDeque::new(k); + * let ret_1: bool = obj.insert_front(value); + * let ret_2: bool = obj.insert_last(value); + * let ret_3: bool = obj.delete_front(); + * let ret_4: bool = obj.delete_last(); + * let ret_5: i32 = obj.get_front(); + * let ret_6: i32 = obj.get_rear(); + * let ret_7: bool = obj.is_empty(); + * let ret_8: bool = obj.is_full(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_641() { + } +} diff --git a/src/problem/p0645_set_mismatch.rs b/src/problem/p0645_set_mismatch.rs new file mode 100644 index 00000000..036d5660 --- /dev/null +++ b/src/problem/p0645_set_mismatch.rs @@ -0,0 +1,43 @@ +/** + * [645] Set Mismatch + * + * You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. + * You are given an integer array nums representing the data status of this set after the error. + * Find the number that occurs twice and the number that is missing and return them in the form of an array. + * + * Example 1: + * Input: nums = [1,2,2,4] + * Output: [2,3] + * Example 2: + * Input: nums = [1,1] + * Output: [1,2] + * + * Constraints: + * + * 2 <= nums.length <= 10^4 + * 1 <= nums[i] <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/set-mismatch/ +// discuss: https://leetcode.com/problems/set-mismatch/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_error_nums(nums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_645() { + } +} diff --git a/src/problem/p0649_dota2_senate.rs b/src/problem/p0649_dota2_senate.rs new file mode 100644 index 00000000..825f4ed2 --- /dev/null +++ b/src/problem/p0649_dota2_senate.rs @@ -0,0 +1,63 @@ +/** + * [649] Dota2 Senate + * + * In the world of Dota2, there are two parties: the Radiant and the Dire. + * The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: + * + * Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds. + * Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game. + * + * Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n. + * The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. + * Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be "Radiant" or "Dire". + * + * Example 1: + * + * Input: senate = "RD" + * Output: "Radiant" + * Explanation: + * The first senator comes from Radiant and he can just ban the next senator's right in round 1. + * And the second senator can't exercise any rights anymore since his right has been banned. + * And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. + * + * Example 2: + * + * Input: senate = "RDD" + * Output: "Dire" + * Explanation: + * The first senator comes from Radiant and he can just ban the next senator's right in round 1. + * And the second senator can't exercise any rights anymore since his right has been banned. + * And the third senator comes from Dire and he can ban the first senator's right in round 1. + * And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. + * + * + * Constraints: + * + * n == senate.length + * 1 <= n <= 10^4 + * senate[i] is either 'R' or 'D'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/dota2-senate/ +// discuss: https://leetcode.com/problems/dota2-senate/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn predict_party_victory(senate: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_649() { + } +} diff --git a/src/problem/p0652_find_duplicate_subtrees.rs b/src/problem/p0652_find_duplicate_subtrees.rs new file mode 100644 index 00000000..b1d367fa --- /dev/null +++ b/src/problem/p0652_find_duplicate_subtrees.rs @@ -0,0 +1,73 @@ +/** + * [652] Find Duplicate Subtrees + * + * Given the root of a binary tree, return all duplicate subtrees. + * For each kind of duplicate subtrees, you only need to return the root node of any one of them. + * Two trees are duplicate if they have the same structure with the same node values. + * + * Example 1: + * + * Input: root = [1,2,3,4,null,2,4,null,null,4] + * Output: [[2,4],[4]] + * + * Example 2: + * + * Input: root = [2,1,1] + * Output: [[1]] + * + * Example 3: + * + * Input: root = [2,2,2,3,null,3,null] + * Output: [[2,3],[3]] + * + * + * Constraints: + * + * The number of the nodes in the tree will be in the range [1, 10^4] + * -200 <= Node.val <= 200 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/find-duplicate-subtrees/ +// discuss: https://leetcode.com/problems/find-duplicate-subtrees/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn find_duplicate_subtrees(root: Option>>) -> Vec>>> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_652() { + } +} diff --git a/src/problem/p0655_print_binary_tree.rs b/src/problem/p0655_print_binary_tree.rs new file mode 100644 index 00000000..2e8ccd39 --- /dev/null +++ b/src/problem/p0655_print_binary_tree.rs @@ -0,0 +1,81 @@ +/** + * [655] Print Binary Tree + * + * Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules: + * + * The height of the tree is height and the number of rows m should be equal to height + 1. + * The number of columns n should be equal to 2^height+1 - 1. + * Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]). + * For each node that has been placed in the matrix at position res[r][c], place its left child at res[r+1][c-2^height-r-1] and its right child at res[r+1][c+2^height-r-1]. + * Continue this process until all the nodes in the tree have been placed. + * Any empty cells should contain the empty string "". + * + * Return the constructed matrix res. + * + * Example 1: + * + * Input: root = [1,2] + * Output: + * [["","1",""], + * ["2","",""]] + * + * Example 2: + * + * Input: root = [1,2,3,null,4] + * Output: + * [["","","","1","","",""], + * ["","2","","","","3",""], + * ["","","4","","","",""]] + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 2^10]. + * -99 <= Node.val <= 99 + * The depth of the tree will be in the range [1, 10]. + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/print-binary-tree/ +// discuss: https://leetcode.com/problems/print-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn print_tree(root: Option>>) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_655() { + } +} diff --git a/src/problem/p0657_robot_return_to_origin.rs b/src/problem/p0657_robot_return_to_origin.rs new file mode 100644 index 00000000..27550834 --- /dev/null +++ b/src/problem/p0657_robot_return_to_origin.rs @@ -0,0 +1,50 @@ +/** + * [657] Robot Return to Origin + * + * There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. + * You are given a string moves that represents the move sequence of the robot where moves[i] represents its i^th move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down). + * Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise. + * Note: The way that the robot is "facing" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move. + * + * Example 1: + * + * Input: moves = "UD" + * Output: true + * Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true. + * + * Example 2: + * + * Input: moves = "LL" + * Output: false + * Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves. + * + * + * Constraints: + * + * 1 <= moves.length <= 2 * 10^4 + * moves only contains the characters 'U', 'D', 'L' and 'R'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/robot-return-to-origin/ +// discuss: https://leetcode.com/problems/robot-return-to-origin/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn judge_circle(moves: String) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_657() { + } +} diff --git a/src/problem/p0658_find_k_closest_elements.rs b/src/problem/p0658_find_k_closest_elements.rs new file mode 100644 index 00000000..527ba187 --- /dev/null +++ b/src/problem/p0658_find_k_closest_elements.rs @@ -0,0 +1,48 @@ +/** + * [658] Find K Closest Elements + * + * Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. + * An integer a is closer to x than an integer b if: + * + * |a - x| < |b - x|, or + * |a - x| == |b - x| and a < b + * + * + * Example 1: + * Input: arr = [1,2,3,4,5], k = 4, x = 3 + * Output: [1,2,3,4] + * Example 2: + * Input: arr = [1,2,3,4,5], k = 4, x = -1 + * Output: [1,2,3,4] + * + * Constraints: + * + * 1 <= k <= arr.length + * 1 <= arr.length <= 10^4 + * arr is sorted in ascending order. + * -10^4 <= arr[i], x <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-k-closest-elements/ +// discuss: https://leetcode.com/problems/find-k-closest-elements/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_closest_elements(arr: Vec, k: i32, x: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_658() { + } +} diff --git a/src/problem/p0659_split_array_into_consecutive_subsequences.rs b/src/problem/p0659_split_array_into_consecutive_subsequences.rs new file mode 100644 index 00000000..a3097be2 --- /dev/null +++ b/src/problem/p0659_split_array_into_consecutive_subsequences.rs @@ -0,0 +1,65 @@ +/** + * [659] Split Array into Consecutive Subsequences + * + * You are given an integer array nums that is sorted in non-decreasing order. + * Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true: + * + * Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer). + * All subsequences have a length of 3 or more. + * + * Return true if you can split nums according to the above conditions, or false otherwise. + * A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not). + * + * Example 1: + * + * Input: nums = [1,2,3,3,4,5] + * Output: true + * Explanation: nums can be split into the following subsequences: + * [1,2,3,3,4,5] --> 1, 2, 3 + * [1,2,3,3,4,5] --> 3, 4, 5 + * + * Example 2: + * + * Input: nums = [1,2,3,3,4,4,5,5] + * Output: true + * Explanation: nums can be split into the following subsequences: + * [1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5 + * [1,2,3,3,4,4,5,5] --> 3, 4, 5 + * + * Example 3: + * + * Input: nums = [1,2,3,4,4,5] + * Output: false + * Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more. + * + * + * Constraints: + * + * 1 <= nums.length <= 10^4 + * -1000 <= nums[i] <= 1000 + * nums is sorted in non-decreasing order. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/split-array-into-consecutive-subsequences/ +// discuss: https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_possible(nums: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_659() { + } +} diff --git a/src/problem/p0662_maximum_width_of_binary_tree.rs b/src/problem/p0662_maximum_width_of_binary_tree.rs new file mode 100644 index 00000000..e6eba83d --- /dev/null +++ b/src/problem/p0662_maximum_width_of_binary_tree.rs @@ -0,0 +1,77 @@ +/** + * [662] Maximum Width of Binary Tree + * + * Given the root of a binary tree, return the maximum width of the given tree. + * The maximum width of a tree is the maximum width among all levels. + * The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation. + * It is guaranteed that the answer will in the range of a 32-bit signed integer. + * + * Example 1: + * + * Input: root = [1,3,2,5,3,null,9] + * Output: 4 + * Explanation: The maximum width exists in the third level with length 4 (5,3,null,9). + * + * Example 2: + * + * Input: root = [1,3,2,5,null,null,9,6,null,7] + * Output: 7 + * Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7). + * + * Example 3: + * + * Input: root = [1,3,2,5] + * Output: 2 + * Explanation: The maximum width exists in the second level with length 2 (3,2). + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 3000]. + * -100 <= Node.val <= 100 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/maximum-width-of-binary-tree/ +// discuss: https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn width_of_binary_tree(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_662() { + } +} diff --git a/src/problem/p0664_strange_printer.rs b/src/problem/p0664_strange_printer.rs new file mode 100644 index 00000000..a76985ed --- /dev/null +++ b/src/problem/p0664_strange_printer.rs @@ -0,0 +1,52 @@ +/** + * [664] Strange Printer + * + * There is a strange printer with the following two special properties: + * + * The printer can only print a sequence of the same character each time. + * At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters. + * + * Given a string s, return the minimum number of turns the printer needed to print it. + * + * Example 1: + * + * Input: s = "aaabbb" + * Output: 2 + * Explanation: Print "aaa" first and then print "bbb". + * + * Example 2: + * + * Input: s = "aba" + * Output: 2 + * Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'. + * + * + * Constraints: + * + * 1 <= s.length <= 100 + * s consists of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/strange-printer/ +// discuss: https://leetcode.com/problems/strange-printer/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn strange_printer(s: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_664() { + } +} diff --git a/src/problem/p0671_second_minimum_node_in_a_binary_tree.rs b/src/problem/p0671_second_minimum_node_in_a_binary_tree.rs new file mode 100644 index 00000000..6299e77f --- /dev/null +++ b/src/problem/p0671_second_minimum_node_in_a_binary_tree.rs @@ -0,0 +1,72 @@ +/** + * [671] Second Minimum Node In a Binary Tree + * + * Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds. + * Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree. + * If no such second minimum value exists, output -1 instead. + * + * + * Example 1: + * + * Input: root = [2,2,5,null,null,5,7] + * Output: 5 + * Explanation: The smallest value is 2, the second smallest value is 5. + * + * Example 2: + * + * Input: root = [2,2,2] + * Output: -1 + * Explanation: The smallest value is 2, but there isn't any second smallest value. + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 25]. + * 1 <= Node.val <= 2^31 - 1 + * root.val == min(root.left.val, root.right.val) for each internal node of the tree. + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/ +// discuss: https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn find_second_minimum_value(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_671() { + } +} diff --git a/src/problem/p0674_longest_continuous_increasing_subsequence.rs b/src/problem/p0674_longest_continuous_increasing_subsequence.rs new file mode 100644 index 00000000..c339c4ec --- /dev/null +++ b/src/problem/p0674_longest_continuous_increasing_subsequence.rs @@ -0,0 +1,51 @@ +/** + * [674] Longest Continuous Increasing Subsequence + * + * Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing. + * A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1]. + * + * Example 1: + * + * Input: nums = [1,3,5,4,7] + * Output: 3 + * Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3. + * Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element + * 4. + * + * Example 2: + * + * Input: nums = [2,2,2,2,2] + * Output: 1 + * Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly + * increasing. + * + * + * Constraints: + * + * 1 <= nums.length <= 10^4 + * -10^9 <= nums[i] <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-continuous-increasing-subsequence/ +// discuss: https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_length_of_lcis(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_674() { + } +} diff --git a/src/problem/p0677_map_sum_pairs.rs b/src/problem/p0677_map_sum_pairs.rs new file mode 100644 index 00000000..c8f3fffc --- /dev/null +++ b/src/problem/p0677_map_sum_pairs.rs @@ -0,0 +1,86 @@ +/** + * [677] Map Sum Pairs + * + * Design a map that allows you to do the following: + * + * Maps a string key to a given value. + * Returns the sum of the values that have a key with a prefix equal to a given string. + * + * Implement the MapSum class: + * + * MapSum() Initializes the MapSum object. + * void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one. + * int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix. + * + * + * Example 1: + * + * Input + * ["MapSum", "insert", "sum", "insert", "sum"] + * [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]] + * Output + * [null, null, 3, null, 5] + * Explanation + * MapSum mapSum = new MapSum(); + * mapSum.insert("apple", 3); + * mapSum.sum("ap"); // return 3 (apple = 3) + * mapSum.insert("app", 2); + * mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5) + * + * + * Constraints: + * + * 1 <= key.length, prefix.length <= 50 + * key and prefix consist of only lowercase English letters. + * 1 <= val <= 1000 + * At most 50 calls will be made to insert and sum. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/map-sum-pairs/ +// discuss: https://leetcode.com/problems/map-sum-pairs/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct MapSum { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl MapSum { + + fn new() -> Self { + + } + + fn insert(&self, key: String, val: i32) { + + } + + fn sum(&self, prefix: String) -> i32 { + + } +} + +/** + * Your MapSum object will be instantiated and called as such: + * let obj = MapSum::new(); + * obj.insert(key, val); + * let ret_2: i32 = obj.sum(prefix); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_677() { + } +} diff --git a/src/problem/p0678_valid_parenthesis_string.rs b/src/problem/p0678_valid_parenthesis_string.rs new file mode 100644 index 00000000..bfdd8855 --- /dev/null +++ b/src/problem/p0678_valid_parenthesis_string.rs @@ -0,0 +1,51 @@ +/** + * [678] Valid Parenthesis String + * + * Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid. + * The following rules define a valid string: + * + * Any left parenthesis '(' must have a corresponding right parenthesis ')'. + * Any right parenthesis ')' must have a corresponding left parenthesis '('. + * Left parenthesis '(' must go before the corresponding right parenthesis ')'. + * '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "". + * + * + * Example 1: + * Input: s = "()" + * Output: true + * Example 2: + * Input: s = "(*)" + * Output: true + * Example 3: + * Input: s = "(*))" + * Output: true + * + * Constraints: + * + * 1 <= s.length <= 100 + * s[i] is '(', ')' or '*'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/valid-parenthesis-string/ +// discuss: https://leetcode.com/problems/valid-parenthesis-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn check_valid_string(s: String) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_678() { + } +} diff --git a/src/problem/p0684_redundant_connection.rs b/src/problem/p0684_redundant_connection.rs new file mode 100644 index 00000000..c4603e21 --- /dev/null +++ b/src/problem/p0684_redundant_connection.rs @@ -0,0 +1,52 @@ +/** + * [684] Redundant Connection + * + * In this problem, a tree is an undirected graph that is connected and has no cycles. + * You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph. + * Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input. + * + * Example 1: + * + * Input: edges = [[1,2],[1,3],[2,3]] + * Output: [2,3] + * + * Example 2: + * + * Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]] + * Output: [1,4] + * + * + * Constraints: + * + * n == edges.length + * 3 <= n <= 1000 + * edges[i].length == 2 + * 1 <= ai < bi <= edges.length + * ai != bi + * There are no repeated edges. + * The given graph is connected. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/redundant-connection/ +// discuss: https://leetcode.com/problems/redundant-connection/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_redundant_connection(edges: Vec>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_684() { + } +} diff --git a/src/problem/p0685_redundant_connection_ii.rs b/src/problem/p0685_redundant_connection_ii.rs new file mode 100644 index 00000000..adb91ae0 --- /dev/null +++ b/src/problem/p0685_redundant_connection_ii.rs @@ -0,0 +1,51 @@ +/** + * [685] Redundant Connection II + * + * In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents. + * The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. + * The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent of child vi. + * Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. + * + * Example 1: + * + * Input: edges = [[1,2],[1,3],[2,3]] + * Output: [2,3] + * + * Example 2: + * + * Input: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]] + * Output: [4,1] + * + * + * Constraints: + * + * n == edges.length + * 3 <= n <= 1000 + * edges[i].length == 2 + * 1 <= ui, vi <= n + * ui != vi + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/redundant-connection-ii/ +// discuss: https://leetcode.com/problems/redundant-connection-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_redundant_directed_connection(edges: Vec>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_685() { + } +} diff --git a/src/problem/p0687_longest_univalue_path.rs b/src/problem/p0687_longest_univalue_path.rs new file mode 100644 index 00000000..3a467fbf --- /dev/null +++ b/src/problem/p0687_longest_univalue_path.rs @@ -0,0 +1,70 @@ +/** + * [687] Longest Univalue Path + * + * Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root. + * The length of the path between two nodes is represented by the number of edges between them. + * + * Example 1: + * + * Input: root = [5,4,5,1,1,null,5] + * Output: 2 + * Explanation: The shown image shows that the longest path of the same value (i.e. 5). + * + * Example 2: + * + * Input: root = [1,4,5,4,4,null,5] + * Output: 2 + * Explanation: The shown image shows that the longest path of the same value (i.e. 4). + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [0, 10^4]. + * -1000 <= Node.val <= 1000 + * The depth of the tree will not exceed 1000. + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/longest-univalue-path/ +// discuss: https://leetcode.com/problems/longest-univalue-path/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn longest_univalue_path(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_687() { + } +} diff --git a/src/problem/p0691_stickers_to_spell_word.rs b/src/problem/p0691_stickers_to_spell_word.rs new file mode 100644 index 00000000..54411520 --- /dev/null +++ b/src/problem/p0691_stickers_to_spell_word.rs @@ -0,0 +1,57 @@ +/** + * [691] Stickers to Spell Word + * + * We are given n different types of stickers. Each sticker has a lowercase English word on it. + * You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker. + * Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1. + * Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words. + * + * Example 1: + * + * Input: stickers = ["with","example","science"], target = "thehat" + * Output: 3 + * Explanation: + * We can use 2 "with" stickers, and 1 "example" sticker. + * After cutting and rearrange the letters of those stickers, we can form the target "thehat". + * Also, this is the minimum number of stickers necessary to form the target string. + * + * Example 2: + * + * Input: stickers = ["notice","possible"], target = "basicbasic" + * Output: -1 + * Explanation: + * We cannot form the target "basicbasic" from cutting letters from the given stickers. + * + * + * Constraints: + * + * n == stickers.length + * 1 <= n <= 50 + * 1 <= stickers[i].length <= 10 + * 1 <= target.length <= 15 + * stickers[i] and target consist of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/stickers-to-spell-word/ +// discuss: https://leetcode.com/problems/stickers-to-spell-word/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_stickers(stickers: Vec, target: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_691() { + } +} diff --git a/src/problem/p0710_random_pick_with_blacklist.rs b/src/problem/p0710_random_pick_with_blacklist.rs new file mode 100644 index 00000000..0818353d --- /dev/null +++ b/src/problem/p0710_random_pick_with_blacklist.rs @@ -0,0 +1,82 @@ +/** + * [710] Random Pick with Blacklist + * + * You are given an integer n and an array of unique integers blacklist. Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned. + * Optimize your algorithm such that it minimizes the number of calls to the built-in random function of your language. + * Implement the Solution class: + * + * Solution(int n, int[] blacklist) Initializes the object with the integer n and the blacklisted integers blacklist. + * int pick() Returns a random integer in the range [0, n - 1] and not in blacklist. + * + * + * Example 1: + * + * Input + * ["Solution", "pick", "pick", "pick", "pick", "pick", "pick", "pick"] + * [[7, [2, 3, 5]], [], [], [], [], [], [], []] + * Output + * [null, 0, 4, 1, 6, 1, 0, 4] + * Explanation + * Solution solution = new Solution(7, [2, 3, 5]); + * solution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick, + * // 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4). + * solution.pick(); // return 4 + * solution.pick(); // return 1 + * solution.pick(); // return 6 + * solution.pick(); // return 1 + * solution.pick(); // return 0 + * solution.pick(); // return 4 + * + * + * Constraints: + * + * 1 <= n <= 10^9 + * 0 <= blacklist.length <= min(10^5, n - 1) + * 0 <= blacklist[i] < n + * All the values of blacklist are unique. + * At most 2 * 10^4 calls will be made to pick. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/random-pick-with-blacklist/ +// discuss: https://leetcode.com/problems/random-pick-with-blacklist/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct Solution { + vec![] + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl Solution { + + fn new(n: i32, blacklist: Vec) -> Self { + + } + + fn pick(&self) -> i32 { + + } +} + +/** + * Your Solution object will be instantiated and called as such: + * let obj = Solution::new(n, blacklist); + * let ret_1: i32 = obj.pick(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_710() { + } +} diff --git a/src/problem/p0714_best_time_to_buy_and_sell_stock_with_transaction_fee.rs b/src/problem/p0714_best_time_to_buy_and_sell_stock_with_transaction_fee.rs new file mode 100644 index 00000000..4f0616c7 --- /dev/null +++ b/src/problem/p0714_best_time_to_buy_and_sell_stock_with_transaction_fee.rs @@ -0,0 +1,54 @@ +/** + * [714] Best Time to Buy and Sell Stock with Transaction Fee + * + * You are given an array prices where prices[i] is the price of a given stock on the i^th day, and an integer fee representing a transaction fee. + * Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. + * Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). + * + * Example 1: + * + * Input: prices = [1,3,2,8,4,9], fee = 2 + * Output: 8 + * Explanation: The maximum profit can be achieved by: + * - Buying at prices[0] = 1 + * - Selling at prices[3] = 8 + * - Buying at prices[4] = 4 + * - Selling at prices[5] = 9 + * The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. + * + * Example 2: + * + * Input: prices = [1,3,7,5,10,3], fee = 3 + * Output: 6 + * + * + * Constraints: + * + * 1 <= prices.length <= 5 * 10^4 + * 1 <= prices[i] < 5 * 10^4 + * 0 <= fee < 5 * 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ +// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_profit(prices: Vec, fee: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_714() { + } +} diff --git a/src/problem/p0717_1_bit_and_2_bit_characters.rs b/src/problem/p0717_1_bit_and_2_bit_characters.rs new file mode 100644 index 00000000..a925dd48 --- /dev/null +++ b/src/problem/p0717_1_bit_and_2_bit_characters.rs @@ -0,0 +1,54 @@ +/** + * [717] 1-bit and 2-bit Characters + * + * We have two special characters: + * + * The first character can be represented by one bit 0. + * The second character can be represented by two bits (10 or 11). + * + * Given a binary array bits that ends with 0, return true if the last character must be a one-bit character. + * + * Example 1: + * + * Input: bits = [1,0,0] + * Output: true + * Explanation: The only way to decode it is two-bit character and one-bit character. + * So the last character is one-bit character. + * + * Example 2: + * + * Input: bits = [1,1,1,0] + * Output: false + * Explanation: The only way to decode it is two-bit character and two-bit character. + * So the last character is not one-bit character. + * + * + * Constraints: + * + * 1 <= bits.length <= 1000 + * bits[i] is either 0 or 1. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/1-bit-and-2-bit-characters/ +// discuss: https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_one_bit_character(bits: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_717() { + } +} diff --git a/src/problem/p0732_my_calendar_iii.rs b/src/problem/p0732_my_calendar_iii.rs new file mode 100644 index 00000000..1ed2f0b1 --- /dev/null +++ b/src/problem/p0732_my_calendar_iii.rs @@ -0,0 +1,77 @@ +/** + * [732] My Calendar III + * + * A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.) + * You are given some events [start, end), after each given event, return an integer k representing the maximum k-booking between all the previous events. + * Implement the MyCalendarThree class: + * + * MyCalendarThree() Initializes the object. + * int book(int start, int end) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar. + * + * + * Example 1: + * + * Input + * ["MyCalendarThree", "book", "book", "book", "book", "book", "book"] + * [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]] + * Output + * [null, 1, 1, 2, 3, 3, 3] + * Explanation + * MyCalendarThree myCalendarThree = new MyCalendarThree(); + * myCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking. + * myCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking. + * myCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking. + * myCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking. + * myCalendarThree.book(5, 10); // return 3 + * myCalendarThree.book(25, 55); // return 3 + * + * + * Constraints: + * + * 0 <= start < end <= 10^9 + * At most 400 calls will be made to book. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/my-calendar-iii/ +// discuss: https://leetcode.com/problems/my-calendar-iii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct MyCalendarThree { + vec![] + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl MyCalendarThree { + + fn new() -> Self { + + } + + fn book(&self, start: i32, end: i32) -> i32 { + + } +} + +/** + * Your MyCalendarThree object will be instantiated and called as such: + * let obj = MyCalendarThree::new(); + * let ret_1: i32 = obj.book(start, end); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_732() { + } +} diff --git a/src/problem/p0752_open_the_lock.rs b/src/problem/p0752_open_the_lock.rs new file mode 100644 index 00000000..153f8194 --- /dev/null +++ b/src/problem/p0752_open_the_lock.rs @@ -0,0 +1,62 @@ +/** + * [752] Open the Lock + * + * You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. + * The lock initially starts at '0000', a string representing the state of the 4 wheels. + * You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. + * Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. + * + * Example 1: + * + * Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" + * Output: 6 + * Explanation: + * A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". + * Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, + * because the wheels of the lock become stuck after the display becomes the dead end "0102". + * + * Example 2: + * + * Input: deadends = ["8888"], target = "0009" + * Output: 1 + * Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009". + * + * Example 3: + * + * Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" + * Output: -1 + * Explanation: We cannot reach the target without getting stuck. + * + * + * Constraints: + * + * 1 <= deadends.length <= 500 + * deadends[i].length == 4 + * target.length == 4 + * target will not be in the list deadends. + * target and deadends[i] consist of digits only. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/open-the-lock/ +// discuss: https://leetcode.com/problems/open-the-lock/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn open_lock(deadends: Vec, target: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_752() { + } +} diff --git a/src/problem/p0775_global_and_local_inversions.rs b/src/problem/p0775_global_and_local_inversions.rs new file mode 100644 index 00000000..22e74796 --- /dev/null +++ b/src/problem/p0775_global_and_local_inversions.rs @@ -0,0 +1,61 @@ +/** + * [775] Global and Local Inversions + * + * You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1]. + * The number of global inversions is the number of the different pairs (i, j) where: + * + * 0 <= i < j < n + * nums[i] > nums[j] + * + * The number of local inversions is the number of indices i where: + * + * 0 <= i < n - 1 + * nums[i] > nums[i + 1] + * + * Return true if the number of global inversions is equal to the number of local inversions. + * + * Example 1: + * + * Input: nums = [1,0,2] + * Output: true + * Explanation: There is 1 global inversion and 1 local inversion. + * + * Example 2: + * + * Input: nums = [1,2,0] + * Output: false + * Explanation: There are 2 global inversions and 1 local inversion. + * + * + * Constraints: + * + * n == nums.length + * 1 <= n <= 10^5 + * 0 <= nums[i] < n + * All the integers of nums are unique. + * nums is a permutation of all the numbers in the range [0, n - 1]. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/global-and-local-inversions/ +// discuss: https://leetcode.com/problems/global-and-local-inversions/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_ideal_permutation(nums: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_775() { + } +} diff --git a/src/problem/p0779_k_th_symbol_in_grammar.rs b/src/problem/p0779_k_th_symbol_in_grammar.rs new file mode 100644 index 00000000..6e2a5c62 --- /dev/null +++ b/src/problem/p0779_k_th_symbol_in_grammar.rs @@ -0,0 +1,61 @@ +/** + * [779] K-th Symbol in Grammar + * + * We build a table of n rows (1-indexed). We start by writing 0 in the 1^st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. + * + * For example, for n = 3, the 1^st row is 0, the 2^nd row is 01, and the 3^rd row is 0110. + * + * Given two integer n and k, return the k^th (1-indexed) symbol in the n^th row of a table of n rows. + * + * Example 1: + * + * Input: n = 1, k = 1 + * Output: 0 + * Explanation: row 1: 0 + * + * Example 2: + * + * Input: n = 2, k = 1 + * Output: 0 + * Explanation: + * row 1: 0 + * row 2: 01 + * + * Example 3: + * + * Input: n = 2, k = 2 + * Output: 1 + * Explanation: + * row 1: 0 + * row 2: 01 + * + * + * Constraints: + * + * 1 <= n <= 30 + * 1 <= k <= 2^n - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/k-th-symbol-in-grammar/ +// discuss: https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn kth_grammar(n: i32, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_779() { + } +} diff --git a/src/problem/p0783_minimum_distance_between_bst_nodes.rs b/src/problem/p0783_minimum_distance_between_bst_nodes.rs new file mode 100644 index 00000000..e359b664 --- /dev/null +++ b/src/problem/p0783_minimum_distance_between_bst_nodes.rs @@ -0,0 +1,69 @@ +/** + * [783] Minimum Distance Between BST Nodes + * + * Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree. + * + * Example 1: + * + * Input: root = [4,2,6,1,3] + * Output: 1 + * + * Example 2: + * + * Input: root = [1,0,48,null,null,12,49] + * Output: 1 + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [2, 100]. + * 0 <= Node.val <= 10^5 + * + * + * Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/ + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/minimum-distance-between-bst-nodes/ +// discuss: https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn min_diff_in_bst(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_783() { + } +} diff --git a/src/problem/p0787_cheapest_flights_within_k_stops.rs b/src/problem/p0787_cheapest_flights_within_k_stops.rs new file mode 100644 index 00000000..4e852ea9 --- /dev/null +++ b/src/problem/p0787_cheapest_flights_within_k_stops.rs @@ -0,0 +1,68 @@ +/** + * [787] Cheapest Flights Within K Stops + * + * There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. + * You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1. + * + * Example 1: + * + * Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 + * Output: 700 + * Explanation: + * The graph is shown above. + * The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. + * Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops. + * + * Example 2: + * + * Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 + * Output: 200 + * Explanation: + * The graph is shown above. + * The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. + * + * Example 3: + * + * Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 + * Output: 500 + * Explanation: + * The graph is shown above. + * The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. + * + * + * Constraints: + * + * 1 <= n <= 100 + * 0 <= flights.length <= (n * (n - 1) / 2) + * flights[i].length == 3 + * 0 <= fromi, toi < n + * fromi != toi + * 1 <= pricei <= 10^4 + * There will not be any multiple flights between two cities. + * 0 <= src, dst, k < n + * src != dst + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/cheapest-flights-within-k-stops/ +// discuss: https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_cheapest_price(n: i32, flights: Vec>, src: i32, dst: i32, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_787() { + } +} diff --git a/src/problem/p0788_rotated_digits.rs b/src/problem/p0788_rotated_digits.rs new file mode 100644 index 00000000..02d770ca --- /dev/null +++ b/src/problem/p0788_rotated_digits.rs @@ -0,0 +1,59 @@ +/** + * [788] Rotated Digits + * + * An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone. + * A number is valid if each digit remains a digit after rotation. For example: + * + * 0, 1, and 8 rotate to themselves, + * 2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored), + * 6 and 9 rotate to each other, and + * the rest of the numbers do not rotate to any other number and become invalid. + * + * Given an integer n, return the number of good integers in the range [1, n]. + * + * Example 1: + * + * Input: n = 10 + * Output: 4 + * Explanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9. + * Note that 1 and 10 are not good numbers, since they remain unchanged after rotating. + * + * Example 2: + * + * Input: n = 1 + * Output: 0 + * + * Example 3: + * + * Input: n = 2 + * Output: 1 + * + * + * Constraints: + * + * 1 <= n <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/rotated-digits/ +// discuss: https://leetcode.com/problems/rotated-digits/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn rotated_digits(n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_788() { + } +} diff --git a/src/problem/p0794_valid_tic_tac_toe_state.rs b/src/problem/p0794_valid_tic_tac_toe_state.rs new file mode 100644 index 00000000..4fe6a904 --- /dev/null +++ b/src/problem/p0794_valid_tic_tac_toe_state.rs @@ -0,0 +1,63 @@ +/** + * [794] Valid Tic-Tac-Toe State + * + * Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. + * The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square. + * Here are the rules of Tic-Tac-Toe: + * + * Players take turns placing characters into empty squares ' '. + * The first player always places 'X' characters, while the second player always places 'O' characters. + * 'X' and 'O' characters are always placed into empty squares, never filled ones. + * The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal. + * The game also ends if all squares are non-empty. + * No more moves can be played if the game is over. + * + * + * Example 1: + * + * Input: board = ["O "," "," "] + * Output: false + * Explanation: The first player always plays "X". + * + * Example 2: + * + * Input: board = ["XOX"," X "," "] + * Output: false + * Explanation: Players take turns making moves. + * + * Example 3: + * + * Input: board = ["XOX","O O","XOX"] + * Output: true + * + * + * Constraints: + * + * board.length == 3 + * board[i].length == 3 + * board[i][j] is either 'X', 'O', or ' '. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/valid-tic-tac-toe-state/ +// discuss: https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn valid_tic_tac_toe(board: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_794() { + } +} diff --git a/src/problem/p0795_number_of_subarrays_with_bounded_maximum.rs b/src/problem/p0795_number_of_subarrays_with_bounded_maximum.rs new file mode 100644 index 00000000..b13a1786 --- /dev/null +++ b/src/problem/p0795_number_of_subarrays_with_bounded_maximum.rs @@ -0,0 +1,48 @@ +/** + * [795] Number of Subarrays with Bounded Maximum + * + * Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right]. + * The test cases are generated so that the answer will fit in a 32-bit integer. + * + * Example 1: + * + * Input: nums = [2,1,4,3], left = 2, right = 3 + * Output: 3 + * Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3]. + * + * Example 2: + * + * Input: nums = [2,9,2,5,6], left = 2, right = 8 + * Output: 7 + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * 0 <= nums[i] <= 10^9 + * 0 <= left <= right <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/ +// discuss: https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_subarray_bounded_max(nums: Vec, left: i32, right: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_795() { + } +} diff --git a/src/problem/p0803_bricks_falling_when_hit.rs b/src/problem/p0803_bricks_falling_when_hit.rs new file mode 100644 index 00000000..0f7f06ed --- /dev/null +++ b/src/problem/p0803_bricks_falling_when_hit.rs @@ -0,0 +1,83 @@ +/** + * [803] Bricks Falling When Hit + * + * You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if: + * + * It is directly connected to the top of the grid, or + * At least one other brick in its four adjacent cells is stable. + * + * You are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks). + * Return an array result, where each result[i] is the number of bricks that will fall after the i^th erasure is applied. + * Note that an erasure may refer to a location with no brick, and if it does, no bricks drop. + * + * Example 1: + * + * Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]] + * Output: [2] + * Explanation: Starting with the grid: + * [[1,0,0,0], + * [1,1,1,0]] + * We erase the underlined brick at (1,0), resulting in the grid: + * [[1,0,0,0], + * [0,1,1,0]] + * The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is: + * [[1,0,0,0], + * [0,0,0,0]] + * Hence the result is [2]. + * + * Example 2: + * + * Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]] + * Output: [0,0] + * Explanation: Starting with the grid: + * [[1,0,0,0], + * [1,1,0,0]] + * We erase the underlined brick at (1,1), resulting in the grid: + * [[1,0,0,0], + * [1,0,0,0]] + * All remaining bricks are still stable, so no bricks fall. The grid remains the same: + * [[1,0,0,0], + * [1,0,0,0]] + * Next, we erase the underlined brick at (1,0), resulting in the grid: + * [[1,0,0,0], + * [0,0,0,0]] + * Once again, all remaining bricks are still stable, so no bricks fall. + * Hence the result is [0,0]. + * + * + * Constraints: + * + * m == grid.length + * n == grid[i].length + * 1 <= m, n <= 200 + * grid[i][j] is 0 or 1. + * 1 <= hits.length <= 4 * 10^4 + * hits[i].length == 2 + * 0 <= xi <= m - 1 + * 0 <= yi <= n - 1 + * All (xi, yi) are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/bricks-falling-when-hit/ +// discuss: https://leetcode.com/problems/bricks-falling-when-hit/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn hit_bricks(grid: Vec>, hits: Vec>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_803() { + } +} diff --git a/src/problem/p0804_unique_morse_code_words.rs b/src/problem/p0804_unique_morse_code_words.rs new file mode 100644 index 00000000..5da22a87 --- /dev/null +++ b/src/problem/p0804_unique_morse_code_words.rs @@ -0,0 +1,65 @@ +/** + * [804] Unique Morse Code Words + * + * International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: + * + * 'a' maps to ".-", + * 'b' maps to "-...", + * 'c' maps to "-.-.", and so on. + * + * For convenience, the full table for the 26 letters of the English alphabet is given below: + * + * [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] + * Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter. + * + * For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-", and "-...". We will call such a concatenation the transformation of a word. + * + * Return the number of different transformations among all words we have. + * + * Example 1: + * + * Input: words = ["gin","zen","gig","msg"] + * Output: 2 + * Explanation: The transformation of each word is: + * "gin" -> "--...-." + * "zen" -> "--...-." + * "gig" -> "--...--." + * "msg" -> "--...--." + * There are 2 different transformations: "--...-." and "--...--.". + * + * Example 2: + * + * Input: words = ["a"] + * Output: 1 + * + * + * Constraints: + * + * 1 <= words.length <= 100 + * 1 <= words[i].length <= 12 + * words[i] consists of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/unique-morse-code-words/ +// discuss: https://leetcode.com/problems/unique-morse-code-words/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn unique_morse_representations(words: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_804() { + } +} diff --git a/src/problem/p0807_max_increase_to_keep_city_skyline.rs b/src/problem/p0807_max_increase_to_keep_city_skyline.rs new file mode 100644 index 00000000..73abe9f5 --- /dev/null +++ b/src/problem/p0807_max_increase_to_keep_city_skyline.rs @@ -0,0 +1,58 @@ +/** + * [807] Max Increase to Keep City Skyline + * + * There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c. + * A city's skyline is the the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different. + * We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction. + * Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction. + * + * Example 1: + * + * Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]] + * Output: 35 + * Explanation: The building heights are shown in the center of the above image. + * The skylines when viewed from each cardinal direction are drawn in red. + * The grid after increasing the height of buildings without affecting skylines is: + * gridNew = [ [8, 4, 8, 7], + * [7, 4, 7, 7], + * [9, 4, 8, 7], + * [3, 3, 3, 3] ] + * + * Example 2: + * + * Input: grid = [[0,0,0],[0,0,0],[0,0,0]] + * Output: 0 + * Explanation: Increasing the height of any building will result in the skyline changing. + * + * + * Constraints: + * + * n == grid.length + * n == grid[r].length + * 2 <= n <= 50 + * 0 <= grid[r][c] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/max-increase-to-keep-city-skyline/ +// discuss: https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_increase_keeping_skyline(grid: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_807() { + } +} diff --git a/src/problem/p0808_soup_servings.rs b/src/problem/p0808_soup_servings.rs new file mode 100644 index 00000000..eb1199ab --- /dev/null +++ b/src/problem/p0808_soup_servings.rs @@ -0,0 +1,57 @@ +/** + * [808] Soup Servings + * + * There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations: + *
    + * Serve 100 ml of soup A and 0 ml of soup B, + * Serve 75 ml of soup A and 25 ml of soup B, + * Serve 50 ml of soup A and 50 ml of soup B, and + * Serve 25 ml of soup A and 75 ml of soup B. + *
+ * When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup. + * Note that we do not have an operation where all 100 ml's of soup B are used first. + * Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time. Answers within 10^-5 of the actual answer will be accepted. + * + * Example 1: + * + * Input: n = 50 + * Output: 0.62500 + * Explanation: If we choose the first two operations, A will become empty first. + * For the third operation, A and B will become empty at the same time. + * For the fourth operation, B will become empty first. + * So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625. + * + * Example 2: + * + * Input: n = 100 + * Output: 0.71875 + * + * + * Constraints: + * + * 0 <= n <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/soup-servings/ +// discuss: https://leetcode.com/problems/soup-servings/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn soup_servings(n: i32) -> f64 { + 0f64 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_808() { + } +} diff --git a/src/problem/p0809_expressive_words.rs b/src/problem/p0809_expressive_words.rs new file mode 100644 index 00000000..99a4f715 --- /dev/null +++ b/src/problem/p0809_expressive_words.rs @@ -0,0 +1,59 @@ +/** + * [809] Expressive Words + * + * Sometimes people repeat letters to represent extra feeling. For example: + * + * "hello" -> "heeellooo" + * "hi" -> "hiiii" + * + * In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo". + * You are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is three or more. + * + * For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has a size less than three. Also, we could do another extension like "ll" -> "lllll" to get "helllllooo". If s = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = s. + * + * Return the number of query strings that are stretchy. + * + * Example 1: + * + * Input: s = "heeellooo", words = ["hello", "hi", "helo"] + * Output: 1 + * Explanation: + * We can extend "e" and "o" in the word "hello" to get "heeellooo". + * We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more. + * + * Example 2: + * + * Input: s = "zzzzzyyyyy", words = ["zzyy","zy","zyy"] + * Output: 3 + * + * + * Constraints: + * + * 1 <= s.length, words.length <= 100 + * 1 <= words[i].length <= 100 + * s and words[i] consist of lowercase letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/expressive-words/ +// discuss: https://leetcode.com/problems/expressive-words/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn expressive_words(s: String, words: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_809() { + } +} diff --git a/src/problem/p0813_largest_sum_of_averages.rs b/src/problem/p0813_largest_sum_of_averages.rs new file mode 100644 index 00000000..0b2a85a0 --- /dev/null +++ b/src/problem/p0813_largest_sum_of_averages.rs @@ -0,0 +1,52 @@ +/** + * [813] Largest Sum of Averages + * + * You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. + * Note that the partition must use every integer in nums, and that the score is not necessarily an integer. + * Return the maximum score you can achieve of all the possible partitions. Answers within 10^-6 of the actual answer will be accepted. + * + * Example 1: + * + * Input: nums = [9,1,2,3,9], k = 3 + * Output: 20.00000 + * Explanation: + * The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. + * We could have also partitioned nums into [9, 1], [2], [3, 9], for example. + * That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. + * + * Example 2: + * + * Input: nums = [1,2,3,4,5,6,7], k = 4 + * Output: 20.50000 + * + * + * Constraints: + * + * 1 <= nums.length <= 100 + * 1 <= nums[i] <= 10^4 + * 1 <= k <= nums.length + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/largest-sum-of-averages/ +// discuss: https://leetcode.com/problems/largest-sum-of-averages/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn largest_sum_of_averages(nums: Vec, k: i32) -> f64 { + 0f64 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_813() { + } +} diff --git a/src/problem/p0818_race_car.rs b/src/problem/p0818_race_car.rs new file mode 100644 index 00000000..77ebcec4 --- /dev/null +++ b/src/problem/p0818_race_car.rs @@ -0,0 +1,66 @@ +/** + * [818] Race Car + * + * Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse): + * + * When you get an instruction 'A', your car does the following: + * + * position += speed + * speed *= 2 + * + * + * When you get an instruction 'R', your car does the following: + * + * If your speed is positive then speed = -1 + * otherwise speed = 1 + * + * Your position stays the same. + * + * For example, after commands "AAR", your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1. + * Given a target position target, return the length of the shortest sequence of instructions to get there. + * + * Example 1: + * + * Input: target = 3 + * Output: 2 + * Explanation: + * The shortest instruction sequence is "AA". + * Your position goes from 0 --> 1 --> 3. + * + * Example 2: + * + * Input: target = 6 + * Output: 5 + * Explanation: + * The shortest instruction sequence is "AAARA". + * Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6. + * + * + * Constraints: + * + * 1 <= target <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/race-car/ +// discuss: https://leetcode.com/problems/race-car/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn racecar(target: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_818() { + } +} diff --git a/src/problem/p0820_short_encoding_of_words.rs b/src/problem/p0820_short_encoding_of_words.rs new file mode 100644 index 00000000..be84351c --- /dev/null +++ b/src/problem/p0820_short_encoding_of_words.rs @@ -0,0 +1,57 @@ +/** + * [820] Short Encoding of Words + * + * A valid encoding of an array of words is any reference string s and array of indices indices such that: + * + * words.length == indices.length + * The reference string s ends with the '#' character. + * For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i]. + * + * Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words. + * + * Example 1: + * + * Input: words = ["time", "me", "bell"] + * Output: 10 + * Explanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5]. + * words[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#" + * words[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#" + * words[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#" + * + * Example 2: + * + * Input: words = ["t"] + * Output: 2 + * Explanation: A valid encoding would be s = "t#" and indices = [0]. + * + * + * Constraints: + * + * 1 <= words.length <= 2000 + * 1 <= words[i].length <= 7 + * words[i] consists of only lowercase letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/short-encoding-of-words/ +// discuss: https://leetcode.com/problems/short-encoding-of-words/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn minimum_length_encoding(words: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_820() { + } +} diff --git a/src/problem/p0823_binary_trees_with_factors.rs b/src/problem/p0823_binary_trees_with_factors.rs new file mode 100644 index 00000000..9381b9ad --- /dev/null +++ b/src/problem/p0823_binary_trees_with_factors.rs @@ -0,0 +1,48 @@ +/** + * [823] Binary Trees With Factors + * + * Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. + * We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. + * Return the number of binary trees we can make. The answer may be too large so return the answer modulo 10^9 + 7. + * + * Example 1: + * + * Input: arr = [2,4] + * Output: 3 + * Explanation: We can make these trees: [2], [4], [4, 2, 2] + * Example 2: + * + * Input: arr = [2,4,5,10] + * Output: 7 + * Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]. + * + * Constraints: + * + * 1 <= arr.length <= 1000 + * 2 <= arr[i] <= 10^9 + * All the values of arr are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/binary-trees-with-factors/ +// discuss: https://leetcode.com/problems/binary-trees-with-factors/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_factored_binary_trees(arr: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_823() { + } +} diff --git a/src/problem/p0825_friends_of_appropriate_ages.rs b/src/problem/p0825_friends_of_appropriate_ages.rs new file mode 100644 index 00000000..da88450c --- /dev/null +++ b/src/problem/p0825_friends_of_appropriate_ages.rs @@ -0,0 +1,63 @@ +/** + * [825] Friends Of Appropriate Ages + * + * There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the i^th person. + * A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true: + * + * age[y] <= 0.5 * age[x] + 7 + * age[y] > age[x] + * age[y] > 100 && age[x] < 100 + * + * Otherwise, x will send a friend request to y. + * Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself. + * Return the total number of friend requests made. + * + * Example 1: + * + * Input: ages = [16,16] + * Output: 2 + * Explanation: 2 people friend request each other. + * + * Example 2: + * + * Input: ages = [16,17,18] + * Output: 2 + * Explanation: Friend requests are made 17 -> 16, 18 -> 17. + * + * Example 3: + * + * Input: ages = [20,30,100,110,120] + * Output: 3 + * Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. + * + * + * Constraints: + * + * n == ages.length + * 1 <= n <= 2 * 10^4 + * 1 <= ages[i] <= 120 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/friends-of-appropriate-ages/ +// discuss: https://leetcode.com/problems/friends-of-appropriate-ages/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_friend_requests(ages: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_825() { + } +} diff --git a/src/problem/p0826_most_profit_assigning_work.rs b/src/problem/p0826_most_profit_assigning_work.rs new file mode 100644 index 00000000..24241b48 --- /dev/null +++ b/src/problem/p0826_most_profit_assigning_work.rs @@ -0,0 +1,58 @@ +/** + * [826] Most Profit Assigning Work + * + * You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: + * + * difficulty[i] and profit[i] are the difficulty and the profit of the i^th job, and + * worker[j] is the ability of j^th worker (i.e., the j^th worker can only complete a job with difficulty at most worker[j]). + * + * Every worker can be assigned at most one job, but one job can be completed multiple times. + * + * For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0. + * + * Return the maximum profit we can achieve after assigning the workers to the jobs. + * + * Example 1: + * + * Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7] + * Output: 100 + * Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately. + * + * Example 2: + * + * Input: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25] + * Output: 0 + * + * + * Constraints: + * + * n == difficulty.length + * n == profit.length + * m == worker.length + * 1 <= n, m <= 10^4 + * 1 <= difficulty[i], profit[i], worker[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/most-profit-assigning-work/ +// discuss: https://leetcode.com/problems/most-profit-assigning-work/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_profit_assignment(difficulty: Vec, profit: Vec, worker: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_826() { + } +} diff --git a/src/problem/p0827_making_a_large_island.rs b/src/problem/p0827_making_a_large_island.rs new file mode 100644 index 00000000..b4f28e09 --- /dev/null +++ b/src/problem/p0827_making_a_large_island.rs @@ -0,0 +1,66 @@ +/** + * [827] Making A Large Island + * + * You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. + * + * Return the size of the largest island in grid after applying this operation. + * + * An island is a 4-directionally connected group of 1s. + * + * + * Example 1: + * + * + * Input: grid = [[1,0],[0,1]] + * Output: 3 + * Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3. + * + * + * Example 2: + * + * + * Input: grid = [[1,1],[1,0]] + * Output: 4 + * Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4. + * + * Example 3: + * + * + * Input: grid = [[1,1],[1,1]] + * Output: 4 + * Explanation: Can't change any 0 to 1, only one island with area = 4. + * + * + * + * Constraints: + * + * + * n == grid.length + * n == grid[i].length + * 1 <= n <= 500 + * grid[i][j] is either 0 or 1. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/making-a-large-island/ +// discuss: https://leetcode.com/problems/making-a-large-island/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn largest_island(grid: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_827() { + } +} diff --git a/src/problem/p0828_count_unique_characters_of_all_substrings_of_a_given_string.rs b/src/problem/p0828_count_unique_characters_of_all_substrings_of_a_given_string.rs new file mode 100644 index 00000000..21016390 --- /dev/null +++ b/src/problem/p0828_count_unique_characters_of_all_substrings_of_a_given_string.rs @@ -0,0 +1,59 @@ +/** + * [828] Count Unique Characters of All Substrings of a Given String + * + * Let's define a function countUniqueChars(s) that returns the number of unique characters on s. + * + * For example, calling countUniqueChars(s) if s = "LEETCODE" then "L", "T", "C", "O", "D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5. + * + * Given a string s, return the sum of countUniqueChars(t) where t is a substring of s. The test cases are generated such that the answer fits in a 32-bit integer. + * Notice that some substrings can be repeated so in this case you have to count the repeated ones too. + * + * Example 1: + * + * Input: s = "ABC" + * Output: 10 + * Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC". + * Every substring is composed with only unique letters. + * Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 + * + * Example 2: + * + * Input: s = "ABA" + * Output: 8 + * Explanation: The same as example 1, except countUniqueChars("ABA") = 1. + * + * Example 3: + * + * Input: s = "LEETCODE" + * Output: 92 + * + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s consists of uppercase English letters only. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/ +// discuss: https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn unique_letter_string(s: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_828() { + } +} diff --git a/src/problem/p0835_image_overlap.rs b/src/problem/p0835_image_overlap.rs new file mode 100644 index 00000000..078cb9b3 --- /dev/null +++ b/src/problem/p0835_image_overlap.rs @@ -0,0 +1,60 @@ +/** + * [835] Image Overlap + * + * You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values. + * We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images. + * Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased. + * Return the largest possible overlap. + * + * Example 1: + * + * Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]] + * Output: 3 + * Explanation: We translate img1 to right by 1 unit and down by 1 unit. + * + * The number of positions that have a 1 in both images is 3 (shown in red). + * + * + * Example 2: + * + * Input: img1 = [[1]], img2 = [[1]] + * Output: 1 + * + * Example 3: + * + * Input: img1 = [[0]], img2 = [[0]] + * Output: 0 + * + * + * Constraints: + * + * n == img1.length == img1[i].length + * n == img2.length == img2[i].length + * 1 <= n <= 30 + * img1[i][j] is either 0 or 1. + * img2[i][j] is either 0 or 1. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/image-overlap/ +// discuss: https://leetcode.com/problems/image-overlap/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn largest_overlap(img1: Vec>, img2: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_835() { + } +} diff --git a/src/problem/p0839_similar_string_groups.rs b/src/problem/p0839_similar_string_groups.rs new file mode 100644 index 00000000..4b9b47be --- /dev/null +++ b/src/problem/p0839_similar_string_groups.rs @@ -0,0 +1,50 @@ +/** + * [839] Similar String Groups + * + * Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal. + * For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts". + * Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. + * We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there? + * + * Example 1: + * + * Input: strs = ["tars","rats","arts","star"] + * Output: 2 + * + * Example 2: + * + * Input: strs = ["omv","ovm"] + * Output: 1 + * + * + * Constraints: + * + * 1 <= strs.length <= 300 + * 1 <= strs[i].length <= 300 + * strs[i] consists of lowercase letters only. + * All words in strs have the same length and are anagrams of each other. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/similar-string-groups/ +// discuss: https://leetcode.com/problems/similar-string-groups/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_similar_groups(strs: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_839() { + } +} diff --git a/src/problem/p0842_split_array_into_fibonacci_sequence.rs b/src/problem/p0842_split_array_into_fibonacci_sequence.rs new file mode 100644 index 00000000..098d1b9b --- /dev/null +++ b/src/problem/p0842_split_array_into_fibonacci_sequence.rs @@ -0,0 +1,61 @@ +/** + * [842] Split Array into Fibonacci Sequence + * + * You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579]. + * Formally, a Fibonacci-like sequence is a list f of non-negative integers such that: + * + * 0 <= f[i] < 2^31, (that is, each integer fits in a 32-bit signed integer type), + * f.length >= 3, and + * f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2. + * + * Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself. + * Return any Fibonacci-like sequence split from num, or return [] if it cannot be done. + * + * Example 1: + * + * Input: num = "1101111" + * Output: [11,0,11,11] + * Explanation: The output [110, 1, 111] would also be accepted. + * + * Example 2: + * + * Input: num = "112358130" + * Output: [] + * Explanation: The task is impossible. + * + * Example 3: + * + * Input: num = "0123" + * Output: [] + * Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid. + * + * + * Constraints: + * + * 1 <= num.length <= 200 + * num contains only digits. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/split-array-into-fibonacci-sequence/ +// discuss: https://leetcode.com/problems/split-array-into-fibonacci-sequence/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn split_into_fibonacci(num: String) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_842() { + } +} diff --git a/src/problem/p0847_shortest_path_visiting_all_nodes.rs b/src/problem/p0847_shortest_path_visiting_all_nodes.rs new file mode 100644 index 00000000..7a2ea60e --- /dev/null +++ b/src/problem/p0847_shortest_path_visiting_all_nodes.rs @@ -0,0 +1,52 @@ +/** + * [847] Shortest Path Visiting All Nodes + * + * You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. + * Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. + * + * Example 1: + * + * Input: graph = [[1,2,3],[0],[0],[0]] + * Output: 4 + * Explanation: One possible path is [1,0,2,0,3] + * + * Example 2: + * + * Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]] + * Output: 4 + * Explanation: One possible path is [0,1,4,2,3] + * + * + * Constraints: + * + * n == graph.length + * 1 <= n <= 12 + * 0 <= graph[i].length < n + * graph[i] does not contain i. + * If graph[a] contains b, then graph[b] contains a. + * The input graph is always connected. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/shortest-path-visiting-all-nodes/ +// discuss: https://leetcode.com/problems/shortest-path-visiting-all-nodes/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn shortest_path_length(graph: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_847() { + } +} diff --git a/src/problem/p0850_rectangle_area_ii.rs b/src/problem/p0850_rectangle_area_ii.rs new file mode 100644 index 00000000..e8559967 --- /dev/null +++ b/src/problem/p0850_rectangle_area_ii.rs @@ -0,0 +1,52 @@ +/** + * [850] Rectangle Area II + * + * You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the i^th rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner. + * Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once. + * Return the total area. Since the answer may be too large, return it modulo 10^9 + 7. + * + * Example 1: + * + * Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]] + * Output: 6 + * Explanation: A total area of 6 is covered by all three rectangales, as illustrated in the picture. + * From (1,1) to (2,2), the green and red rectangles overlap. + * From (1,0) to (2,3), all three rectangles overlap. + * + * Example 2: + * + * Input: rectangles = [[0,0,1000000000,1000000000]] + * Output: 49 + * Explanation: The answer is 10^18 modulo (10^9 + 7), which is 49. + * + * + * Constraints: + * + * 1 <= rectangles.length <= 200 + * rectanges[i].length == 4 + * 0 <= xi1, yi1, xi2, yi2 <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/rectangle-area-ii/ +// discuss: https://leetcode.com/problems/rectangle-area-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn rectangle_area(rectangles: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_850() { + } +} diff --git a/src/problem/p0858_mirror_reflection.rs b/src/problem/p0858_mirror_reflection.rs new file mode 100644 index 00000000..36a23d64 --- /dev/null +++ b/src/problem/p0858_mirror_reflection.rs @@ -0,0 +1,48 @@ +/** + * [858] Mirror Reflection + * + * There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. + * The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0^th receptor. + * Given the two integers p and q, return the number of the receptor that the ray meets first. + * The test cases are guaranteed so that the ray will meet a receptor eventually. + * + * Example 1: + * + * Input: p = 2, q = 1 + * Output: 2 + * Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall. + * + * Example 2: + * + * Input: p = 3, q = 1 + * Output: 1 + * + * + * Constraints: + * + * 1 <= q <= p <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/mirror-reflection/ +// discuss: https://leetcode.com/problems/mirror-reflection/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn mirror_reflection(p: i32, q: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_858() { + } +} diff --git a/src/problem/p0859_buddy_strings.rs b/src/problem/p0859_buddy_strings.rs new file mode 100644 index 00000000..a6a69b4f --- /dev/null +++ b/src/problem/p0859_buddy_strings.rs @@ -0,0 +1,57 @@ +/** + * [859] Buddy Strings + * + * Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false. + * Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j]. + * + * For example, swapping at indices 0 and 2 in "abcd" results in "cbad". + * + * + * Example 1: + * + * Input: s = "ab", goal = "ba" + * Output: true + * Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal. + * + * Example 2: + * + * Input: s = "ab", goal = "ab" + * Output: false + * Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal. + * + * Example 3: + * + * Input: s = "aa", goal = "aa" + * Output: true + * Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal. + * + * + * Constraints: + * + * 1 <= s.length, goal.length <= 2 * 10^4 + * s and goal consist of lowercase letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/buddy-strings/ +// discuss: https://leetcode.com/problems/buddy-strings/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn buddy_strings(s: String, goal: String) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_859() { + } +} diff --git a/src/problem/p0861_score_after_flipping_matrix.rs b/src/problem/p0861_score_after_flipping_matrix.rs new file mode 100644 index 00000000..9bc0d37a --- /dev/null +++ b/src/problem/p0861_score_after_flipping_matrix.rs @@ -0,0 +1,51 @@ +/** + * [861] Score After Flipping Matrix + * + * You are given an m x n binary matrix grid. + * A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's). + * Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. + * Return the highest possible score after making any number of moves (including zero moves). + * + * Example 1: + * + * Input: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]] + * Output: 39 + * Explanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39 + * + * Example 2: + * + * Input: grid = [[0]] + * Output: 1 + * + * + * Constraints: + * + * m == grid.length + * n == grid[i].length + * 1 <= m, n <= 20 + * grid[i][j] is either 0 or 1. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/score-after-flipping-matrix/ +// discuss: https://leetcode.com/problems/score-after-flipping-matrix/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn matrix_score(grid: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_861() { + } +} diff --git a/src/problem/p0865_smallest_subtree_with_all_the_deepest_nodes.rs b/src/problem/p0865_smallest_subtree_with_all_the_deepest_nodes.rs new file mode 100644 index 00000000..f1fa4185 --- /dev/null +++ b/src/problem/p0865_smallest_subtree_with_all_the_deepest_nodes.rs @@ -0,0 +1,83 @@ +/** + * [865] Smallest Subtree with all the Deepest Nodes + * + * Given the root of a binary tree, the depth of each node is the shortest distance to the root. + * Return the smallest subtree such that it contains all the deepest nodes in the original tree. + * A node is called the deepest if it has the largest depth possible among any node in the entire tree. + * The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node. + * + * Example 1: + * + * Input: root = [3,5,1,6,2,0,8,null,null,7,4] + * Output: [2,7,4] + * Explanation: We return the node with value 2, colored in yellow in the diagram. + * The nodes coloured in blue are the deepest nodes of the tree. + * Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it. + * + * Example 2: + * + * Input: root = [1] + * Output: [1] + * Explanation: The root is the deepest node in the tree. + * + * Example 3: + * + * Input: root = [0,1,3,null,2] + * Output: [2] + * Explanation: The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest. + * + * + * Constraints: + * + * The number of nodes in the tree will be in the range [1, 500]. + * 0 <= Node.val <= 500 + * The values of the nodes in the tree are unique. + * + * + * Note: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/ + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/ +// discuss: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn subtree_with_all_deepest(root: Option>>) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_865() { + } +} diff --git a/src/problem/p0869_reordered_power_of_2.rs b/src/problem/p0869_reordered_power_of_2.rs new file mode 100644 index 00000000..e6f8d5d6 --- /dev/null +++ b/src/problem/p0869_reordered_power_of_2.rs @@ -0,0 +1,45 @@ +/** + * [869] Reordered Power of 2 + * + * You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero. + * Return true if and only if we can do this so that the resulting number is a power of two. + * + * Example 1: + * + * Input: n = 1 + * Output: true + * + * Example 2: + * + * Input: n = 10 + * Output: false + * + * + * Constraints: + * + * 1 <= n <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/reordered-power-of-2/ +// discuss: https://leetcode.com/problems/reordered-power-of-2/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn reordered_power_of2(n: i32) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_869() { + } +} diff --git a/src/problem/p0871_minimum_number_of_refueling_stops.rs b/src/problem/p0871_minimum_number_of_refueling_stops.rs new file mode 100644 index 00000000..d776bbfc --- /dev/null +++ b/src/problem/p0871_minimum_number_of_refueling_stops.rs @@ -0,0 +1,63 @@ +/** + * [871] Minimum Number of Refueling Stops + * + * A car travels from a starting position to a destination which is target miles east of the starting position. + * There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the i^th gas station is positioni miles east of the starting position and has fueli liters of gas. + * The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. + * Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1. + * Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived. + * + * Example 1: + * + * Input: target = 1, startFuel = 1, stations = [] + * Output: 0 + * Explanation: We can reach the target without refueling. + * + * Example 2: + * + * Input: target = 100, startFuel = 1, stations = [[10,100]] + * Output: -1 + * Explanation: We can not reach the target (or even the first gas station). + * + * Example 3: + * + * Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]] + * Output: 2 + * Explanation: We start with 10 liters of fuel. + * We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas. + * Then, we drive from position 10 to position 60 (expending 50 liters of fuel), + * and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target. + * We made 2 refueling stops along the way, so we return 2. + * + * + * Constraints: + * + * 1 <= target, startFuel <= 10^9 + * 0 <= stations.length <= 500 + * 0 <= positioni <= positioni+1 < target + * 1 <= fueli < 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-number-of-refueling-stops/ +// discuss: https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_refuel_stops(target: i32, start_fuel: i32, stations: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_871() { + } +} diff --git a/src/problem/p0872_leaf_similar_trees.rs b/src/problem/p0872_leaf_similar_trees.rs new file mode 100644 index 00000000..ab5221da --- /dev/null +++ b/src/problem/p0872_leaf_similar_trees.rs @@ -0,0 +1,70 @@ +/** + * [872] Leaf-Similar Trees + * + * Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence. + * + * For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). + * Two binary trees are considered leaf-similar if their leaf value sequence is the same. + * Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. + * + * Example 1: + * + * Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8] + * Output: true + * + * Example 2: + * + * Input: root1 = [1,2,3], root2 = [1,3,2] + * Output: false + * + * + * Constraints: + * + * The number of nodes in each tree will be in the range [1, 200]. + * Both of the given trees will have values in the range [0, 200]. + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/leaf-similar-trees/ +// discuss: https://leetcode.com/problems/leaf-similar-trees/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn leaf_similar(root1: Option>>, root2: Option>>) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_872() { + } +} diff --git a/src/problem/p0874_walking_robot_simulation.rs b/src/problem/p0874_walking_robot_simulation.rs new file mode 100644 index 00000000..54c43f0b --- /dev/null +++ b/src/problem/p0874_walking_robot_simulation.rs @@ -0,0 +1,85 @@ +/** + * [874] Walking Robot Simulation + * + * A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands: + * + * -2: Turn left 90 degrees. + * -1: Turn right 90 degrees. + * 1 <= k <= 9: Move forward k units, one unit at a time. + * + * Some of the grid squares are obstacles. The i^th obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command. + * Return the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5, return 25). + * Note: + * + * North means +Y direction. + * East means +X direction. + * South means -Y direction. + * West means -X direction. + * + * + * Example 1: + * + * Input: commands = [4,-1,3], obstacles = [] + * Output: 25 + * Explanation: The robot starts at (0, 0): + * 1. Move north 4 units to (0, 4). + * 2. Turn right. + * 3. Move east 3 units to (3, 4). + * The furthest point the robot ever gets from the origin is (3, 4), which squared is 3^2 + 4^2 = 25 units away. + * + * Example 2: + * + * Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]] + * Output: 65 + * Explanation: The robot starts at (0, 0): + * 1. Move north 4 units to (0, 4). + * 2. Turn right. + * 3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4). + * 4. Turn left. + * 5. Move north 4 units to (1, 8). + * The furthest point the robot ever gets from the origin is (1, 8), which squared is 1^2 + 8^2 = 65 units away. + * + * Example 3: + * + * Input: commands = [6,-1,-1,6], obstacles = [] + * Output: 36 + * Explanation: The robot starts at (0, 0): + * 1. Move north 6 units to (0, 6). + * 2. Turn right. + * 3. Turn right. + * 4. Move south 6 units to (0, 0). + * The furthest point the robot ever gets from the origin is (0, 6), which squared is 6^2 = 36 units away. + * + * + * Constraints: + * + * 1 <= commands.length <= 10^4 + * commands[i] is either -2, -1, or an integer in the range [1, 9]. + * 0 <= obstacles.length <= 10^4 + * -3 * 10^4 <= xi, yi <= 3 * 10^4 + * The answer is guaranteed to be less than 2^31. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/walking-robot-simulation/ +// discuss: https://leetcode.com/problems/walking-robot-simulation/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn robot_sim(commands: Vec, obstacles: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_874() { + } +} diff --git a/src/problem/p0880_decoded_string_at_index.rs b/src/problem/p0880_decoded_string_at_index.rs new file mode 100644 index 00000000..562dc1d8 --- /dev/null +++ b/src/problem/p0880_decoded_string_at_index.rs @@ -0,0 +1,65 @@ +/** + * [880] Decoded String at Index + * + * You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: + * + * If the character read is a letter, that letter is written onto the tape. + * If the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total. + * + * Given an integer k, return the k^th letter (1-indexed) in the decoded string. + * + * Example 1: + * + * Input: s = "leet2code3", k = 10 + * Output: "o" + * Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode". + * The 10^th letter in the string is "o". + * + * Example 2: + * + * Input: s = "ha22", k = 5 + * Output: "h" + * Explanation: The decoded string is "hahahaha". + * The 5^th letter is "h". + * + * Example 3: + * + * Input: s = "a2345678999999999999999", k = 1 + * Output: "a" + * Explanation: The decoded string is "a" repeated 8301530446056247680 times. + * The 1^st letter is "a". + * + * + * Constraints: + * + * 2 <= s.length <= 100 + * s consists of lowercase English letters and digits 2 through 9. + * s starts with a letter. + * 1 <= k <= 10^9 + * It is guaranteed that k is less than or equal to the length of the decoded string. + * The decoded string is guaranteed to have less than 2^63 letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/decoded-string-at-index/ +// discuss: https://leetcode.com/problems/decoded-string-at-index/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn decode_at_index(s: String, k: i32) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_880() { + } +} diff --git a/src/problem/p0881_boats_to_save_people.rs b/src/problem/p0881_boats_to_save_people.rs new file mode 100644 index 00000000..a48b078b --- /dev/null +++ b/src/problem/p0881_boats_to_save_people.rs @@ -0,0 +1,54 @@ +/** + * [881] Boats to Save People + * + * You are given an array people where people[i] is the weight of the i^th person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. + * Return the minimum number of boats to carry every given person. + * + * Example 1: + * + * Input: people = [1,2], limit = 3 + * Output: 1 + * Explanation: 1 boat (1, 2) + * + * Example 2: + * + * Input: people = [3,2,2,1], limit = 3 + * Output: 3 + * Explanation: 3 boats (1, 2), (2) and (3) + * + * Example 3: + * + * Input: people = [3,5,3,4], limit = 5 + * Output: 4 + * Explanation: 4 boats (3), (3), (4), (5) + * + * + * Constraints: + * + * 1 <= people.length <= 5 * 10^4 + * 1 <= people[i] <= limit <= 3 * 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/boats-to-save-people/ +// discuss: https://leetcode.com/problems/boats-to-save-people/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_rescue_boats(people: Vec, limit: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_881() { + } +} diff --git a/src/problem/p0882_reachable_nodes_in_subdivided_graph.rs b/src/problem/p0882_reachable_nodes_in_subdivided_graph.rs new file mode 100644 index 00000000..6f3f4e41 --- /dev/null +++ b/src/problem/p0882_reachable_nodes_in_subdivided_graph.rs @@ -0,0 +1,62 @@ +/** + * [882] Reachable Nodes In Subdivided Graph + * + * You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. + * The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge. + * To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi]. + * In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less. + * Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph. + * + * Example 1: + * + * Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3 + * Output: 13 + * Explanation: The edge subdivisions are shown in the image above. + * The nodes that are reachable are highlighted in yellow. + * + * Example 2: + * + * Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4 + * Output: 23 + * + * Example 3: + * + * Input: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5 + * Output: 1 + * Explanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable. + * + * + * Constraints: + * + * 0 <= edges.length <= min(n * (n - 1) / 2, 10^4) + * edges[i].length == 3 + * 0 <= ui < vi < n + * There are no multiple edges in the graph. + * 0 <= cnti <= 10^4 + * 0 <= maxMoves <= 10^9 + * 1 <= n <= 3000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/ +// discuss: https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn reachable_nodes(edges: Vec>, max_moves: i32, n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_882() { + } +} diff --git a/src/problem/p0885_spiral_matrix_iii.rs b/src/problem/p0885_spiral_matrix_iii.rs new file mode 100644 index 00000000..b40f1b85 --- /dev/null +++ b/src/problem/p0885_spiral_matrix_iii.rs @@ -0,0 +1,48 @@ +/** + * [885] Spiral Matrix III + * + * You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. + * You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid. + * Return an array of coordinates representing the positions of the grid in the order you visited them. + * + * Example 1: + * + * Input: rows = 1, cols = 4, rStart = 0, cStart = 0 + * Output: [[0,0],[0,1],[0,2],[0,3]] + * + * Example 2: + * + * Input: rows = 5, cols = 6, rStart = 1, cStart = 4 + * Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]] + * + * + * Constraints: + * + * 1 <= rows, cols <= 100 + * 0 <= rStart < rows + * 0 <= cStart < cols + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/spiral-matrix-iii/ +// discuss: https://leetcode.com/problems/spiral-matrix-iii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn spiral_matrix_iii(rows: i32, cols: i32, r_start: i32, c_start: i32) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_885() { + } +} diff --git a/src/problem/p0886_possible_bipartition.rs b/src/problem/p0886_possible_bipartition.rs new file mode 100644 index 00000000..c2e0cd50 --- /dev/null +++ b/src/problem/p0886_possible_bipartition.rs @@ -0,0 +1,56 @@ +/** + * [886] Possible Bipartition + * + * We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group. + * Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way. + * + * Example 1: + * + * Input: n = 4, dislikes = [[1,2],[1,3],[2,4]] + * Output: true + * Explanation: group1 [1,4] and group2 [2,3]. + * + * Example 2: + * + * Input: n = 3, dislikes = [[1,2],[1,3],[2,3]] + * Output: false + * + * Example 3: + * + * Input: n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]] + * Output: false + * + * + * Constraints: + * + * 1 <= n <= 2000 + * 0 <= dislikes.length <= 10^4 + * dislikes[i].length == 2 + * 1 <= dislikes[i][j] <= n + * ai < bi + * All the pairs of dislikes are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/possible-bipartition/ +// discuss: https://leetcode.com/problems/possible-bipartition/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn possible_bipartition(n: i32, dislikes: Vec>) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_886() { + } +} diff --git a/src/problem/p0887_super_egg_drop.rs b/src/problem/p0887_super_egg_drop.rs new file mode 100644 index 00000000..d10fd77c --- /dev/null +++ b/src/problem/p0887_super_egg_drop.rs @@ -0,0 +1,58 @@ +/** + * [887] Super Egg Drop + * + * You are given k identical eggs and you have access to a building with n floors labeled from 1 to n. + * You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. + * Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. + * Return the minimum number of moves that you need to determine with certainty what the value of f is. + * + * Example 1: + * + * Input: k = 1, n = 2 + * Output: 2 + * Explanation: + * Drop the egg from floor 1. If it breaks, we know that f = 0. + * Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. + * If it does not break, then we know f = 2. + * Hence, we need at minimum 2 moves to determine with certainty what the value of f is. + * + * Example 2: + * + * Input: k = 2, n = 6 + * Output: 3 + * + * Example 3: + * + * Input: k = 3, n = 14 + * Output: 4 + * + * + * Constraints: + * + * 1 <= k <= 100 + * 1 <= n <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/super-egg-drop/ +// discuss: https://leetcode.com/problems/super-egg-drop/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn super_egg_drop(k: i32, n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_887() { + } +} diff --git a/src/problem/p0888_fair_candy_swap.rs b/src/problem/p0888_fair_candy_swap.rs new file mode 100644 index 00000000..dd047c02 --- /dev/null +++ b/src/problem/p0888_fair_candy_swap.rs @@ -0,0 +1,54 @@ +/** + * [888] Fair Candy Swap + * + * Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the i^th box of candy that Alice has and bobSizes[j] is the number of candies of the j^th box of candy that Bob has. + * Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. + * Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists. + * + * Example 1: + * + * Input: aliceSizes = [1,1], bobSizes = [2,2] + * Output: [1,2] + * + * Example 2: + * + * Input: aliceSizes = [1,2], bobSizes = [2,3] + * Output: [1,2] + * + * Example 3: + * + * Input: aliceSizes = [2], bobSizes = [1,3] + * Output: [2,3] + * + * + * Constraints: + * + * 1 <= aliceSizes.length, bobSizes.length <= 10^4 + * 1 <= aliceSizes[i], bobSizes[j] <= 10^5 + * Alice and Bob have a different total number of candies. + * There will be at least one valid answer for the given input. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/fair-candy-swap/ +// discuss: https://leetcode.com/problems/fair-candy-swap/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn fair_candy_swap(alice_sizes: Vec, bob_sizes: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_888() { + } +} diff --git a/src/problem/p0901_online_stock_span.rs b/src/problem/p0901_online_stock_span.rs new file mode 100644 index 00000000..2b94de24 --- /dev/null +++ b/src/problem/p0901_online_stock_span.rs @@ -0,0 +1,81 @@ +/** + * [901] Online Stock Span + * + * Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day. + * The span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price. + * + * For example, if the price of a stock over the next 7 days were [100,80,60,70,60,75,85], then the stock spans would be [1,1,1,2,1,4,6]. + * + * Implement the StockSpanner class: + * + * StockSpanner() Initializes the object of the class. + * int next(int price) Returns the span of the stock's price given that today's price is price. + * + * + * Example 1: + * + * Input + * ["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] + * [[], [100], [80], [60], [70], [60], [75], [85]] + * Output + * [null, 1, 1, 1, 2, 1, 4, 6] + * Explanation + * StockSpanner stockSpanner = new StockSpanner(); + * stockSpanner.next(100); // return 1 + * stockSpanner.next(80); // return 1 + * stockSpanner.next(60); // return 1 + * stockSpanner.next(70); // return 2 + * stockSpanner.next(60); // return 1 + * stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. + * stockSpanner.next(85); // return 6 + * + * + * Constraints: + * + * 1 <= price <= 10^5 + * At most 10^4 calls will be made to next. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/online-stock-span/ +// discuss: https://leetcode.com/problems/online-stock-span/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct StockSpanner { + vec![] + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl StockSpanner { + + fn new() -> Self { + + } + + fn next(&self, price: i32) -> i32 { + + } +} + +/** + * Your StockSpanner object will be instantiated and called as such: + * let obj = StockSpanner::new(); + * let ret_1: i32 = obj.next(price); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_901() { + } +} diff --git a/src/problem/p0904_fruit_into_baskets.rs b/src/problem/p0904_fruit_into_baskets.rs new file mode 100644 index 00000000..1494c5ca --- /dev/null +++ b/src/problem/p0904_fruit_into_baskets.rs @@ -0,0 +1,62 @@ +/** + * [904] Fruit Into Baskets + * + * You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the i^th tree produces. + * You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: + * + * You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold. + * Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. + * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. + * + * Given the integer array fruits, return the maximum number of fruits you can pick. + * + * Example 1: + * + * Input: fruits = [1,2,1] + * Output: 3 + * Explanation: We can pick from all 3 trees. + * + * Example 2: + * + * Input: fruits = [0,1,2,2] + * Output: 3 + * Explanation: We can pick from trees [1,2,2]. + * If we had started at the first tree, we would only pick from trees [0,1]. + * + * Example 3: + * + * Input: fruits = [1,2,3,2,2] + * Output: 4 + * Explanation: We can pick from trees [2,3,2,2]. + * If we had started at the first tree, we would only pick from trees [1,2]. + * + * + * Constraints: + * + * 1 <= fruits.length <= 10^5 + * 0 <= fruits[i] < fruits.length + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/fruit-into-baskets/ +// discuss: https://leetcode.com/problems/fruit-into-baskets/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn total_fruit(fruits: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_904() { + } +} diff --git a/src/problem/p0905_sort_array_by_parity.rs b/src/problem/p0905_sort_array_by_parity.rs new file mode 100644 index 00000000..8affba98 --- /dev/null +++ b/src/problem/p0905_sort_array_by_parity.rs @@ -0,0 +1,47 @@ +/** + * [905] Sort Array By Parity + * + * Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. + * Return any array that satisfies this condition. + * + * Example 1: + * + * Input: nums = [3,1,2,4] + * Output: [2,4,3,1] + * Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. + * + * Example 2: + * + * Input: nums = [0] + * Output: [0] + * + * + * Constraints: + * + * 1 <= nums.length <= 5000 + * 0 <= nums[i] <= 5000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/sort-array-by-parity/ +// discuss: https://leetcode.com/problems/sort-array-by-parity/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn sort_array_by_parity(nums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_905() { + } +} diff --git a/src/problem/p0907_sum_of_subarray_minimums.rs b/src/problem/p0907_sum_of_subarray_minimums.rs new file mode 100644 index 00000000..7cf208e8 --- /dev/null +++ b/src/problem/p0907_sum_of_subarray_minimums.rs @@ -0,0 +1,49 @@ +/** + * [907] Sum of Subarray Minimums + * + * Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 10^9 + 7. + * + * Example 1: + * + * Input: arr = [3,1,2,4] + * Output: 17 + * Explanation: + * Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. + * Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. + * Sum is 17. + * + * Example 2: + * + * Input: arr = [11,81,94,43,3] + * Output: 444 + * + * + * Constraints: + * + * 1 <= arr.length <= 3 * 10^4 + * 1 <= arr[i] <= 3 * 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/sum-of-subarray-minimums/ +// discuss: https://leetcode.com/problems/sum-of-subarray-minimums/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn sum_subarray_mins(arr: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_907() { + } +} diff --git a/src/problem/p0912_sort_an_array.rs b/src/problem/p0912_sort_an_array.rs new file mode 100644 index 00000000..c1b3aafa --- /dev/null +++ b/src/problem/p0912_sort_an_array.rs @@ -0,0 +1,41 @@ +/** + * [912] Sort an Array + * + * Given an array of integers nums, sort the array in ascending order. + * + * Example 1: + * Input: nums = [5,2,3,1] + * Output: [1,2,3,5] + * Example 2: + * Input: nums = [5,1,1,2,0,0] + * Output: [0,0,1,1,2,5] + * + * Constraints: + * + * 1 <= nums.length <= 5 * 10^4 + * -5 * 10^4 <= nums[i] <= 5 * 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/sort-an-array/ +// discuss: https://leetcode.com/problems/sort-an-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn sort_array(nums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_912() { + } +} diff --git a/src/problem/p0917_reverse_only_letters.rs b/src/problem/p0917_reverse_only_letters.rs new file mode 100644 index 00000000..ff5596b0 --- /dev/null +++ b/src/problem/p0917_reverse_only_letters.rs @@ -0,0 +1,50 @@ +/** + * [917] Reverse Only Letters + * + * Given a string s, reverse the string according to the following rules: + * + * All the characters that are not English letters remain in the same position. + * All the English letters (lowercase or uppercase) should be reversed. + * + * Return s after reversing it. + * + * Example 1: + * Input: s = "ab-cd" + * Output: "dc-ba" + * Example 2: + * Input: s = "a-bC-dEf-ghIj" + * Output: "j-Ih-gfE-dCba" + * Example 3: + * Input: s = "Test1ng-Leet=code-Q!" + * Output: "Qedo1ct-eeLg=ntse-T!" + * + * Constraints: + * + * 1 <= s.length <= 100 + * s consists of characters with ASCII values in the range [33, 122]. + * s does not contain '\"' or '\\'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/reverse-only-letters/ +// discuss: https://leetcode.com/problems/reverse-only-letters/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn reverse_only_letters(s: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_917() { + } +} diff --git a/src/problem/p0921_minimum_add_to_make_parentheses_valid.rs b/src/problem/p0921_minimum_add_to_make_parentheses_valid.rs new file mode 100644 index 00000000..f98160c4 --- /dev/null +++ b/src/problem/p0921_minimum_add_to_make_parentheses_valid.rs @@ -0,0 +1,55 @@ +/** + * [921] Minimum Add to Make Parentheses Valid + * + * A parentheses string is valid if and only if: + * + * It is the empty string, + * It can be written as AB (A concatenated with B), where A and B are valid strings, or + * It can be written as (A), where A is a valid string. + * + * You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string. + * + * For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))". + * + * Return the minimum number of moves required to make s valid. + * + * Example 1: + * + * Input: s = "())" + * Output: 1 + * + * Example 2: + * + * Input: s = "(((" + * Output: 3 + * + * + * Constraints: + * + * 1 <= s.length <= 1000 + * s[i] is either '(' or ')'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ +// discuss: https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_add_to_make_valid(s: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_921() { + } +} diff --git a/src/problem/p0923_3sum_with_multiplicity.rs b/src/problem/p0923_3sum_with_multiplicity.rs new file mode 100644 index 00000000..f373e285 --- /dev/null +++ b/src/problem/p0923_3sum_with_multiplicity.rs @@ -0,0 +1,63 @@ +/** + * [923] 3Sum With Multiplicity + * + * Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target. + * As the answer can be very large, return it modulo 10^9 + 7. + * + * Example 1: + * + * Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8 + * Output: 20 + * Explanation: + * Enumerating by the values (arr[i], arr[j], arr[k]): + * (1, 2, 5) occurs 8 times; + * (1, 3, 4) occurs 8 times; + * (2, 2, 4) occurs 2 times; + * (2, 3, 3) occurs 2 times. + * + * Example 2: + * + * Input: arr = [1,1,2,2,2,2], target = 5 + * Output: 12 + * Explanation: + * arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times: + * We choose one 1 from [1,1] in 2 ways, + * and two 2s from [2,2,2,2] in 6 ways. + * + * Example 3: + * + * Input: arr = [2,1,3], target = 6 + * Output: 1 + * Explanation: (1, 2, 3) occured one time in the array so we return 1. + * + * + * Constraints: + * + * 3 <= arr.length <= 3000 + * 0 <= arr[i] <= 100 + * 0 <= target <= 300 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/3sum-with-multiplicity/ +// discuss: https://leetcode.com/problems/3sum-with-multiplicity/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn three_sum_multi(arr: Vec, target: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_923() { + } +} diff --git a/src/problem/p0927_three_equal_parts.rs b/src/problem/p0927_three_equal_parts.rs new file mode 100644 index 00000000..32e5c0f1 --- /dev/null +++ b/src/problem/p0927_three_equal_parts.rs @@ -0,0 +1,53 @@ +/** + * [927] Three Equal Parts + * + * You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. + * If it is possible, return any [i, j] with i + 1 < j, such that: + * + * arr[0], arr[1], ..., arr[i] is the first part, + * arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and + * arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part. + * All three parts have equal binary values. + * + * If it is not possible, return [-1, -1]. + * Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value. + * + * Example 1: + * Input: arr = [1,0,1,0,1] + * Output: [0,3] + * Example 2: + * Input: arr = [1,1,0,1,1] + * Output: [-1,-1] + * Example 3: + * Input: arr = [1,1,0,0,1] + * Output: [0,2] + * + * Constraints: + * + * 3 <= arr.length <= 3 * 10^4 + * arr[i] is 0 or 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/three-equal-parts/ +// discuss: https://leetcode.com/problems/three-equal-parts/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn three_equal_parts(arr: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_927() { + } +} diff --git a/src/problem/p0933_number_of_recent_calls.rs b/src/problem/p0933_number_of_recent_calls.rs new file mode 100644 index 00000000..3e5ebba9 --- /dev/null +++ b/src/problem/p0933_number_of_recent_calls.rs @@ -0,0 +1,76 @@ +/** + * [933] Number of Recent Calls + * + * You have a RecentCounter class which counts the number of recent requests within a certain time frame. + * Implement the RecentCounter class: + * + * RecentCounter() Initializes the counter with zero recent requests. + * int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t]. + * + * It is guaranteed that every call to ping uses a strictly larger value of t than the previous call. + * + * Example 1: + * + * Input + * ["RecentCounter", "ping", "ping", "ping", "ping"] + * [[], [1], [100], [3001], [3002]] + * Output + * [null, 1, 2, 3, 3] + * Explanation + * RecentCounter recentCounter = new RecentCounter(); + * recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1 + * recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2 + * recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3 + * recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3 + * + * + * Constraints: + * + * 1 <= t <= 10^9 + * Each test case will call ping with strictly increasing values of t. + * At most 10^4 calls will be made to ping. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-recent-calls/ +// discuss: https://leetcode.com/problems/number-of-recent-calls/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct RecentCounter { + vec![] + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl RecentCounter { + + fn new() -> Self { + + } + + fn ping(&self, t: i32) -> i32 { + + } +} + +/** + * Your RecentCounter object will be instantiated and called as such: + * let obj = RecentCounter::new(); + * let ret_1: i32 = obj.ping(t); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_933() { + } +} diff --git a/src/problem/p0941_valid_mountain_array.rs b/src/problem/p0941_valid_mountain_array.rs new file mode 100644 index 00000000..f2d084e0 --- /dev/null +++ b/src/problem/p0941_valid_mountain_array.rs @@ -0,0 +1,54 @@ +/** + * [941] Valid Mountain Array + * + * Given an array of integers arr, return true if and only if it is a valid mountain array. + * Recall that arr is a mountain array if and only if: + * + * arr.length >= 3 + * There exists some i with 0 < i < arr.length - 1 such that: + * + * arr[0] < arr[1] < ... < arr[i - 1] < arr[i] + * arr[i] > arr[i + 1] > ... > arr[arr.length - 1] + * + * + * + * + * Example 1: + * Input: arr = [2,1] + * Output: false + * Example 2: + * Input: arr = [3,5,5] + * Output: false + * Example 3: + * Input: arr = [0,3,2,1] + * Output: true + * + * Constraints: + * + * 1 <= arr.length <= 10^4 + * 0 <= arr[i] <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/valid-mountain-array/ +// discuss: https://leetcode.com/problems/valid-mountain-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn valid_mountain_array(arr: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_941() { + } +} diff --git a/src/problem/p0942_di_string_match.rs b/src/problem/p0942_di_string_match.rs new file mode 100644 index 00000000..05caffa7 --- /dev/null +++ b/src/problem/p0942_di_string_match.rs @@ -0,0 +1,49 @@ +/** + * [942] DI String Match + * + * A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: + * + * s[i] == 'I' if perm[i] < perm[i + 1], and + * s[i] == 'D' if perm[i] > perm[i + 1]. + * + * Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them. + * + * Example 1: + * Input: s = "IDID" + * Output: [0,4,1,3,2] + * Example 2: + * Input: s = "III" + * Output: [0,1,2,3] + * Example 3: + * Input: s = "DDI" + * Output: [3,2,0,1] + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s[i] is either 'I' or 'D'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/di-string-match/ +// discuss: https://leetcode.com/problems/di-string-match/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn di_string_match(s: String) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_942() { + } +} diff --git a/src/problem/p0943_find_the_shortest_superstring.rs b/src/problem/p0943_find_the_shortest_superstring.rs new file mode 100644 index 00000000..0dfcd587 --- /dev/null +++ b/src/problem/p0943_find_the_shortest_superstring.rs @@ -0,0 +1,49 @@ +/** + * [943] Find the Shortest Superstring + * + * Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them. + * You may assume that no string in words is a substring of another string in words. + * + * Example 1: + * + * Input: words = ["alex","loves","leetcode"] + * Output: "alexlovesleetcode" + * Explanation: All permutations of "alex","loves","leetcode" would also be accepted. + * + * Example 2: + * + * Input: words = ["catg","ctaagt","gcta","ttca","atgcatc"] + * Output: "gctaagttcatgcatc" + * + * + * Constraints: + * + * 1 <= words.length <= 12 + * 1 <= words[i].length <= 20 + * words[i] consists of lowercase English letters. + * All the strings of words are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-the-shortest-superstring/ +// discuss: https://leetcode.com/problems/find-the-shortest-superstring/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn shortest_superstring(words: Vec) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_943() { + } +} diff --git a/src/problem/p0944_delete_columns_to_make_sorted.rs b/src/problem/p0944_delete_columns_to_make_sorted.rs new file mode 100644 index 00000000..71703190 --- /dev/null +++ b/src/problem/p0944_delete_columns_to_make_sorted.rs @@ -0,0 +1,74 @@ +/** + * [944] Delete Columns to Make Sorted + * + * You are given an array of n strings strs, all of the same length. + * The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as: + * + * abc + * bce + * cae + * + * You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1. + * Return the number of columns that you will delete. + * + * Example 1: + * + * Input: strs = ["cba","daf","ghi"] + * Output: 1 + * Explanation: The grid looks as follows: + * cba + * daf + * ghi + * Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. + * + * Example 2: + * + * Input: strs = ["a","b"] + * Output: 0 + * Explanation: The grid looks as follows: + * a + * b + * Column 0 is the only column and is sorted, so you will not delete any columns. + * + * Example 3: + * + * Input: strs = ["zyx","wvu","tsr"] + * Output: 3 + * Explanation: The grid looks as follows: + * zyx + * wvu + * tsr + * All 3 columns are not sorted, so you will delete all 3. + * + * + * Constraints: + * + * n == strs.length + * 1 <= n <= 100 + * 1 <= strs[i].length <= 1000 + * strs[i] consists of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/delete-columns-to-make-sorted/ +// discuss: https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_deletion_size(strs: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_944() { + } +} diff --git a/src/problem/p0948_bag_of_tokens.rs b/src/problem/p0948_bag_of_tokens.rs new file mode 100644 index 00000000..0f779d71 --- /dev/null +++ b/src/problem/p0948_bag_of_tokens.rs @@ -0,0 +1,65 @@ +/** + * [948] Bag of Tokens + * + * You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the i^th token (0-indexed). + * Your goal is to maximize your total score by potentially playing each token in one of two ways: + * + * If your current power is at least tokens[i], you may play the i^th token face up, losing tokens[i] power and gaining 1 score. + * If your current score is at least 1, you may play the i^th token face down, gaining tokens[i] power and losing 1 score. + * + * Each token may be played at most once and in any order. You do not have to play all the tokens. + * Return the largest possible score you can achieve after playing any number of tokens. + * + * Example 1: + * + * Input: tokens = [100], power = 50 + * Output: 0 + * Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score. + * + * Example 2: + * + * Input: tokens = [100,200], power = 150 + * Output: 1 + * Explanation: Play the 0^th token (100) face up, your power becomes 50 and score becomes 1. + * There is no need to play the 1^st token since you cannot play it face up to add to your score. + * + * Example 3: + * + * Input: tokens = [100,200,300,400], power = 200 + * Output: 2 + * Explanation: Play the tokens in this order to get a score of 2: + * 1. Play the 0^th token (100) face up, your power becomes 100 and score becomes 1. + * 2. Play the 3^rd token (400) face down, your power becomes 500 and score becomes 0. + * 3. Play the 1^st token (200) face up, your power becomes 300 and score becomes 1. + * 4. Play the 2^nd token (300) face up, your power becomes 0 and score becomes 2. + * + * + * Constraints: + * + * 0 <= tokens.length <= 1000 + * 0 <= tokens[i], power < 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/bag-of-tokens/ +// discuss: https://leetcode.com/problems/bag-of-tokens/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn bag_of_tokens_score(tokens: Vec, power: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_948() { + } +} diff --git a/src/problem/p0949_largest_time_for_given_digits.rs b/src/problem/p0949_largest_time_for_given_digits.rs new file mode 100644 index 00000000..86207838 --- /dev/null +++ b/src/problem/p0949_largest_time_for_given_digits.rs @@ -0,0 +1,49 @@ +/** + * [949] Largest Time for Given Digits + * + * Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once. + * 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. + * Return the latest 24-hour time in "HH:MM" format. If no valid time can be made, return an empty string. + * + * Example 1: + * + * Input: arr = [1,2,3,4] + * Output: "23:41" + * Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest. + * + * Example 2: + * + * Input: arr = [5,5,5,5] + * Output: "" + * Explanation: There are no valid 24-hour times as "55:55" is not valid. + * + * + * Constraints: + * + * arr.length == 4 + * 0 <= arr[i] <= 9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/largest-time-for-given-digits/ +// discuss: https://leetcode.com/problems/largest-time-for-given-digits/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn largest_time_from_digits(arr: Vec) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_949() { + } +} diff --git a/src/problem/p0954_array_of_doubled_pairs.rs b/src/problem/p0954_array_of_doubled_pairs.rs new file mode 100644 index 00000000..07bc5d5c --- /dev/null +++ b/src/problem/p0954_array_of_doubled_pairs.rs @@ -0,0 +1,52 @@ +/** + * [954] Array of Doubled Pairs + * + * Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise. + * + * Example 1: + * + * Input: arr = [3,1,3,6] + * Output: false + * + * Example 2: + * + * Input: arr = [2,1,2,6] + * Output: false + * + * Example 3: + * + * Input: arr = [4,-2,2,-4] + * Output: true + * Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4]. + * + * + * Constraints: + * + * 2 <= arr.length <= 3 * 10^4 + * arr.length is even. + * -10^5 <= arr[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/array-of-doubled-pairs/ +// discuss: https://leetcode.com/problems/array-of-doubled-pairs/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn can_reorder_doubled(arr: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_954() { + } +} diff --git a/src/problem/p0955_delete_columns_to_make_sorted_ii.rs b/src/problem/p0955_delete_columns_to_make_sorted_ii.rs new file mode 100644 index 00000000..81433b64 --- /dev/null +++ b/src/problem/p0955_delete_columns_to_make_sorted_ii.rs @@ -0,0 +1,64 @@ +/** + * [955] Delete Columns to Make Sorted II + * + * You are given an array of n strings strs, all of the same length. + * We may choose any deletion indices, and we delete all the characters in those indices for each string. + * For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"]. + * Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length. + * + * Example 1: + * + * Input: strs = ["ca","bb","ac"] + * Output: 1 + * Explanation: + * After deleting the first column, strs = ["a", "b", "c"]. + * Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]). + * We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1. + * + * Example 2: + * + * Input: strs = ["xc","yb","za"] + * Output: 0 + * Explanation: + * strs is already in lexicographic order, so we do not need to delete anything. + * Note that the rows of strs are not necessarily in lexicographic order: + * i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...) + * + * Example 3: + * + * Input: strs = ["zyx","wvu","tsr"] + * Output: 3 + * Explanation: We have to delete every column. + * + * + * Constraints: + * + * n == strs.length + * 1 <= n <= 100 + * 1 <= strs[i].length <= 100 + * strs[i] consists of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/delete-columns-to-make-sorted-ii/ +// discuss: https://leetcode.com/problems/delete-columns-to-make-sorted-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_deletion_size(strs: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_955() { + } +} diff --git a/src/problem/p0961_n_repeated_element_in_size_2n_array.rs b/src/problem/p0961_n_repeated_element_in_size_2n_array.rs new file mode 100644 index 00000000..018c1e46 --- /dev/null +++ b/src/problem/p0961_n_repeated_element_in_size_2n_array.rs @@ -0,0 +1,52 @@ +/** + * [961] N-Repeated Element in Size 2N Array + * + * You are given an integer array nums with the following properties: + * + * nums.length == 2 * n. + * nums contains n + 1 unique elements. + * Exactly one element of nums is repeated n times. + * + * Return the element that is repeated n times. + * + * Example 1: + * Input: nums = [1,2,3,3] + * Output: 3 + * Example 2: + * Input: nums = [2,1,2,5,3,2] + * Output: 2 + * Example 3: + * Input: nums = [5,1,5,2,5,3,5,4] + * Output: 5 + * + * Constraints: + * + * 2 <= n <= 5000 + * nums.length == 2 * n + * 0 <= nums[i] <= 10^4 + * nums contains n + 1 unique elements and one of them is repeated exactly n times. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ +// discuss: https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn repeated_n_times(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_961() { + } +} diff --git a/src/problem/p0966_vowel_spellchecker.rs b/src/problem/p0966_vowel_spellchecker.rs new file mode 100644 index 00000000..96594d88 --- /dev/null +++ b/src/problem/p0966_vowel_spellchecker.rs @@ -0,0 +1,67 @@ +/** + * [966] Vowel Spellchecker + * + * Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. + * For a given query word, the spell checker handles two categories of spelling mistakes: + * + * Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist. + * + * Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow" + * Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow" + * Example: wordlist = ["yellow"], query = "yellow": correct = "yellow" + * + * + * Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist. + * + * Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw" + * Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match) + * Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match) + * + * + * + * In addition, the spell checker operates under the following precedence rules: + * + * When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back. + * When the query matches a word up to capitlization, you should return the first such match in the wordlist. + * When the query matches a word up to vowel errors, you should return the first such match in the wordlist. + * If the query has no matches in the wordlist, you should return the empty string. + * + * Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i]. + * + * Example 1: + * Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"] + * Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"] + * Example 2: + * Input: wordlist = ["yellow"], queries = ["YellOw"] + * Output: ["yellow"] + * + * Constraints: + * + * 1 <= wordlist.length, queries.length <= 5000 + * 1 <= wordlist[i].length, queries[i].length <= 7 + * wordlist[i] and queries[i] consist only of only English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/vowel-spellchecker/ +// discuss: https://leetcode.com/problems/vowel-spellchecker/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn spellchecker(wordlist: Vec, queries: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_966() { + } +} diff --git a/src/problem/p0975_odd_even_jump.rs b/src/problem/p0975_odd_even_jump.rs new file mode 100644 index 00000000..56b7d12c --- /dev/null +++ b/src/problem/p0975_odd_even_jump.rs @@ -0,0 +1,79 @@ +/** + * [975] Odd Even Jump + * + * You are given an integer array arr. From some starting index, you can make a series of jumps. The (1^st, 3^rd, 5^th, ...) jumps in the series are called odd-numbered jumps, and the (2^nd, 4^th, 6^th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices. + * You may jump forward from index i to index j (with i < j) in the following way: + * + * During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j, you can only jump to the smallest such index j. + * During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j, you can only jump to the smallest such index j. + * It may be the case that for some index i, there are no legal jumps. + * + * A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once). + * Return the number of good starting indices. + * + * Example 1: + * + * Input: arr = [10,13,12,14,15] + * Output: 2 + * Explanation: + * From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more. + * From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more. + * From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end. + * From starting index i = 4, we have reached the end already. + * In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of + * jumps. + * + * Example 2: + * + * Input: arr = [2,3,1,1,4] + * Output: 3 + * Explanation: + * From starting index i = 0, we make jumps to i = 1, i = 2, i = 3: + * During our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0]. + * During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3 + * During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2]. + * We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good. + * In a similar manner, we can deduce that: + * From starting index i = 1, we jump to i = 4, so we reach the end. + * From starting index i = 2, we jump to i = 3, and then we can't jump anymore. + * From starting index i = 3, we jump to i = 4, so we reach the end. + * From starting index i = 4, we are already at the end. + * In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some + * number of jumps. + * + * Example 3: + * + * Input: arr = [5,1,3,4,2] + * Output: 3 + * Explanation: We can reach the end from starting indices 1, 2, and 4. + * + * + * Constraints: + * + * 1 <= arr.length <= 2 * 10^4 + * 0 <= arr[i] < 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/odd-even-jump/ +// discuss: https://leetcode.com/problems/odd-even-jump/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn odd_even_jumps(arr: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_975() { + } +} diff --git a/src/problem/p0981_time_based_key_value_store.rs b/src/problem/p0981_time_based_key_value_store.rs new file mode 100644 index 00000000..fe03ae54 --- /dev/null +++ b/src/problem/p0981_time_based_key_value_store.rs @@ -0,0 +1,85 @@ +/** + * [981] Time Based Key-Value Store + * + * Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. + * Implement the TimeMap class: + * + * TimeMap() Initializes the object of the data structure. + * void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp. + * String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "". + * + * + * Example 1: + * + * Input + * ["TimeMap", "set", "get", "get", "set", "get", "get"] + * [[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]] + * Output + * [null, null, "bar", "bar", null, "bar2", "bar2"] + * Explanation + * TimeMap timeMap = new TimeMap(); + * timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1. + * timeMap.get("foo", 1); // return "bar" + * timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar". + * timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4. + * timeMap.get("foo", 4); // return "bar2" + * timeMap.get("foo", 5); // return "bar2" + * + * + * Constraints: + * + * 1 <= key.length, value.length <= 100 + * key and value consist of lowercase English letters and digits. + * 1 <= timestamp <= 10^7 + * All the timestamps timestamp of set are strictly increasing. + * At most 2 * 10^5 calls will be made to set and get. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/time-based-key-value-store/ +// discuss: https://leetcode.com/problems/time-based-key-value-store/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct TimeMap { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl TimeMap { + + fn new() -> Self { + + } + + fn set(&self, key: String, value: String, timestamp: i32) { + + } + + fn get(&self, key: String, timestamp: i32) -> String { + + } +} + +/** + * Your TimeMap object will be instantiated and called as such: + * let obj = TimeMap::new(); + * obj.set(key, value, timestamp); + * let ret_2: String = obj.get(key, timestamp); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_981() { + } +} diff --git a/src/problem/p0991_broken_calculator.rs b/src/problem/p0991_broken_calculator.rs new file mode 100644 index 00000000..dd701e11 --- /dev/null +++ b/src/problem/p0991_broken_calculator.rs @@ -0,0 +1,57 @@ +/** + * [991] Broken Calculator + * + * There is a broken calculator that has the integer startValue on its display initially. In one operation, you can: + * + * multiply the number on display by 2, or + * subtract 1 from the number on display. + * + * Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator. + * + * Example 1: + * + * Input: startValue = 2, target = 3 + * Output: 2 + * Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}. + * + * Example 2: + * + * Input: startValue = 5, target = 8 + * Output: 2 + * Explanation: Use decrement and then double {5 -> 4 -> 8}. + * + * Example 3: + * + * Input: startValue = 3, target = 10 + * Output: 3 + * Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}. + * + * + * Constraints: + * + * 1 <= startValue, target <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/broken-calculator/ +// discuss: https://leetcode.com/problems/broken-calculator/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn broken_calc(start_value: i32, target: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_991() { + } +} diff --git a/src/problem/p0997_find_the_town_judge.rs b/src/problem/p0997_find_the_town_judge.rs new file mode 100644 index 00000000..7ecb6b6e --- /dev/null +++ b/src/problem/p0997_find_the_town_judge.rs @@ -0,0 +1,62 @@ +/** + * [997] Find the Town Judge + * + * In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge. + * If the town judge exists, then: + *
    + * The town judge trusts nobody. + * Everybody (except for the town judge) trusts the town judge. + * There is exactly one person that satisfies properties 1 and 2. + *
+ * You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi. + * Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise. + * + * Example 1: + * + * Input: n = 2, trust = [[1,2]] + * Output: 2 + * + * Example 2: + * + * Input: n = 3, trust = [[1,3],[2,3]] + * Output: 3 + * + * Example 3: + * + * Input: n = 3, trust = [[1,3],[2,3],[3,1]] + * Output: -1 + * + * + * Constraints: + * + * 1 <= n <= 1000 + * 0 <= trust.length <= 10^4 + * trust[i].length == 2 + * All the pairs of trust are unique. + * ai != bi + * 1 <= ai, bi <= n + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-the-town-judge/ +// discuss: https://leetcode.com/problems/find-the-town-judge/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_judge(n: i32, trust: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_997() { + } +} diff --git a/src/problem/p1001_grid_illumination.rs b/src/problem/p1001_grid_illumination.rs new file mode 100644 index 00000000..2bc046b1 --- /dev/null +++ b/src/problem/p1001_grid_illumination.rs @@ -0,0 +1,64 @@ +/** + * [1001] Grid Illumination + * + * There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off. + * You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on. + * When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal. + * You are also given another 2D array queries, where queries[j] = [rowj, colj]. For the j^th query, determine whether grid[rowj][colj] is illuminated or not. After answering the j^th query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj]. + * Return an array of integers ans, where ans[j] should be 1 if the cell in the j^th query was illuminated, or 0 if the lamp was not. + * + * Example 1: + * + * Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]] + * Output: [1,0] + * Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4]. + * The 0^th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square. + * + * The 1^st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle. + * + * + * Example 2: + * + * Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]] + * Output: [1,1] + * + * Example 3: + * + * Input: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]] + * Output: [1,1,0] + * + * + * Constraints: + * + * 1 <= n <= 10^9 + * 0 <= lamps.length <= 20000 + * 0 <= queries.length <= 20000 + * lamps[i].length == 2 + * 0 <= rowi, coli < n + * queries[j].length == 2 + * 0 <= rowj, colj < n + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/grid-illumination/ +// discuss: https://leetcode.com/problems/grid-illumination/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn grid_illumination(n: i32, lamps: Vec>, queries: Vec>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1001() { + } +} diff --git a/src/problem/p1018_binary_prefix_divisible_by_5.rs b/src/problem/p1018_binary_prefix_divisible_by_5.rs new file mode 100644 index 00000000..5cf25d6e --- /dev/null +++ b/src/problem/p1018_binary_prefix_divisible_by_5.rs @@ -0,0 +1,52 @@ +/** + * [1018] Binary Prefix Divisible By 5 + * + * You are given a binary array nums (0-indexed). + * We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit). + * + * For example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5. + * + * Return an array of booleans answer where answer[i] is true if xi is divisible by 5. + * + * Example 1: + * + * Input: nums = [0,1,1] + * Output: [true,false,false] + * Explanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. + * Only the first number is divisible by 5, so answer[0] is true. + * + * Example 2: + * + * Input: nums = [1,1,1] + * Output: [false,false,false] + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * nums[i] is either 0 or 1. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/binary-prefix-divisible-by-5/ +// discuss: https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn prefixes_div_by5(nums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1018() { + } +} diff --git a/src/problem/p1023_camelcase_matching.rs b/src/problem/p1023_camelcase_matching.rs new file mode 100644 index 00000000..1f856ae8 --- /dev/null +++ b/src/problem/p1023_camelcase_matching.rs @@ -0,0 +1,58 @@ +/** + * [1023] Camelcase Matching + * + * Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise. + * A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters. + * + * Example 1: + * + * Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB" + * Output: [true,false,true,true,false] + * Explanation: "FooBar" can be generated like this "F" + "oo" + "B" + "ar". + * "FootBall" can be generated like this "F" + "oot" + "B" + "all". + * "FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer". + * + * Example 2: + * + * Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa" + * Output: [true,false,true,false,false] + * Explanation: "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r". + * "FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll". + * + * Example 3: + * + * Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT" + * Output: [false,true,false,false,false] + * Explanation: "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est". + * + * + * Constraints: + * + * 1 <= pattern.length, queries.length <= 100 + * 1 <= queries[i].length <= 100 + * queries[i] and pattern consist of English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/camelcase-matching/ +// discuss: https://leetcode.com/problems/camelcase-matching/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn camel_match(queries: Vec, pattern: String) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1023() { + } +} diff --git a/src/problem/p1024_video_stitching.rs b/src/problem/p1024_video_stitching.rs new file mode 100644 index 00000000..f3635fe3 --- /dev/null +++ b/src/problem/p1024_video_stitching.rs @@ -0,0 +1,63 @@ +/** + * [1024] Video Stitching + * + * You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. + * Each video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi. + * We can cut these clips into segments freely. + * + * For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7]. + * + * Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1. + * + * Example 1: + * + * Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10 + * Output: 3 + * Explanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips. + * Then, we can reconstruct the sporting event as follows: + * We cut [1,9] into segments [1,2] + [2,8] + [8,9]. + * Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10]. + * + * Example 2: + * + * Input: clips = [[0,1],[1,2]], time = 5 + * Output: -1 + * Explanation: We cannot cover [0,5] with only [0,1] and [1,2]. + * + * Example 3: + * + * Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9 + * Output: 3 + * Explanation: We can take clips [0,4], [4,7], and [6,9]. + * + * + * Constraints: + * + * 1 <= clips.length <= 100 + * 0 <= starti <= endi <= 100 + * 1 <= time <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/video-stitching/ +// discuss: https://leetcode.com/problems/video-stitching/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn video_stitching(clips: Vec>, time: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1024() { + } +} diff --git a/src/problem/p1026_maximum_difference_between_node_and_ancestor.rs b/src/problem/p1026_maximum_difference_between_node_and_ancestor.rs new file mode 100644 index 00000000..f15d91e2 --- /dev/null +++ b/src/problem/p1026_maximum_difference_between_node_and_ancestor.rs @@ -0,0 +1,72 @@ +/** + * [1026] Maximum Difference Between Node and Ancestor + * + * Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b. + * A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b. + * + * Example 1: + * + * Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] + * Output: 7 + * Explanation: We have various ancestor-node differences, some of which are given below : + * |8 - 3| = 5 + * |3 - 7| = 4 + * |8 - 1| = 7 + * |10 - 13| = 3 + * Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. + * Example 2: + * + * Input: root = [1,null,2,null,0,3] + * Output: 3 + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [2, 5000]. + * 0 <= Node.val <= 10^5 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/ +// discuss: https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn max_ancestor_diff(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1026() { + } +} diff --git a/src/problem/p1027_longest_arithmetic_subsequence.rs b/src/problem/p1027_longest_arithmetic_subsequence.rs new file mode 100644 index 00000000..5ebdb4a6 --- /dev/null +++ b/src/problem/p1027_longest_arithmetic_subsequence.rs @@ -0,0 +1,57 @@ +/** + * [1027] Longest Arithmetic Subsequence + * + * Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. + * Recall that a subsequence of an array nums is a list nums[i1], nums[i2], ..., nums[ik] with 0 <= i1 < i2 < ... < ik <= nums.length - 1, and that a sequence seq is arithmetic if seq[i+1] - seq[i] are all the same value (for 0 <= i < seq.length - 1). + * + * Example 1: + * + * Input: nums = [3,6,9,12] + * Output: 4 + * Explanation: + * The whole array is an arithmetic sequence with steps of length = 3. + * + * Example 2: + * + * Input: nums = [9,4,7,2,10] + * Output: 3 + * Explanation: + * The longest arithmetic subsequence is [4,7,10]. + * + * Example 3: + * + * Input: nums = [20,1,15,3,10,5,8] + * Output: 4 + * Explanation: + * The longest arithmetic subsequence is [20,15,10,5]. + * + * + * Constraints: + * + * 2 <= nums.length <= 1000 + * 0 <= nums[i] <= 500 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-arithmetic-subsequence/ +// discuss: https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn longest_arith_seq_length(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1027() { + } +} diff --git a/src/problem/p1028_recover_a_tree_from_preorder_traversal.rs b/src/problem/p1028_recover_a_tree_from_preorder_traversal.rs new file mode 100644 index 00000000..02e3e0ec --- /dev/null +++ b/src/problem/p1028_recover_a_tree_from_preorder_traversal.rs @@ -0,0 +1,74 @@ +/** + * [1028] Recover a Tree From Preorder Traversal + * + * We run a preorder depth-first search (DFS) on the root of a binary tree. + * At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node. If the depth of a node is D, the depth of its immediate child is D + 1. The depth of the root node is 0. + * If a node has only one child, that child is guaranteed to be the left child. + * Given the output traversal of this traversal, recover the tree and return its root. + * + * Example 1: + * + * Input: traversal = "1-2--3--4-5--6--7" + * Output: [1,2,5,3,4,6,7] + * + * Example 2: + * + * Input: traversal = "1-2--3---4-5--6---7" + * Output: [1,2,5,3,null,6,null,4,null,7] + * + * Example 3: + * + * Input: traversal = "1-401--349---90--88" + * Output: [1,401,null,349,88,90] + * + * + * Constraints: + * + * The number of nodes in the original tree is in the range [1, 1000]. + * 1 <= Node.val <= 10^9 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/ +// discuss: https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn recover_from_preorder(traversal: String) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1028() { + } +} diff --git a/src/problem/p1040_moving_stones_until_consecutive_ii.rs b/src/problem/p1040_moving_stones_until_consecutive_ii.rs new file mode 100644 index 00000000..4db4687d --- /dev/null +++ b/src/problem/p1040_moving_stones_until_consecutive_ii.rs @@ -0,0 +1,61 @@ +/** + * [1040] Moving Stones Until Consecutive II + * + * There are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones. + * Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone. + * + * In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone. + * + * The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). + * Return an integer array answer of length 2 where: + * + * answer[0] is the minimum number of moves you can play, and + * answer[1] is the maximum number of moves you can play. + * + * + * Example 1: + * + * Input: stones = [7,4,9] + * Output: [1,2] + * Explanation: We can move 4 -> 8 for one move to finish the game. + * Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game. + * + * Example 2: + * + * Input: stones = [6,5,4,3,10] + * Output: [2,3] + * Explanation: We can move 3 -> 8 then 10 -> 7 to finish the game. + * Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game. + * Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move. + * + * + * Constraints: + * + * 3 <= stones.length <= 10^4 + * 1 <= stones[i] <= 10^9 + * All the values of stones are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/moving-stones-until-consecutive-ii/ +// discuss: https://leetcode.com/problems/moving-stones-until-consecutive-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_moves_stones_ii(stones: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1040() { + } +} diff --git a/src/problem/p1046_last_stone_weight.rs b/src/problem/p1046_last_stone_weight.rs new file mode 100644 index 00000000..081cd675 --- /dev/null +++ b/src/problem/p1046_last_stone_weight.rs @@ -0,0 +1,57 @@ +/** + * [1046] Last Stone Weight + * + * You are given an array of integers stones where stones[i] is the weight of the i^th stone. + * We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is: + * + * If x == y, both stones are destroyed, and + * If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. + * + * At the end of the game, there is at most one stone left. + * Return the weight of the last remaining stone. If there are no stones left, return 0. + * + * Example 1: + * + * Input: stones = [2,7,4,1,8,1] + * Output: 1 + * Explanation: + * We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, + * we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, + * we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, + * we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone. + * + * Example 2: + * + * Input: stones = [1] + * Output: 1 + * + * + * Constraints: + * + * 1 <= stones.length <= 30 + * 1 <= stones[i] <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/last-stone-weight/ +// discuss: https://leetcode.com/problems/last-stone-weight/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn last_stone_weight(stones: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1046() { + } +} diff --git a/src/problem/p1048_longest_string_chain.rs b/src/problem/p1048_longest_string_chain.rs new file mode 100644 index 00000000..776c9bdd --- /dev/null +++ b/src/problem/p1048_longest_string_chain.rs @@ -0,0 +1,61 @@ +/** + * [1048] Longest String Chain + * + * You are given an array of words where each word consists of lowercase English letters. + * wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB. + * + * For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad". + * + * A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1. + * Return the length of the longest possible word chain with words chosen from the given list of words. + * + * Example 1: + * + * Input: words = ["a","b","ba","bca","bda","bdca"] + * Output: 4 + * Explanation: One of the longest word chains is ["a","ba","bda","bdca"]. + * + * Example 2: + * + * Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"] + * Output: 5 + * Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"]. + * + * Example 3: + * + * Input: words = ["abcd","dbqca"] + * Output: 1 + * Explanation: The trivial word chain ["abcd"] is one of the longest word chains. + * ["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed. + * + * + * Constraints: + * + * 1 <= words.length <= 1000 + * 1 <= words[i].length <= 16 + * words[i] only consists of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-string-chain/ +// discuss: https://leetcode.com/problems/longest-string-chain/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn longest_str_chain(words: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1048() { + } +} diff --git a/src/problem/p1051_height_checker.rs b/src/problem/p1051_height_checker.rs new file mode 100644 index 00000000..3e08e57d --- /dev/null +++ b/src/problem/p1051_height_checker.rs @@ -0,0 +1,64 @@ +/** + * [1051] Height Checker + * + * A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the i^th student in line. + * You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the i^th student in line (0-indexed). + * Return the number of indices where heights[i] != expected[i]. + * + * Example 1: + * + * Input: heights = [1,1,4,2,1,3] + * Output: 3 + * Explanation: + * heights: [1,1,4,2,1,3] + * expected: [1,1,1,2,3,4] + * Indices 2, 4, and 5 do not match. + * + * Example 2: + * + * Input: heights = [5,1,2,3,4] + * Output: 5 + * Explanation: + * heights: [5,1,2,3,4] + * expected: [1,2,3,4,5] + * All indices do not match. + * + * Example 3: + * + * Input: heights = [1,2,3,4,5] + * Output: 0 + * Explanation: + * heights: [1,2,3,4,5] + * expected: [1,2,3,4,5] + * All indices match. + * + * + * Constraints: + * + * 1 <= heights.length <= 100 + * 1 <= heights[i] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/height-checker/ +// discuss: https://leetcode.com/problems/height-checker/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn height_checker(heights: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1051() { + } +} diff --git a/src/problem/p1052_grumpy_bookstore_owner.rs b/src/problem/p1052_grumpy_bookstore_owner.rs new file mode 100644 index 00000000..7a9d9bba --- /dev/null +++ b/src/problem/p1052_grumpy_bookstore_owner.rs @@ -0,0 +1,53 @@ +/** + * [1052] Grumpy Bookstore Owner + * + * There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the i^th minute and all those customers leave after the end of that minute. + * On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the i^th minute, and is 0 otherwise. + * When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. + * The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. + * Return the maximum number of customers that can be satisfied throughout the day. + * + * Example 1: + * + * Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3 + * Output: 16 + * Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. + * The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16. + * + * Example 2: + * + * Input: customers = [1], grumpy = [0], minutes = 1 + * Output: 1 + * + * + * Constraints: + * + * n == customers.length == grumpy.length + * 1 <= minutes <= n <= 2 * 10^4 + * 0 <= customers[i] <= 1000 + * grumpy[i] is either 0 or 1. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/grumpy-bookstore-owner/ +// discuss: https://leetcode.com/problems/grumpy-bookstore-owner/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_satisfied(customers: Vec, grumpy: Vec, minutes: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1052() { + } +} diff --git a/src/problem/p1071_greatest_common_divisor_of_strings.rs b/src/problem/p1071_greatest_common_divisor_of_strings.rs new file mode 100644 index 00000000..62af07e9 --- /dev/null +++ b/src/problem/p1071_greatest_common_divisor_of_strings.rs @@ -0,0 +1,51 @@ +/** + * [1071] Greatest Common Divisor of Strings + * + * For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). + * Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2. + * + * Example 1: + * + * Input: str1 = "ABCABC", str2 = "ABC" + * Output: "ABC" + * + * Example 2: + * + * Input: str1 = "ABABAB", str2 = "ABAB" + * Output: "AB" + * + * Example 3: + * + * Input: str1 = "LEET", str2 = "CODE" + * Output: "" + * + * + * Constraints: + * + * 1 <= str1.length, str2.length <= 1000 + * str1 and str2 consist of English uppercase letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/greatest-common-divisor-of-strings/ +// discuss: https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn gcd_of_strings(str1: String, str2: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1071() { + } +} diff --git a/src/problem/p1094_car_pooling.rs b/src/problem/p1094_car_pooling.rs new file mode 100644 index 00000000..4f9b144b --- /dev/null +++ b/src/problem/p1094_car_pooling.rs @@ -0,0 +1,50 @@ +/** + * [1094] Car Pooling + * + * There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). + * You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the i^th trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location. + * Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise. + * + * Example 1: + * + * Input: trips = [[2,1,5],[3,3,7]], capacity = 4 + * Output: false + * + * Example 2: + * + * Input: trips = [[2,1,5],[3,3,7]], capacity = 5 + * Output: true + * + * + * Constraints: + * + * 1 <= trips.length <= 1000 + * trips[i].length == 3 + * 1 <= numPassengersi <= 100 + * 0 <= fromi < toi <= 1000 + * 1 <= capacity <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/car-pooling/ +// discuss: https://leetcode.com/problems/car-pooling/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn car_pooling(trips: Vec>, capacity: i32) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1094() { + } +} diff --git a/src/problem/p1095_find_in_mountain_array.rs b/src/problem/p1095_find_in_mountain_array.rs new file mode 100644 index 00000000..c568ffb2 --- /dev/null +++ b/src/problem/p1095_find_in_mountain_array.rs @@ -0,0 +1,74 @@ +/** + * [1095] Find in Mountain Array + * + * (This problem is an interactive problem.) + * You may recall that an array arr is a mountain array if and only if: + * + * arr.length >= 3 + * There exists some i with 0 < i < arr.length - 1 such that: + * + * arr[0] < arr[1] < ... < arr[i - 1] < arr[i] + * arr[i] > arr[i + 1] > ... > arr[arr.length - 1] + * + * + * + * Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1. + * You cannot access the mountain array directly. You may only access the array using a MountainArray interface: + * + * MountainArray.get(k) returns the element of the array at index k (0-indexed). + * MountainArray.length() returns the length of the array. + * + * Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. + * + * Example 1: + * + * Input: array = [1,2,3,4,5,3,1], target = 3 + * Output: 2 + * Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. + * Example 2: + * + * Input: array = [0,1,2,4,2,1], target = 3 + * Output: -1 + * Explanation: 3 does not exist in the array, so we return -1. + * + * + * Constraints: + * + * 3 <= mountain_arr.length() <= 10^4 + * 0 <= target <= 10^9 + * 0 <= mountain_arr.get(index) <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-in-mountain-array/ +// discuss: https://leetcode.com/problems/find-in-mountain-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +/** + * // This is the MountainArray's API interface. + * // You should not implement it, or speculate about its implementation + * struct MountainArray; + * impl MountainArray { + * fn get(index:i32)->i32; + * fn length()->i32; + * }; + */ + +impl Solution { + pub fn find_in_mountain_array(target: i32, mountainArr: &MountainArray) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1095() { + } +} diff --git a/src/problem/p1110_delete_nodes_and_return_forest.rs b/src/problem/p1110_delete_nodes_and_return_forest.rs new file mode 100644 index 00000000..40ac7b29 --- /dev/null +++ b/src/problem/p1110_delete_nodes_and_return_forest.rs @@ -0,0 +1,70 @@ +/** + * [1110] Delete Nodes And Return Forest + * + * Given the root of a binary tree, each node in the tree has a distinct value. + * After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). + * Return the roots of the trees in the remaining forest. You may return the result in any order. + * + * Example 1: + * + * Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] + * Output: [[1,2,null,4],[6],[7]] + * + * Example 2: + * + * Input: root = [1,2,4,null,3], to_delete = [3] + * Output: [[1,2,4]] + * + * + * Constraints: + * + * The number of nodes in the given tree is at most 1000. + * Each node has a distinct value between 1 and 1000. + * to_delete.length <= 1000 + * to_delete contains distinct values between 1 and 1000. + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/delete-nodes-and-return-forest/ +// discuss: https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn del_nodes(root: Option>>, to_delete: Vec) -> Vec>>> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1110() { + } +} diff --git a/src/problem/p1122_relative_sort_array.rs b/src/problem/p1122_relative_sort_array.rs new file mode 100644 index 00000000..1bc4488a --- /dev/null +++ b/src/problem/p1122_relative_sort_array.rs @@ -0,0 +1,48 @@ +/** + * [1122] Relative Sort Array + * + * Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. + * Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. + * + * Example 1: + * + * Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] + * Output: [2,2,2,1,4,3,3,9,6,7,19] + * + * Example 2: + * + * Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6] + * Output: [22,28,8,6,17,44] + * + * + * Constraints: + * + * 1 <= arr1.length, arr2.length <= 1000 + * 0 <= arr1[i], arr2[i] <= 1000 + * All the elements of arr2 are distinct. + * Each arr2[i] is in arr1. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/relative-sort-array/ +// discuss: https://leetcode.com/problems/relative-sort-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn relative_sort_array(arr1: Vec, arr2: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1122() { + } +} diff --git a/src/problem/p1123_lowest_common_ancestor_of_deepest_leaves.rs b/src/problem/p1123_lowest_common_ancestor_of_deepest_leaves.rs new file mode 100644 index 00000000..009c3509 --- /dev/null +++ b/src/problem/p1123_lowest_common_ancestor_of_deepest_leaves.rs @@ -0,0 +1,85 @@ +/** + * [1123] Lowest Common Ancestor of Deepest Leaves + * + * Given the root of a binary tree, return the lowest common ancestor of its deepest leaves. + * Recall that: + * + * The node of a binary tree is a leaf if and only if it has no children + * The depth of the root of the tree is 0. if the depth of a node is d, the depth of each of its children is d + 1. + * The lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A. + * + * + * Example 1: + * + * Input: root = [3,5,1,6,2,0,8,null,null,7,4] + * Output: [2,7,4] + * Explanation: We return the node with value 2, colored in yellow in the diagram. + * The nodes coloured in blue are the deepest leaf-nodes of the tree. + * Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3. + * Example 2: + * + * Input: root = [1] + * Output: [1] + * Explanation: The root is the deepest node in the tree, and it's the lca of itself. + * + * Example 3: + * + * Input: root = [0,1,3,null,2] + * Output: [2] + * Explanation: The deepest leaf node in the tree is 2, the lca of one node is itself. + * + * + * Constraints: + * + * The number of nodes in the tree will be in the range [1, 1000]. + * 0 <= Node.val <= 1000 + * The values of the nodes in the tree are unique. + * + * + * Note: This question is the same as 865: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/ + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/ +// discuss: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn lca_deepest_leaves(root: Option>>) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1123() { + } +} diff --git a/src/problem/p1140_stone_game_ii.rs b/src/problem/p1140_stone_game_ii.rs new file mode 100644 index 00000000..a274847f --- /dev/null +++ b/src/problem/p1140_stone_game_ii.rs @@ -0,0 +1,50 @@ +/** + * [1140] Stone Game II + * + * Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. + * Alice and Bob take turns, with Alice starting first. Initially, M = 1. + * On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X). + * The game continues until all the stones have been taken. + * Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get. + * + * Example 1: + * + * Input: piles = [2,7,9,4,4] + * Output: 10 + * Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. + * + * Example 2: + * + * Input: piles = [1,2,3,4,5,100] + * Output: 104 + * + * + * Constraints: + * + * 1 <= piles.length <= 100 + * 1 <= piles[i] <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/stone-game-ii/ +// discuss: https://leetcode.com/problems/stone-game-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn stone_game_ii(piles: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1140() { + } +} diff --git a/src/problem/p1143_longest_common_subsequence.rs b/src/problem/p1143_longest_common_subsequence.rs new file mode 100644 index 00000000..63633fc8 --- /dev/null +++ b/src/problem/p1143_longest_common_subsequence.rs @@ -0,0 +1,58 @@ +/** + * [1143] Longest Common Subsequence + * + * Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. + * A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + * + * For example, "ace" is a subsequence of "abcde". + * + * A common subsequence of two strings is a subsequence that is common to both strings. + * + * Example 1: + * + * Input: text1 = "abcde", text2 = "ace" + * Output: 3 + * Explanation: The longest common subsequence is "ace" and its length is 3. + * + * Example 2: + * + * Input: text1 = "abc", text2 = "abc" + * Output: 3 + * Explanation: The longest common subsequence is "abc" and its length is 3. + * + * Example 3: + * + * Input: text1 = "abc", text2 = "def" + * Output: 0 + * Explanation: There is no such common subsequence, so the result is 0. + * + * + * Constraints: + * + * 1 <= text1.length, text2.length <= 1000 + * text1 and text2 consist of only lowercase English characters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-common-subsequence/ +// discuss: https://leetcode.com/problems/longest-common-subsequence/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn longest_common_subsequence(text1: String, text2: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1143() { + } +} diff --git a/src/problem/p1144_decrease_elements_to_make_array_zigzag.rs b/src/problem/p1144_decrease_elements_to_make_array_zigzag.rs new file mode 100644 index 00000000..792d244c --- /dev/null +++ b/src/problem/p1144_decrease_elements_to_make_array_zigzag.rs @@ -0,0 +1,52 @@ +/** + * [1144] Decrease Elements To Make Array Zigzag + * + * Given an array nums of integers, a move consists of choosing any element and decreasing it by 1. + * An array A is a zigzag array if either: + * + * Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ... + * OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ... + * + * Return the minimum number of moves to transform the given array nums into a zigzag array. + * + * Example 1: + * + * Input: nums = [1,2,3] + * Output: 2 + * Explanation: We can decrease 2 to 0 or 3 to 1. + * + * Example 2: + * + * Input: nums = [9,6,1,6,2] + * Output: 4 + * + * + * Constraints: + * + * 1 <= nums.length <= 1000 + * 1 <= nums[i] <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/ +// discuss: https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn moves_to_make_zigzag(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1144() { + } +} diff --git a/src/problem/p1146_snapshot_array.rs b/src/problem/p1146_snapshot_array.rs new file mode 100644 index 00000000..2932324d --- /dev/null +++ b/src/problem/p1146_snapshot_array.rs @@ -0,0 +1,85 @@ +/** + * [1146] Snapshot Array + * + * Implement a SnapshotArray that supports the following interface: + * + * SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0. + * void set(index, val) sets the element at the given index to be equal to val. + * int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1. + * int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id + * + * + * Example 1: + * + * Input: ["SnapshotArray","set","snap","set","get"] + * [[3],[0,5],[],[0,6],[0,0]] + * Output: [null,null,0,null,5] + * Explanation: + * SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3 + * snapshotArr.set(0,5); // Set array[0] = 5 + * snapshotArr.snap(); // Take a snapshot, return snap_id = 0 + * snapshotArr.set(0,6); + * snapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5 + * + * Constraints: + * + * 1 <= length <= 5 * 10^4 + * 0 <= index < length + * 0 <= val <= 10^9 + * 0 <= snap_id < (the total number of times we call snap()) + * At most 5 * 10^4 calls will be made to set, snap, and get. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/snapshot-array/ +// discuss: https://leetcode.com/problems/snapshot-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct SnapshotArray { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl SnapshotArray { + + fn new(length: i32) -> Self { + + } + + fn set(&self, index: i32, val: i32) { + + } + + fn snap(&self) -> i32 { + + } + + fn get(&self, index: i32, snap_id: i32) -> i32 { + + } +} + +/** + * Your SnapshotArray object will be instantiated and called as such: + * let obj = SnapshotArray::new(length); + * obj.set(index, val); + * let ret_2: i32 = obj.snap(); + * let ret_3: i32 = obj.get(index, snap_id); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1146() { + } +} diff --git a/src/problem/p1155_number_of_dice_rolls_with_target_sum.rs b/src/problem/p1155_number_of_dice_rolls_with_target_sum.rs new file mode 100644 index 00000000..6a010097 --- /dev/null +++ b/src/problem/p1155_number_of_dice_rolls_with_target_sum.rs @@ -0,0 +1,56 @@ +/** + * [1155] Number of Dice Rolls With Target Sum + * + * You have n dice and each die has k faces numbered from 1 to k. + * Given three integers n, k, and target, return the number of possible ways (out of the k^n total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 10^9 + 7. + * + * Example 1: + * + * Input: n = 1, k = 6, target = 3 + * Output: 1 + * Explanation: You throw one die with 6 faces. + * There is only one way to get a sum of 3. + * + * Example 2: + * + * Input: n = 2, k = 6, target = 7 + * Output: 6 + * Explanation: You throw two dice, each with 6 faces. + * There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1. + * + * Example 3: + * + * Input: n = 30, k = 30, target = 500 + * Output: 222616187 + * Explanation: The answer must be returned modulo 10^9 + 7. + * + * + * Constraints: + * + * 1 <= n, k <= 30 + * 1 <= target <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/ +// discuss: https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_rolls_to_target(n: i32, k: i32, target: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1155() { + } +} diff --git a/src/problem/p1163_last_substring_in_lexicographical_order.rs b/src/problem/p1163_last_substring_in_lexicographical_order.rs new file mode 100644 index 00000000..76e7449f --- /dev/null +++ b/src/problem/p1163_last_substring_in_lexicographical_order.rs @@ -0,0 +1,46 @@ +/** + * [1163] Last Substring in Lexicographical Order + * + * Given a string s, return the last substring of s in lexicographical order. + * + * Example 1: + * + * Input: s = "abab" + * Output: "bab" + * Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab". + * + * Example 2: + * + * Input: s = "leetcode" + * Output: "tcode" + * + * + * Constraints: + * + * 1 <= s.length <= 4 * 10^5 + * s contains only lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/last-substring-in-lexicographical-order/ +// discuss: https://leetcode.com/problems/last-substring-in-lexicographical-order/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn last_substring(s: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1163() { + } +} diff --git a/src/problem/p1172_dinner_plate_stacks.rs b/src/problem/p1172_dinner_plate_stacks.rs new file mode 100644 index 00000000..e771f323 --- /dev/null +++ b/src/problem/p1172_dinner_plate_stacks.rs @@ -0,0 +1,115 @@ +/** + * [1172] Dinner Plate Stacks + * + * You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity. + * Implement the DinnerPlates class: + * + * DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity. + * void push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity. + * int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty. + * int popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty. + * + * + * Example 1: + * + * Input + * ["DinnerPlates", "push", "push", "push", "push", "push", "popAtStack", "push", "push", "popAtStack", "popAtStack", "pop", "pop", "pop", "pop", "pop"] + * [[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []] + * Output + * [null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1] + * Explanation: + * DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2 + * D.push(1); + * D.push(2); + * D.push(3); + * D.push(4); + * D.push(5); // The stacks are now: 2 4 + * 1 3 5 + * ﹈ ﹈ ﹈ + * D.popAtStack(0); // Returns 2. The stacks are now: 4 + * 1 3 5 + * ﹈ ﹈ ﹈ + * D.push(20); // The stacks are now: 20 4 + * 1 3 5 + * ﹈ ﹈ ﹈ + * D.push(21); // The stacks are now: 20 4 21 + * 1 3 5 + * ﹈ ﹈ ﹈ + * D.popAtStack(0); // Returns 20. The stacks are now: 4 21 + * 1 3 5 + * ﹈ ﹈ ﹈ + * D.popAtStack(2); // Returns 21. The stacks are now: 4 + * 1 3 5 + * ﹈ ﹈ ﹈ + * D.pop() // Returns 5. The stacks are now: 4 + * 1 3 + * ﹈ ﹈ + * D.pop() // Returns 4. The stacks are now: 1 3 + * ﹈ ﹈ + * D.pop() // Returns 3. The stacks are now: 1 + * ﹈ + * D.pop() // Returns 1. There are no stacks. + * D.pop() // Returns -1. There are still no stacks. + * + * + * Constraints: + * + * 1 <= capacity <= 2 * 10^4 + * 1 <= val <= 2 * 10^4 + * 0 <= index <= 10^5 + * At most 2 * 10^5 calls will be made to push, pop, and popAtStack. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/dinner-plate-stacks/ +// discuss: https://leetcode.com/problems/dinner-plate-stacks/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct DinnerPlates { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl DinnerPlates { + + fn new(capacity: i32) -> Self { + + } + + fn push(&self, val: i32) { + + } + + fn pop(&self) -> i32 { + + } + + fn pop_at_stack(&self, index: i32) -> i32 { + + } +} + +/** + * Your DinnerPlates object will be instantiated and called as such: + * let obj = DinnerPlates::new(capacity); + * obj.push(val); + * let ret_2: i32 = obj.pop(); + * let ret_3: i32 = obj.pop_at_stack(index); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1172() { + } +} diff --git a/src/problem/p1187_make_array_strictly_increasing.rs b/src/problem/p1187_make_array_strictly_increasing.rs new file mode 100644 index 00000000..f4a03672 --- /dev/null +++ b/src/problem/p1187_make_array_strictly_increasing.rs @@ -0,0 +1,66 @@ +/** + * [1187] Make Array Strictly Increasing + * + * Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. + * + * In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j]. + * + * If there is no way to make arr1 strictly increasing, return -1. + * + * + * Example 1: + * + * + * Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4] + * Output: 1 + * Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7]. + * + * + * Example 2: + * + * + * Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1] + * Output: 2 + * Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7]. + * + * + * Example 3: + * + * + * Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3] + * Output: -1 + * Explanation: You can't make arr1 strictly increasing. + * + * + * Constraints: + * + * + * 1 <= arr1.length, arr2.length <= 2000 + * 0 <= arr1[i], arr2[i] <= 10^9 + * + * + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/make-array-strictly-increasing/ +// discuss: https://leetcode.com/problems/make-array-strictly-increasing/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn make_array_increasing(arr1: Vec, arr2: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1187() { + } +} diff --git a/src/problem/p1202_smallest_string_with_swaps.rs b/src/problem/p1202_smallest_string_with_swaps.rs new file mode 100644 index 00000000..3ee3f01b --- /dev/null +++ b/src/problem/p1202_smallest_string_with_swaps.rs @@ -0,0 +1,64 @@ +/** + * [1202] Smallest String With Swaps + * + * You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. + * You can swap the characters at any pair of indices in the given pairs any number of times. + * Return the lexicographically smallest string that s can be changed to after using the swaps. + * + * Example 1: + * + * Input: s = "dcab", pairs = [[0,3],[1,2]] + * Output: "bacd" + * Explaination: + * Swap s[0] and s[3], s = "bcad" + * Swap s[1] and s[2], s = "bacd" + * + * Example 2: + * + * Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]] + * Output: "abcd" + * Explaination: + * Swap s[0] and s[3], s = "bcad" + * Swap s[0] and s[2], s = "acbd" + * Swap s[1] and s[2], s = "abcd" + * Example 3: + * + * Input: s = "cba", pairs = [[0,1],[1,2]] + * Output: "abc" + * Explaination: + * Swap s[0] and s[1], s = "bca" + * Swap s[1] and s[2], s = "bac" + * Swap s[0] and s[1], s = "abc" + * + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * 0 <= pairs.length <= 10^5 + * 0 <= pairs[i][0], pairs[i][1] < s.length + * s only contains lower case English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/smallest-string-with-swaps/ +// discuss: https://leetcode.com/problems/smallest-string-with-swaps/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn smallest_string_with_swaps(s: String, pairs: Vec>) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1202() { + } +} diff --git a/src/problem/p1207_unique_number_of_occurrences.rs b/src/problem/p1207_unique_number_of_occurrences.rs new file mode 100644 index 00000000..e08fac72 --- /dev/null +++ b/src/problem/p1207_unique_number_of_occurrences.rs @@ -0,0 +1,50 @@ +/** + * [1207] Unique Number of Occurrences + * + * Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise. + * + * Example 1: + * + * Input: arr = [1,2,2,1,1,3] + * Output: true + * Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. + * Example 2: + * + * Input: arr = [1,2] + * Output: false + * + * Example 3: + * + * Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] + * Output: true + * + * + * Constraints: + * + * 1 <= arr.length <= 1000 + * -1000 <= arr[i] <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/unique-number-of-occurrences/ +// discuss: https://leetcode.com/problems/unique-number-of-occurrences/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn unique_occurrences(arr: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1207() { + } +} diff --git a/src/problem/p1221_split_a_string_in_balanced_strings.rs b/src/problem/p1221_split_a_string_in_balanced_strings.rs new file mode 100644 index 00000000..343e45be --- /dev/null +++ b/src/problem/p1221_split_a_string_in_balanced_strings.rs @@ -0,0 +1,59 @@ +/** + * [1221] Split a String in Balanced Strings + * + * Balanced strings are those that have an equal quantity of 'L' and 'R' characters. + * Given a balanced string s, split it into some number of substrings such that: + * + * Each substring is balanced. + * + * Return the maximum number of balanced strings you can obtain. + * + * Example 1: + * + * Input: s = "RLRRLLRLRL" + * Output: 4 + * Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. + * + * Example 2: + * + * Input: s = "RLRRRLLRLL" + * Output: 2 + * Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'. + * Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2^nd and 5^th substrings are not balanced. + * Example 3: + * + * Input: s = "LLLLRRRR" + * Output: 1 + * Explanation: s can be split into "LLLLRRRR". + * + * + * Constraints: + * + * 2 <= s.length <= 1000 + * s[i] is either 'L' or 'R'. + * s is a balanced string. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/split-a-string-in-balanced-strings/ +// discuss: https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn balanced_string_split(s: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1221() { + } +} diff --git a/src/problem/p1237_find_positive_integer_solution_for_a_given_equation.rs b/src/problem/p1237_find_positive_integer_solution_for_a_given_equation.rs new file mode 100644 index 00000000..cb82a35c --- /dev/null +++ b/src/problem/p1237_find_positive_integer_solution_for_a_given_equation.rs @@ -0,0 +1,86 @@ +/** + * [1237] Find Positive Integer Solution for a Given Equation + * + * Given a callable function f(x, y) with a hidden formula and a value z, reverse engineer the formula and return all positive integer pairs x and y where f(x,y) == z. You may return the pairs in any order. + * While the exact formula is hidden, the function is monotonically increasing, i.e.: + * + * f(x, y) < f(x + 1, y) + * f(x, y) < f(x, y + 1) + * + * The function interface is defined like this: + * + * interface CustomFunction { + * public: + * // Returns some positive integer f(x, y) for two positive integers x and y based on a formula. + * int f(int x, int y); + * }; + * + * We will judge your solution as follows: + * + * The judge has a list of 9 hidden implementations of CustomFunction, along with a way to generate an answer key of all valid pairs for a specific z. + * The judge will receive two inputs: a function_id (to determine which implementation to test your code with), and the target z. + * The judge will call your findSolution and compare your results with the answer key. + * If your results match the answer key, your solution will be Accepted. + * + * + * Example 1: + * + * Input: function_id = 1, z = 5 + * Output: [[1,4],[2,3],[3,2],[4,1]] + * Explanation: The hidden formula for function_id = 1 is f(x, y) = x + y. + * The following positive integer values of x and y make f(x, y) equal to 5: + * x=1, y=4 -> f(1, 4) = 1 + 4 = 5. + * x=2, y=3 -> f(2, 3) = 2 + 3 = 5. + * x=3, y=2 -> f(3, 2) = 3 + 2 = 5. + * x=4, y=1 -> f(4, 1) = 4 + 1 = 5. + * + * Example 2: + * + * Input: function_id = 2, z = 5 + * Output: [[1,5],[5,1]] + * Explanation: The hidden formula for function_id = 2 is f(x, y) = x * y. + * The following positive integer values of x and y make f(x, y) equal to 5: + * x=1, y=5 -> f(1, 5) = 1 * 5 = 5. + * x=5, y=1 -> f(5, 1) = 5 * 1 = 5. + * + * + * Constraints: + * + * 1 <= function_id <= 9 + * 1 <= z <= 100 + * It is guaranteed that the solutions of f(x, y) == z will be in the range 1 <= x, y <= 1000. + * It is also guaranteed that f(x, y) will fit in 32 bit signed integer if 1 <= x, y <= 1000. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/ +// discuss: https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +/* + * // This is the custom function interface. + * // You should not implement it, or speculate about its implementation + * struct CustomFunction; + * impl CustomFunction { + * pub fn f(x:i32,y:i32)->i32{} + * } + */ + +impl Solution { + pub fn find_solution(customfunction: &CustomFunction, z: i32) -> Vec> { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1237() { + } +} diff --git a/src/problem/p1238_circular_permutation_in_binary_representation.rs b/src/problem/p1238_circular_permutation_in_binary_representation.rs new file mode 100644 index 00000000..f4c8872f --- /dev/null +++ b/src/problem/p1238_circular_permutation_in_binary_representation.rs @@ -0,0 +1,60 @@ +/** + * [1238] Circular Permutation in Binary Representation + * + * Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : + * + * + * p[0] = start + * p[i] and p[i+1] differ by only one bit in their binary representation. + * p[0] and p[2^n -1] must also differ by only one bit in their binary representation. + * + * + * + * Example 1: + * + * + * Input: n = 2, start = 3 + * Output: [3,2,0,1] + * Explanation: The binary representation of the permutation is (11,10,00,01). + * All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2] + * + * + * Example 2: + * + * + * Input: n = 3, start = 2 + * Output: [2,6,7,5,4,0,1,3] + * Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011). + * + * + * + * Constraints: + * + * + * 1 <= n <= 16 + * 0 <= start < 2 ^ n + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/circular-permutation-in-binary-representation/ +// discuss: https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn circular_permutation(n: i32, start: i32) -> Vec { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1238() { + } +} diff --git a/src/problem/p1239_maximum_length_of_a_concatenated_string_with_unique_characters.rs b/src/problem/p1239_maximum_length_of_a_concatenated_string_with_unique_characters.rs new file mode 100644 index 00000000..0680544b --- /dev/null +++ b/src/problem/p1239_maximum_length_of_a_concatenated_string_with_unique_characters.rs @@ -0,0 +1,63 @@ +/** + * [1239] Maximum Length of a Concatenated String with Unique Characters + * + * You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. + * Return the maximum possible length of s. + * A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. + * + * Example 1: + * + * Input: arr = ["un","iq","ue"] + * Output: 4 + * Explanation: All the valid concatenations are: + * - "" + * - "un" + * - "iq" + * - "ue" + * - "uniq" ("un" + "iq") + * - "ique" ("iq" + "ue") + * Maximum length is 4. + * + * Example 2: + * + * Input: arr = ["cha","r","act","ers"] + * Output: 6 + * Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). + * + * Example 3: + * + * Input: arr = ["abcdefghijklmnopqrstuvwxyz"] + * Output: 26 + * Explanation: The only string in arr has all 26 characters. + * + * + * Constraints: + * + * 1 <= arr.length <= 16 + * 1 <= arr[i].length <= 26 + * arr[i] contains only lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/ +// discuss: https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_length(arr: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1239() { + } +} diff --git a/src/problem/p1247_minimum_swaps_to_make_strings_equal.rs b/src/problem/p1247_minimum_swaps_to_make_strings_equal.rs new file mode 100644 index 00000000..d75036c6 --- /dev/null +++ b/src/problem/p1247_minimum_swaps_to_make_strings_equal.rs @@ -0,0 +1,55 @@ +/** + * [1247] Minimum Swaps to Make Strings Equal + * + * You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j]. + * Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so. + * + * Example 1: + * + * Input: s1 = "xx", s2 = "yy" + * Output: 1 + * Explanation: Swap s1[0] and s2[1], s1 = "yx", s2 = "yx". + * + * Example 2: + * + * Input: s1 = "xy", s2 = "yx" + * Output: 2 + * Explanation: Swap s1[0] and s2[0], s1 = "yy", s2 = "xx". + * Swap s1[0] and s2[1], s1 = "xy", s2 = "xy". + * Note that you cannot swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings. + * + * Example 3: + * + * Input: s1 = "xx", s2 = "xy" + * Output: -1 + * + * + * Constraints: + * + * 1 <= s1.length, s2.length <= 1000 + * s1, s2 only contain 'x' or 'y'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/ +// discuss: https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn minimum_swap(s1: String, s2: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1247() { + } +} diff --git a/src/problem/p1253_reconstruct_a_2_row_binary_matrix.rs b/src/problem/p1253_reconstruct_a_2_row_binary_matrix.rs new file mode 100644 index 00000000..c786066a --- /dev/null +++ b/src/problem/p1253_reconstruct_a_2_row_binary_matrix.rs @@ -0,0 +1,62 @@ +/** + * [1253] Reconstruct a 2-Row Binary Matrix + * + * Given the following details of a matrix with n columns and 2 rows : + * + * The matrix is a binary matrix, which means each element in the matrix can be 0 or 1. + * The sum of elements of the 0-th(upper) row is given as upper. + * The sum of elements of the 1-st(lower) row is given as lower. + * The sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an integer array with length n. + * + * Your task is to reconstruct the matrix with upper, lower and colsum. + * Return it as a 2-D integer array. + * If there are more than one valid solution, any of them will be accepted. + * If no valid solution exists, return an empty 2-D array. + * + * Example 1: + * + * Input: upper = 2, lower = 1, colsum = [1,1,1] + * Output: [[1,1,0],[0,0,1]] + * Explanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers. + * + * Example 2: + * + * Input: upper = 2, lower = 3, colsum = [2,2,1,1] + * Output: [] + * + * Example 3: + * + * Input: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1] + * Output: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]] + * + * + * Constraints: + * + * 1 <= colsum.length <= 10^5 + * 0 <= upper, lower <= colsum.length + * 0 <= colsum[i] <= 2 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/ +// discuss: https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn reconstruct_matrix(upper: i32, lower: i32, colsum: Vec) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1253() { + } +} diff --git a/src/problem/p1260_shift_2d_grid.rs b/src/problem/p1260_shift_2d_grid.rs new file mode 100644 index 00000000..3eed909d --- /dev/null +++ b/src/problem/p1260_shift_2d_grid.rs @@ -0,0 +1,61 @@ +/** + * [1260] Shift 2D Grid + * + * Given a 2D grid of size m x n and an integer k. You need to shift the grid k times. + * In one shift operation: + * + * Element at grid[i][j] moves to grid[i][j + 1]. + * Element at grid[i][n - 1] moves to grid[i + 1][0]. + * Element at grid[m - 1][n - 1] moves to grid[0][0]. + * + * Return the 2D grid after applying shift operation k times. + * + * Example 1: + * + * Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1 + * Output: [[9,1,2],[3,4,5],[6,7,8]] + * + * Example 2: + * + * Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4 + * Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]] + * + * Example 3: + * + * Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9 + * Output: [[1,2,3],[4,5,6],[7,8,9]] + * + * + * Constraints: + * + * m == grid.length + * n == grid[i].length + * 1 <= m <= 50 + * 1 <= n <= 50 + * -1000 <= grid[i][j] <= 1000 + * 0 <= k <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/shift-2d-grid/ +// discuss: https://leetcode.com/problems/shift-2d-grid/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn shift_grid(grid: Vec>, k: i32) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1260() { + } +} diff --git a/src/problem/p1262_greatest_sum_divisible_by_three.rs b/src/problem/p1262_greatest_sum_divisible_by_three.rs new file mode 100644 index 00000000..473e4d11 --- /dev/null +++ b/src/problem/p1262_greatest_sum_divisible_by_three.rs @@ -0,0 +1,52 @@ +/** + * [1262] Greatest Sum Divisible by Three + * + * Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three. + * + * Example 1: + * + * Input: nums = [3,6,5,1,8] + * Output: 18 + * Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3). + * Example 2: + * + * Input: nums = [4] + * Output: 0 + * Explanation: Since 4 is not divisible by 3, do not pick any number. + * + * Example 3: + * + * Input: nums = [1,2,3,4,4] + * Output: 12 + * Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3). + * + * + * Constraints: + * + * 1 <= nums.length <= 4 * 10^4 + * 1 <= nums[i] <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/greatest-sum-divisible-by-three/ +// discuss: https://leetcode.com/problems/greatest-sum-divisible-by-three/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_sum_div_three(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1262() { + } +} diff --git a/src/problem/p1266_minimum_time_visiting_all_points.rs b/src/problem/p1266_minimum_time_visiting_all_points.rs new file mode 100644 index 00000000..b5100da3 --- /dev/null +++ b/src/problem/p1266_minimum_time_visiting_all_points.rs @@ -0,0 +1,62 @@ +/** + * [1266] Minimum Time Visiting All Points + * + * On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points. + * You can move according to these rules: + * + * In 1 second, you can either: + * + * move vertically by one unit, + * move horizontally by one unit, or + * move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second). + * + * + * You have to visit the points in the same order as they appear in the array. + * You are allowed to pass through points that appear later in the order, but these do not count as visits. + * + * + * Example 1: + * + * Input: points = [[1,1],[3,4],[-1,0]] + * Output: 7 + * Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] + * Time from [1,1] to [3,4] = 3 seconds + * Time from [3,4] to [-1,0] = 4 seconds + * Total time = 7 seconds + * Example 2: + * + * Input: points = [[3,2],[-2,2]] + * Output: 5 + * + * + * Constraints: + * + * points.length == n + * 1 <= n <= 100 + * points[i].length == 2 + * -1000 <= points[i][0], points[i][1] <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-time-visiting-all-points/ +// discuss: https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_time_to_visit_all_points(points: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1266() { + } +} diff --git a/src/problem/p1276_number_of_burgers_with_no_waste_of_ingredients.rs b/src/problem/p1276_number_of_burgers_with_no_waste_of_ingredients.rs new file mode 100644 index 00000000..64b59cb1 --- /dev/null +++ b/src/problem/p1276_number_of_burgers_with_no_waste_of_ingredients.rs @@ -0,0 +1,58 @@ +/** + * [1276] Number of Burgers with No Waste of Ingredients + * + * Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows: + * + * Jumbo Burger: 4 tomato slices and 1 cheese slice. + * Small Burger: 2 Tomato slices and 1 cheese slice. + * + * Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return []. + * + * Example 1: + * + * Input: tomatoSlices = 16, cheeseSlices = 7 + * Output: [1,6] + * Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese. + * There will be no remaining ingredients. + * + * Example 2: + * + * Input: tomatoSlices = 17, cheeseSlices = 4 + * Output: [] + * Explantion: There will be no way to use all ingredients to make small and jumbo burgers. + * + * Example 3: + * + * Input: tomatoSlices = 4, cheeseSlices = 17 + * Output: [] + * Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining. + * + * + * Constraints: + * + * 0 <= tomatoSlices, cheeseSlices <= 10^7 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/ +// discuss: https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_of_burgers(tomato_slices: i32, cheese_slices: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1276() { + } +} diff --git a/src/problem/p1289_minimum_falling_path_sum_ii.rs b/src/problem/p1289_minimum_falling_path_sum_ii.rs new file mode 100644 index 00000000..bce6db16 --- /dev/null +++ b/src/problem/p1289_minimum_falling_path_sum_ii.rs @@ -0,0 +1,53 @@ +/** + * [1289] Minimum Falling Path Sum II + * + * Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. + * A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column. + * + * Example 1: + * + * Input: arr = [[1,2,3],[4,5,6],[7,8,9]] + * Output: 13 + * Explanation: + * The possible falling paths are: + * [1,5,9], [1,5,7], [1,6,7], [1,6,8], + * [2,4,8], [2,4,9], [2,6,7], [2,6,8], + * [3,4,8], [3,4,9], [3,5,7], [3,5,9] + * The falling path with the smallest sum is [1,5,7], so the answer is 13. + * + * Example 2: + * + * Input: grid = [[7]] + * Output: 7 + * + * + * Constraints: + * + * n == grid.length == grid[i].length + * 1 <= n <= 200 + * -99 <= grid[i][j] <= 99 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-falling-path-sum-ii/ +// discuss: https://leetcode.com/problems/minimum-falling-path-sum-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_falling_path_sum(grid: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1289() { + } +} diff --git a/src/problem/p1292_maximum_side_length_of_a_square_with_sum_less_than_or_equal_to_threshold.rs b/src/problem/p1292_maximum_side_length_of_a_square_with_sum_less_than_or_equal_to_threshold.rs new file mode 100644 index 00000000..d2a03c60 --- /dev/null +++ b/src/problem/p1292_maximum_side_length_of_a_square_with_sum_less_than_or_equal_to_threshold.rs @@ -0,0 +1,49 @@ +/** + * [1292] Maximum Side Length of a Square with Sum Less than or Equal to Threshold + * + * Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square. + * + * Example 1: + * + * Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4 + * Output: 2 + * Explanation: The maximum side length of square with sum less than 4 is 2 as shown. + * + * Example 2: + * + * Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1 + * Output: 0 + * + * + * Constraints: + * + * m == mat.length + * n == mat[i].length + * 1 <= m, n <= 300 + * 0 <= mat[i][j] <= 10^4 + * 0 <= threshold <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/ +// discuss: https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_side_length(mat: Vec>, threshold: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1292() { + } +} diff --git a/src/problem/p1295_find_numbers_with_even_number_of_digits.rs b/src/problem/p1295_find_numbers_with_even_number_of_digits.rs new file mode 100644 index 00000000..f377b87c --- /dev/null +++ b/src/problem/p1295_find_numbers_with_even_number_of_digits.rs @@ -0,0 +1,54 @@ +/** + * [1295] Find Numbers with Even Number of Digits + * + * Given an array nums of integers, return how many of them contain an even number of digits. + * + * Example 1: + * + * Input: nums = [12,345,2,6,7896] + * Output: 2 + * Explanation: + * 12 contains 2 digits (even number of digits). + * 345 contains 3 digits (odd number of digits). + * 2 contains 1 digit (odd number of digits). + * 6 contains 1 digit (odd number of digits). + * 7896 contains 4 digits (even number of digits). + * Therefore only 12 and 7896 contain an even number of digits. + * + * Example 2: + * + * Input: nums = [555,901,482,1771] + * Output: 1 + * Explanation: + * Only 1771 contains an even number of digits. + * + * + * Constraints: + * + * 1 <= nums.length <= 500 + * 1 <= nums[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-numbers-with-even-number-of-digits/ +// discuss: https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_numbers(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1295() { + } +} diff --git a/src/problem/p1296_divide_array_in_sets_of_k_consecutive_numbers.rs b/src/problem/p1296_divide_array_in_sets_of_k_consecutive_numbers.rs new file mode 100644 index 00000000..b08d4e0f --- /dev/null +++ b/src/problem/p1296_divide_array_in_sets_of_k_consecutive_numbers.rs @@ -0,0 +1,56 @@ +/** + * [1296] Divide Array in Sets of K Consecutive Numbers + * + * Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers. + * Return true if it is possible. Otherwise, return false. + * + * Example 1: + * + * Input: nums = [1,2,3,3,4,4,5,6], k = 4 + * Output: true + * Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6]. + * + * Example 2: + * + * Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3 + * Output: true + * Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11]. + * + * Example 3: + * + * Input: nums = [1,2,3,4], k = 3 + * Output: false + * Explanation: Each array should be divided in subarrays of size 3. + * + * + * Constraints: + * + * 1 <= k <= nums.length <= 10^5 + * 1 <= nums[i] <= 10^9 + * + * + * Note: This question is the same as 846: https://leetcode.com/problems/hand-of-straights/ + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/ +// discuss: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_possible_divide(nums: Vec, k: i32) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1296() { + } +} diff --git a/src/problem/p1298_maximum_candies_you_can_get_from_boxes.rs b/src/problem/p1298_maximum_candies_you_can_get_from_boxes.rs new file mode 100644 index 00000000..35d3d9ad --- /dev/null +++ b/src/problem/p1298_maximum_candies_you_can_get_from_boxes.rs @@ -0,0 +1,70 @@ +/** + * [1298] Maximum Candies You Can Get from Boxes + * + * You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where: + * + * status[i] is 1 if the i^th box is open and 0 if the i^th box is closed, + * candies[i] is the number of candies in the i^th box, + * keys[i] is a list of the labels of the boxes you can open after opening the i^th box. + * containedBoxes[i] is a list of the boxes you found inside the i^th box. + * + * You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it. + * Return the maximum number of candies you can get following the rules above. + * + * Example 1: + * + * Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0] + * Output: 16 + * Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2. + * Box 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2. + * In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed. + * Total number of candies collected = 7 + 4 + 5 = 16 candy. + * + * Example 2: + * + * Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0] + * Output: 6 + * Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys. + * The total number of candies will be 6. + * + * + * Constraints: + * + * n == status.length == candies.length == keys.length == containedBoxes.length + * 1 <= n <= 1000 + * status[i] is either 0 or 1. + * 1 <= candies[i] <= 1000 + * 0 <= keys[i].length <= n + * 0 <= keys[i][j] < n + * All values of keys[i] are unique. + * 0 <= containedBoxes[i].length <= n + * 0 <= containedBoxes[i][j] < n + * All values of containedBoxes[i] are unique. + * Each box is contained in one box at most. + * 0 <= initialBoxes.length <= n + * 0 <= initialBoxes[i] < n + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/ +// discuss: https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_candies(status: Vec, candies: Vec, keys: Vec>, contained_boxes: Vec>, initial_boxes: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1298() { + } +} diff --git a/src/problem/p1299_replace_elements_with_greatest_element_on_right_side.rs b/src/problem/p1299_replace_elements_with_greatest_element_on_right_side.rs new file mode 100644 index 00000000..7195258d --- /dev/null +++ b/src/problem/p1299_replace_elements_with_greatest_element_on_right_side.rs @@ -0,0 +1,54 @@ +/** + * [1299] Replace Elements with Greatest Element on Right Side + * + * Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. + * After doing so, return the array. + * + * Example 1: + * + * Input: arr = [17,18,5,4,6,1] + * Output: [18,6,6,6,1,-1] + * Explanation: + * - index 0 --> the greatest element to the right of index 0 is index 1 (18). + * - index 1 --> the greatest element to the right of index 1 is index 4 (6). + * - index 2 --> the greatest element to the right of index 2 is index 4 (6). + * - index 3 --> the greatest element to the right of index 3 is index 4 (6). + * - index 4 --> the greatest element to the right of index 4 is index 5 (1). + * - index 5 --> there are no elements to the right of index 5, so we put -1. + * + * Example 2: + * + * Input: arr = [400] + * Output: [-1] + * Explanation: There are no elements to the right of index 0. + * + * + * Constraints: + * + * 1 <= arr.length <= 10^4 + * 1 <= arr[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/ +// discuss: https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn replace_elements(arr: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1299() { + } +} diff --git a/src/problem/p1311_get_watched_videos_by_your_friends.rs b/src/problem/p1311_get_watched_videos_by_your_friends.rs new file mode 100644 index 00000000..b3c75c10 --- /dev/null +++ b/src/problem/p1311_get_watched_videos_by_your_friends.rs @@ -0,0 +1,64 @@ +/** + * [1311] Get Watched Videos by Your Friends + * + * There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i. + * Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest. + * + * Example 1: + * + * + * Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1 + * Output: ["B","C"] + * Explanation: + * You have id = 0 (green color in the figure) and your friends are (yellow color in the figure): + * Person with id = 1 -> watchedVideos = ["C"] + * Person with id = 2 -> watchedVideos = ["B","C"] + * The frequencies of watchedVideos by your friends are: + * B -> 1 + * C -> 2 + * + * Example 2: + * + * + * Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2 + * Output: ["D"] + * Explanation: + * You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure). + * + * + * Constraints: + * + * n == watchedVideos.length == friends.length + * 2 <= n <= 100 + * 1 <= watchedVideos[i].length <= 100 + * 1 <= watchedVideos[i][j].length <= 8 + * 0 <= friends[i].length < n + * 0 <= friends[i][j] < n + * 0 <= id < n + * 1 <= level < n + * if friends[i] contains j, then friends[j] contains i + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/get-watched-videos-by-your-friends/ +// discuss: https://leetcode.com/problems/get-watched-videos-by-your-friends/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn watched_videos_by_friends(watched_videos: Vec>, friends: Vec>, id: i32, level: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1311() { + } +} diff --git a/src/problem/p1314_matrix_block_sum.rs b/src/problem/p1314_matrix_block_sum.rs new file mode 100644 index 00000000..10a8b8da --- /dev/null +++ b/src/problem/p1314_matrix_block_sum.rs @@ -0,0 +1,52 @@ +/** + * [1314] Matrix Block Sum + * + * Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for: + * + * i - k <= r <= i + k, + * j - k <= c <= j + k, and + * (r, c) is a valid position in the matrix. + * + * + * Example 1: + * + * Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1 + * Output: [[12,21,16],[27,45,33],[24,39,28]] + * + * Example 2: + * + * Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2 + * Output: [[45,45,45],[45,45,45],[45,45,45]] + * + * + * Constraints: + * + * m == mat.length + * n == mat[i].length + * 1 <= m, n, k <= 100 + * 1 <= mat[i][j] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/matrix-block-sum/ +// discuss: https://leetcode.com/problems/matrix-block-sum/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn matrix_block_sum(mat: Vec>, k: i32) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1314() { + } +} diff --git a/src/problem/p1324_print_words_vertically.rs b/src/problem/p1324_print_words_vertically.rs new file mode 100644 index 00000000..2413f3eb --- /dev/null +++ b/src/problem/p1324_print_words_vertically.rs @@ -0,0 +1,69 @@ +/** + * [1324] Print Words Vertically + * + * Given a string s. Return all the words vertically in the same order in which they appear in s.
+ * Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
+ * Each word would be put on only one column and that in one column there will be only one word. + * + * + * Example 1: + * + * + * Input: s = "HOW ARE YOU" + * Output: ["HAY","ORO","WEU"] + * Explanation: Each word is printed vertically. + * "HAY" + * "ORO" + * "WEU" + * + * + * Example 2: + * + * + * Input: s = "TO BE OR NOT TO BE" + * Output: ["TBONTB","OEROOE"," T"] + * Explanation: Trailing spaces is not allowed. + * "TBONTB" + * "OEROOE" + * " T" + * + * + * Example 3: + * + * + * Input: s = "CONTEST IS COMING" + * Output: ["CIC","OSO","N M","T I","E N","S G","T"] + * + * + * + * Constraints: + * + * + * 1 <= s.length <= 200 + * s contains only upper case English letters. + * It's guaranteed that there is only one space between 2 words. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/print-words-vertically/ +// discuss: https://leetcode.com/problems/print-words-vertically/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn print_vertically(s: String) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1324() { + } +} diff --git a/src/problem/p1326_minimum_number_of_taps_to_open_to_water_a_garden.rs b/src/problem/p1326_minimum_number_of_taps_to_open_to_water_a_garden.rs new file mode 100644 index 00000000..195c4dfe --- /dev/null +++ b/src/problem/p1326_minimum_number_of_taps_to_open_to_water_a_garden.rs @@ -0,0 +1,57 @@ +/** + * [1326] Minimum Number of Taps to Open to Water a Garden + * + * There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). + * There are n + 1 taps located at points [0, 1, ..., n] in the garden. + * Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. + * Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1. + * + * Example 1: + * + * Input: n = 5, ranges = [3,4,1,1,0,0] + * Output: 1 + * Explanation: The tap at point 0 can cover the interval [-3,3] + * The tap at point 1 can cover the interval [-3,5] + * The tap at point 2 can cover the interval [1,3] + * The tap at point 3 can cover the interval [2,4] + * The tap at point 4 can cover the interval [4,4] + * The tap at point 5 can cover the interval [5,5] + * Opening Only the second tap will water the whole garden [0,5] + * + * Example 2: + * + * Input: n = 3, ranges = [0,0,0,0] + * Output: -1 + * Explanation: Even if you activate all the four taps you cannot water the whole garden. + * + * + * Constraints: + * + * 1 <= n <= 10^4 + * ranges.length == n + 1 + * 0 <= ranges[i] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/ +// discuss: https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_taps(n: i32, ranges: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1326() { + } +} diff --git a/src/problem/p1329_sort_the_matrix_diagonally.rs b/src/problem/p1329_sort_the_matrix_diagonally.rs new file mode 100644 index 00000000..c88c9e04 --- /dev/null +++ b/src/problem/p1329_sort_the_matrix_diagonally.rs @@ -0,0 +1,48 @@ +/** + * [1329] Sort the Matrix Diagonally + * + * A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. + * Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix. + * + * Example 1: + * + * Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] + * Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] + * + * Example 2: + * + * Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]] + * Output: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]] + * + * + * Constraints: + * + * m == mat.length + * n == mat[i].length + * 1 <= m, n <= 100 + * 1 <= mat[i][j] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/sort-the-matrix-diagonally/ +// discuss: https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn diagonal_sort(mat: Vec>) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1329() { + } +} diff --git a/src/problem/p1339_maximum_product_of_splitted_binary_tree.rs b/src/problem/p1339_maximum_product_of_splitted_binary_tree.rs new file mode 100644 index 00000000..a4f5924e --- /dev/null +++ b/src/problem/p1339_maximum_product_of_splitted_binary_tree.rs @@ -0,0 +1,70 @@ +/** + * [1339] Maximum Product of Splitted Binary Tree + * + * Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. + * Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 10^9 + 7. + * Note that you need to maximize the answer before taking the mod and not after taking it. + * + * Example 1: + * + * Input: root = [1,2,3,4,5,6] + * Output: 110 + * Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10) + * + * Example 2: + * + * Input: root = [1,null,2,3,4,null,null,5,6] + * Output: 90 + * Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6) + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [2, 5 * 10^4]. + * 1 <= Node.val <= 10^4 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/ +// discuss: https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn max_product(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1339() { + } +} diff --git a/src/problem/p1343_number_of_sub_arrays_of_size_k_and_average_greater_than_or_equal_to_threshold.rs b/src/problem/p1343_number_of_sub_arrays_of_size_k_and_average_greater_than_or_equal_to_threshold.rs new file mode 100644 index 00000000..e13e2a54 --- /dev/null +++ b/src/problem/p1343_number_of_sub_arrays_of_size_k_and_average_greater_than_or_equal_to_threshold.rs @@ -0,0 +1,49 @@ +/** + * [1343] Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold + * + * Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold. + * + * Example 1: + * + * Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4 + * Output: 3 + * Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold). + * + * Example 2: + * + * Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5 + * Output: 6 + * Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers. + * + * + * Constraints: + * + * 1 <= arr.length <= 10^5 + * 1 <= arr[i] <= 10^4 + * 1 <= k <= arr.length + * 0 <= threshold <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/ +// discuss: https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_of_subarrays(arr: Vec, k: i32, threshold: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1343() { + } +} diff --git a/src/problem/p1349_maximum_students_taking_exam.rs b/src/problem/p1349_maximum_students_taking_exam.rs new file mode 100644 index 00000000..db5e86f3 --- /dev/null +++ b/src/problem/p1349_maximum_students_taking_exam.rs @@ -0,0 +1,68 @@ +/** + * [1349] Maximum Students Taking Exam + * + * Given a m * n matrix seats that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character. + * Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible.. + * Students must be placed in seats in good condition. + * + * Example 1: + * + * Input: seats = [["#",".","#","#",".","#"], + * [".","#","#","#","#","."], + * ["#",".","#","#",".","#"]] + * Output: 4 + * Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam. + * + * Example 2: + * + * Input: seats = [[".","#"], + * ["#","#"], + * ["#","."], + * ["#","#"], + * [".","#"]] + * Output: 3 + * Explanation: Place all students in available seats. + * + * Example 3: + * + * Input: seats = [["#",".",".",".","#"], + * [".","#",".","#","."], + * [".",".","#",".","."], + * [".","#",".","#","."], + * ["#",".",".",".","#"]] + * Output: 10 + * Explanation: Place students in available seats in column 1, 3 and 5. + * + * + * Constraints: + * + * seats contains only characters '.' and'#'. + * m == seats.length + * n == seats[i].length + * 1 <= m <= 8 + * 1 <= n <= 8 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-students-taking-exam/ +// discuss: https://leetcode.com/problems/maximum-students-taking-exam/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_students(seats: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1349() { + } +} diff --git a/src/problem/p1351_count_negative_numbers_in_a_sorted_matrix.rs b/src/problem/p1351_count_negative_numbers_in_a_sorted_matrix.rs new file mode 100644 index 00000000..149b5043 --- /dev/null +++ b/src/problem/p1351_count_negative_numbers_in_a_sorted_matrix.rs @@ -0,0 +1,50 @@ +/** + * [1351] Count Negative Numbers in a Sorted Matrix + * + * Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid. + * + * Example 1: + * + * Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] + * Output: 8 + * Explanation: There are 8 negatives number in the matrix. + * + * Example 2: + * + * Input: grid = [[3,2],[1,0]] + * Output: 0 + * + * + * Constraints: + * + * m == grid.length + * n == grid[i].length + * 1 <= m, n <= 100 + * -100 <= grid[i][j] <= 100 + * + * + * Follow up: Could you find an O(n + m) solution? + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/ +// discuss: https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_negatives(grid: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1351() { + } +} diff --git a/src/problem/p1352_product_of_the_last_k_numbers.rs b/src/problem/p1352_product_of_the_last_k_numbers.rs new file mode 100644 index 00000000..9eed2382 --- /dev/null +++ b/src/problem/p1352_product_of_the_last_k_numbers.rs @@ -0,0 +1,89 @@ +/** + * [1352] Product of the Last K Numbers + * + * Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream. + * Implement the ProductOfNumbers class: + * + * ProductOfNumbers() Initializes the object with an empty stream. + * void add(int num) Appends the integer num to the stream. + * int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers. + * + * The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing. + * + * Example: + * + * Input + * ["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"] + * [[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]] + * Output + * [null,null,null,null,null,null,20,40,0,null,32] + * Explanation + * ProductOfNumbers productOfNumbers = new ProductOfNumbers(); + * productOfNumbers.add(3); // [3] + * productOfNumbers.add(0); // [3,0] + * productOfNumbers.add(2); // [3,0,2] + * productOfNumbers.add(5); // [3,0,2,5] + * productOfNumbers.add(4); // [3,0,2,5,4] + * productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20 + * productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40 + * productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0 + * productOfNumbers.add(8); // [3,0,2,5,4,8] + * productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32 + * + * + * Constraints: + * + * 0 <= num <= 100 + * 1 <= k <= 4 * 10^4 + * At most 4 * 10^4 calls will be made to add and getProduct. + * The product of the stream at any point in time will fit in a 32-bit integer. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/product-of-the-last-k-numbers/ +// discuss: https://leetcode.com/problems/product-of-the-last-k-numbers/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct ProductOfNumbers { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl ProductOfNumbers { + + fn new() -> Self { + + } + + fn add(&self, num: i32) { + + } + + fn get_product(&self, k: i32) -> i32 { + + } +} + +/** + * Your ProductOfNumbers object will be instantiated and called as such: + * let obj = ProductOfNumbers::new(); + * obj.add(num); + * let ret_2: i32 = obj.get_product(k); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1352() { + } +} diff --git a/src/problem/p1359_count_all_valid_pickup_and_delivery_options.rs b/src/problem/p1359_count_all_valid_pickup_and_delivery_options.rs new file mode 100644 index 00000000..d5da8342 --- /dev/null +++ b/src/problem/p1359_count_all_valid_pickup_and_delivery_options.rs @@ -0,0 +1,55 @@ +/** + * [1359] Count All Valid Pickup and Delivery Options + * + * Given n orders, each order consist in pickup and delivery services. + * Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). + * Since the answer may be too large, return it modulo 10^9 + 7. + * + * Example 1: + * + * Input: n = 1 + * Output: 1 + * Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1. + * + * Example 2: + * + * Input: n = 2 + * Output: 6 + * Explanation: All possible orders: + * (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). + * This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. + * + * Example 3: + * + * Input: n = 3 + * Output: 90 + * + * + * Constraints: + * + * 1 <= n <= 500 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/ +// discuss: https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_orders(n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1359() { + } +} diff --git a/src/problem/p1371_find_the_longest_substring_containing_vowels_in_even_counts.rs b/src/problem/p1371_find_the_longest_substring_containing_vowels_in_even_counts.rs new file mode 100644 index 00000000..83f618d1 --- /dev/null +++ b/src/problem/p1371_find_the_longest_substring_containing_vowels_in_even_counts.rs @@ -0,0 +1,53 @@ +/** + * [1371] Find the Longest Substring Containing Vowels in Even Counts + * + * Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. + * + * Example 1: + * + * Input: s = "eleetminicoworoep" + * Output: 13 + * Explanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u. + * + * Example 2: + * + * Input: s = "leetcodeisgreat" + * Output: 5 + * Explanation: The longest substring is "leetc" which contains two e's. + * + * Example 3: + * + * Input: s = "bcbcbc" + * Output: 6 + * Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times. + * + * + * Constraints: + * + * 1 <= s.length <= 5 x 10^5 + * s contains only lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/ +// discuss: https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_the_longest_substring(s: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1371() { + } +} diff --git a/src/problem/p1372_longest_zigzag_path_in_a_binary_tree.rs b/src/problem/p1372_longest_zigzag_path_in_a_binary_tree.rs new file mode 100644 index 00000000..ae4123f3 --- /dev/null +++ b/src/problem/p1372_longest_zigzag_path_in_a_binary_tree.rs @@ -0,0 +1,82 @@ +/** + * [1372] Longest ZigZag Path in a Binary Tree + * + * You are given the root of a binary tree. + * A ZigZag path for a binary tree is defined as follow: + * + * Choose any node in the binary tree and a direction (right or left). + * If the current direction is right, move to the right child of the current node; otherwise, move to the left child. + * Change the direction from right to left or from left to right. + * Repeat the second and third steps until you can't move in the tree. + * + * Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). + * Return the longest ZigZag path contained in that tree. + * + * Example 1: + * + * Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1] + * Output: 3 + * Explanation: Longest ZigZag path in blue nodes (right -> left -> right). + * + * Example 2: + * + * Input: root = [1,1,1,null,1,null,null,1,1,null,1] + * Output: 4 + * Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right). + * + * Example 3: + * + * Input: root = [1] + * Output: 0 + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 5 * 10^4]. + * 1 <= Node.val <= 100 + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/ +// discuss: https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn longest_zig_zag(root: Option>>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1372() { + } +} diff --git a/src/problem/p1383_maximum_performance_of_a_team.rs b/src/problem/p1383_maximum_performance_of_a_team.rs new file mode 100644 index 00000000..8bdc92c2 --- /dev/null +++ b/src/problem/p1383_maximum_performance_of_a_team.rs @@ -0,0 +1,60 @@ +/** + * [1383] Maximum Performance of a Team + * + * You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the i^th engineer respectively. + * Choose at most k different engineers out of the n engineers to form a team with the maximum performance. + * The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. + * Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 10^9 + 7. + * + * Example 1: + * + * Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2 + * Output: 60 + * Explanation: + * We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60. + * + * Example 2: + * + * Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3 + * Output: 68 + * Explanation: + * This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68. + * + * Example 3: + * + * Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4 + * Output: 72 + * + * + * Constraints: + * + * 1 <= k <= n <= 10^5 + * speed.length == n + * efficiency.length == n + * 1 <= speed[i] <= 10^5 + * 1 <= efficiency[i] <= 10^8 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-performance-of-a-team/ +// discuss: https://leetcode.com/problems/maximum-performance-of-a-team/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_performance(n: i32, speed: Vec, efficiency: Vec, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1383() { + } +} diff --git a/src/problem/p1385_find_the_distance_value_between_two_arrays.rs b/src/problem/p1385_find_the_distance_value_between_two_arrays.rs new file mode 100644 index 00000000..604138ec --- /dev/null +++ b/src/problem/p1385_find_the_distance_value_between_two_arrays.rs @@ -0,0 +1,68 @@ +/** + * [1385] Find the Distance Value Between Two Arrays + * + * Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. + * The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d. + * + * Example 1: + * + * Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2 + * Output: 2 + * Explanation: + * For arr1[0]=4 we have: + * |4-10|=6 > d=2 + * |4-9|=5 > d=2 + * |4-1|=3 > d=2 + * |4-8|=4 > d=2 + * For arr1[1]=5 we have: + * |5-10|=5 > d=2 + * |5-9|=4 > d=2 + * |5-1|=4 > d=2 + * |5-8|=3 > d=2 + * For arr1[2]=8 we have: + * |8-10|=2 <= d=2 + * |8-9|=1 <= d=2 + * |8-1|=7 > d=2 + * |8-8|=0 <= d=2 + * + * Example 2: + * + * Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3 + * Output: 2 + * + * Example 3: + * + * Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6 + * Output: 1 + * + * + * Constraints: + * + * 1 <= arr1.length, arr2.length <= 500 + * -1000 <= arr1[i], arr2[j] <= 1000 + * 0 <= d <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-the-distance-value-between-two-arrays/ +// discuss: https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_the_distance_value(arr1: Vec, arr2: Vec, d: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1385() { + } +} diff --git a/src/problem/p1386_cinema_seat_allocation.rs b/src/problem/p1386_cinema_seat_allocation.rs new file mode 100644 index 00000000..70489e08 --- /dev/null +++ b/src/problem/p1386_cinema_seat_allocation.rs @@ -0,0 +1,59 @@ +/** + * [1386] Cinema Seat Allocation + * + * + * A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. + * Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved. + * Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side. + * + * Example 1: + * + * + * Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]] + * Output: 4 + * Explanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group. + * + * Example 2: + * + * Input: n = 2, reservedSeats = [[2,1],[1,8],[2,6]] + * Output: 2 + * + * Example 3: + * + * Input: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]] + * Output: 4 + * + * + * Constraints: + * + * 1 <= n <= 10^9 + * 1 <= reservedSeats.length <= min(10*n, 10^4) + * reservedSeats[i].length == 2 + * 1 <= reservedSeats[i][0] <= n + * 1 <= reservedSeats[i][1] <= 10 + * All reservedSeats[i] are distinct. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/cinema-seat-allocation/ +// discuss: https://leetcode.com/problems/cinema-seat-allocation/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_number_of_families(n: i32, reserved_seats: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1386() { + } +} diff --git a/src/problem/p1388_pizza_with_3n_slices.rs b/src/problem/p1388_pizza_with_3n_slices.rs new file mode 100644 index 00000000..3d8a4f2a --- /dev/null +++ b/src/problem/p1388_pizza_with_3n_slices.rs @@ -0,0 +1,55 @@ +/** + * [1388] Pizza With 3n Slices + * + * There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: + * + * You will pick any pizza slice. + * Your friend Alice will pick the next slice in the anti-clockwise direction of your pick. + * Your friend Bob will pick the next slice in the clockwise direction of your pick. + * Repeat until there are no more slices of pizzas. + * + * Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick. + * + * Example 1: + * + * Input: slices = [1,2,3,4,5,6] + * Output: 10 + * Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. + * + * Example 2: + * + * Input: slices = [8,9,8,6,1,1] + * Output: 16 + * Explanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. + * + * + * Constraints: + * + * 3 * n == slices.length + * 1 <= slices.length <= 500 + * 1 <= slices[i] <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/pizza-with-3n-slices/ +// discuss: https://leetcode.com/problems/pizza-with-3n-slices/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_size_slices(slices: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1388() { + } +} diff --git a/src/problem/p1390_four_divisors.rs b/src/problem/p1390_four_divisors.rs new file mode 100644 index 00000000..6b4feb84 --- /dev/null +++ b/src/problem/p1390_four_divisors.rs @@ -0,0 +1,55 @@ +/** + * [1390] Four Divisors + * + * Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0. + * + * Example 1: + * + * Input: nums = [21,4,7] + * Output: 32 + * Explanation: + * 21 has 4 divisors: 1, 3, 7, 21 + * 4 has 3 divisors: 1, 2, 4 + * 7 has 2 divisors: 1, 7 + * The answer is the sum of divisors of 21 only. + * + * Example 2: + * + * Input: nums = [21,21] + * Output: 64 + * + * Example 3: + * + * Input: nums = [1,2,3,4,5] + * Output: 0 + * + * + * Constraints: + * + * 1 <= nums.length <= 10^4 + * 1 <= nums[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/four-divisors/ +// discuss: https://leetcode.com/problems/four-divisors/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn sum_four_divisors(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1390() { + } +} diff --git a/src/problem/p1406_stone_game_iii.rs b/src/problem/p1406_stone_game_iii.rs new file mode 100644 index 00000000..aac67bd3 --- /dev/null +++ b/src/problem/p1406_stone_game_iii.rs @@ -0,0 +1,61 @@ +/** + * [1406] Stone Game III + * + * Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. + * Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row. + * The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially. + * The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. + * Assume Alice and Bob play optimally. + * Return "Alice" if Alice will win, "Bob" if Bob will win, or "Tie" if they will end the game with the same score. + * + * Example 1: + * + * Input: values = [1,2,3,7] + * Output: "Bob" + * Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. + * + * Example 2: + * + * Input: values = [1,2,3,-9] + * Output: "Alice" + * Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. + * If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose. + * If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose. + * Remember that both play optimally so here Alice will choose the scenario that makes her win. + * + * Example 3: + * + * Input: values = [1,2,3,6] + * Output: "Tie" + * Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. + * + * + * Constraints: + * + * 1 <= stoneValue.length <= 5 * 10^4 + * -1000 <= stoneValue[i] <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/stone-game-iii/ +// discuss: https://leetcode.com/problems/stone-game-iii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn stone_game_iii(stone_value: Vec) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1406() { + } +} diff --git a/src/problem/p1409_queries_on_a_permutation_with_key.rs b/src/problem/p1409_queries_on_a_permutation_with_key.rs new file mode 100644 index 00000000..9dcc8e97 --- /dev/null +++ b/src/problem/p1409_queries_on_a_permutation_with_key.rs @@ -0,0 +1,72 @@ +/** + * [1409] Queries on a Permutation With Key + * + * Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules: + * + * + * In the beginning, you have the permutation P=[1,2,3,...,m]. + * For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i]. + * + * + * Return an array containing the result for the given queries. + * + * + * Example 1: + * + * + * Input: queries = [3,1,2,1], m = 5 + * Output: [2,1,2,1] + * Explanation: The queries are processed as follow: + * For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. + * For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. + * For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. + * For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. + * Therefore, the array containing the result is [2,1,2,1]. + * + * + * Example 2: + * + * + * Input: queries = [4,1,2,2], m = 4 + * Output: [3,1,2,0] + * + * + * Example 3: + * + * + * Input: queries = [7,5,5,8,3], m = 8 + * Output: [6,5,0,7,5] + * + * + * + * Constraints: + * + * + * 1 <= m <= 10^3 + * 1 <= queries.length <= m + * 1 <= queries[i] <= m + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/queries-on-a-permutation-with-key/ +// discuss: https://leetcode.com/problems/queries-on-a-permutation-with-key/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn process_queries(queries: Vec, m: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1409() { + } +} diff --git a/src/problem/p1414_find_the_minimum_number_of_fibonacci_numbers_whose_sum_is_k.rs b/src/problem/p1414_find_the_minimum_number_of_fibonacci_numbers_whose_sum_is_k.rs new file mode 100644 index 00000000..566a6d79 --- /dev/null +++ b/src/problem/p1414_find_the_minimum_number_of_fibonacci_numbers_whose_sum_is_k.rs @@ -0,0 +1,58 @@ +/** + * [1414] Find the Minimum Number of Fibonacci Numbers Whose Sum Is K + * + * Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times. + * The Fibonacci numbers are defined as: + * + * F1 = 1 + * F2 = 1 + * Fn = Fn-1 + Fn-2 for n > 2. + * It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k. + * + * Example 1: + * + * Input: k = 7 + * Output: 2 + * Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... + * For k = 7 we can use 2 + 5 = 7. + * Example 2: + * + * Input: k = 10 + * Output: 2 + * Explanation: For k = 10 we can use 2 + 8 = 10. + * + * Example 3: + * + * Input: k = 19 + * Output: 3 + * Explanation: For k = 19 we can use 1 + 5 + 13 = 19. + * + * + * Constraints: + * + * 1 <= k <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/ +// discuss: https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_min_fibonacci_numbers(k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1414() { + } +} diff --git a/src/problem/p1418_display_table_of_food_orders_in_a_restaurant.rs b/src/problem/p1418_display_table_of_food_orders_in_a_restaurant.rs new file mode 100644 index 00000000..37f6f69f --- /dev/null +++ b/src/problem/p1418_display_table_of_food_orders_in_a_restaurant.rs @@ -0,0 +1,75 @@ +/** + * [1418] Display Table of Food Orders in a Restaurant + * + * Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders. + * + * Return the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order. + * + * + * Example 1: + * + * + * Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]] + * Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] + * Explanation: + * The displaying table looks like: + * Table,Beef Burrito,Ceviche,Fried Chicken,Water + * 3 ,0 ,2 ,1 ,0 + * 5 ,0 ,1 ,0 ,1 + * 10 ,1 ,0 ,0 ,0 + * For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche". + * For the table 5: Carla orders "Water" and "Ceviche". + * For the table 10: Corina orders "Beef Burrito". + * + * + * Example 2: + * + * + * Input: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]] + * Output: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] + * Explanation: + * For the table 1: Adam and Brianna order "Canadian Waffles". + * For the table 12: James, Ratesh and Amadeus order "Fried Chicken". + * + * + * Example 3: + * + * + * Input: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]] + * Output: [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]] + * + * + * + * Constraints: + * + * + * 1 <= orders.length <= 5 * 10^4 + * orders[i].length == 3 + * 1 <= customerNamei.length, foodItemi.length <= 20 + * customerNamei and foodItemi consist of lowercase and uppercase English letters and the space character. + * tableNumberi is a valid integer between 1 and 500. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/ +// discuss: https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn display_table(orders: Vec>) -> Vec> { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1418() { + } +} diff --git a/src/problem/p1438_longest_continuous_subarray_with_absolute_diff_less_than_or_equal_to_limit.rs b/src/problem/p1438_longest_continuous_subarray_with_absolute_diff_less_than_or_equal_to_limit.rs new file mode 100644 index 00000000..a8caaa3b --- /dev/null +++ b/src/problem/p1438_longest_continuous_subarray_with_absolute_diff_less_than_or_equal_to_limit.rs @@ -0,0 +1,64 @@ +/** + * [1438] Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit + * + * Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit. + * + * Example 1: + * + * Input: nums = [8,2,4,7], limit = 4 + * Output: 2 + * Explanation: All subarrays are: + * [8] with maximum absolute diff |8-8| = 0 <= 4. + * [8,2] with maximum absolute diff |8-2| = 6 > 4. + * [8,2,4] with maximum absolute diff |8-2| = 6 > 4. + * [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. + * [2] with maximum absolute diff |2-2| = 0 <= 4. + * [2,4] with maximum absolute diff |2-4| = 2 <= 4. + * [2,4,7] with maximum absolute diff |2-7| = 5 > 4. + * [4] with maximum absolute diff |4-4| = 0 <= 4. + * [4,7] with maximum absolute diff |4-7| = 3 <= 4. + * [7] with maximum absolute diff |7-7| = 0 <= 4. + * Therefore, the size of the longest subarray is 2. + * + * Example 2: + * + * Input: nums = [10,1,2,4,7,2], limit = 5 + * Output: 4 + * Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. + * + * Example 3: + * + * Input: nums = [4,2,2,2,4,4,2,2], limit = 0 + * Output: 3 + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * 1 <= nums[i] <= 10^9 + * 0 <= limit <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/ +// discuss: https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn longest_subarray(nums: Vec, limit: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1438() { + } +} diff --git a/src/problem/p1465_maximum_area_of_a_piece_of_cake_after_horizontal_and_vertical_cuts.rs b/src/problem/p1465_maximum_area_of_a_piece_of_cake_after_horizontal_and_vertical_cuts.rs new file mode 100644 index 00000000..76577561 --- /dev/null +++ b/src/problem/p1465_maximum_area_of_a_piece_of_cake_after_horizontal_and_vertical_cuts.rs @@ -0,0 +1,62 @@ +/** + * [1465] Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts + * + * You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where: + * + * horizontalCuts[i] is the distance from the top of the rectangular cake to the i^th horizontal cut and similarly, and + * verticalCuts[j] is the distance from the left of the rectangular cake to the j^th vertical cut. + * + * Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 10^9 + 7. + * + * Example 1: + * + * Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3] + * Output: 4 + * Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area. + * + * Example 2: + * + * Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1] + * Output: 6 + * Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area. + * + * Example 3: + * + * Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3] + * Output: 9 + * + * + * Constraints: + * + * 2 <= h, w <= 10^9 + * 1 <= horizontalCuts.length <= min(h - 1, 10^5) + * 1 <= verticalCuts.length <= min(w - 1, 10^5) + * 1 <= horizontalCuts[i] < h + * 1 <= verticalCuts[i] < w + * All the elements in horizontalCuts are distinct. + * All the elements in verticalCuts are distinct. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/ +// discuss: https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_area(h: i32, w: i32, horizontal_cuts: Vec, vertical_cuts: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1465() { + } +} diff --git a/src/problem/p1466_reorder_routes_to_make_all_paths_lead_to_the_city_zero.rs b/src/problem/p1466_reorder_routes_to_make_all_paths_lead_to_the_city_zero.rs new file mode 100644 index 00000000..e71de77e --- /dev/null +++ b/src/problem/p1466_reorder_routes_to_make_all_paths_lead_to_the_city_zero.rs @@ -0,0 +1,59 @@ +/** + * [1466] Reorder Routes to Make All Paths Lead to the City Zero + * + * There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. + * Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi. + * This year, there will be a big event in the capital (city 0), and many people want to travel to this city. + * Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed. + * It's guaranteed that each city can reach city 0 after reorder. + * + * Example 1: + * + * Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]] + * Output: 3 + * Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). + * + * Example 2: + * + * Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]] + * Output: 2 + * Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). + * + * Example 3: + * + * Input: n = 3, connections = [[1,0],[2,0]] + * Output: 0 + * + * + * Constraints: + * + * 2 <= n <= 5 * 10^4 + * connections.length == n - 1 + * connections[i].length == 2 + * 0 <= ai, bi <= n - 1 + * ai != bi + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/ +// discuss: https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_reorder(n: i32, connections: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1466() { + } +} diff --git a/src/problem/p1499_max_value_of_equation.rs b/src/problem/p1499_max_value_of_equation.rs new file mode 100644 index 00000000..d488e193 --- /dev/null +++ b/src/problem/p1499_max_value_of_equation.rs @@ -0,0 +1,54 @@ +/** + * [1499] Max Value of Equation + * + * You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k. + * Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length. + * It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k. + * + * Example 1: + * + * Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1 + * Output: 4 + * Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1. + * No other pairs satisfy the condition, so we return the max of 4 and 1. + * + * Example 2: + * + * Input: points = [[0,0],[3,0],[9,2]], k = 3 + * Output: 3 + * Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3. + * + * + * Constraints: + * + * 2 <= points.length <= 10^5 + * points[i].length == 2 + * -10^8 <= xi, yi <= 10^8 + * 0 <= k <= 2 * 10^8 + * xi < xj for all 1 <= i < j <= points.length + * xi form a strictly increasing sequence. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/max-value-of-equation/ +// discuss: https://leetcode.com/problems/max-value-of-equation/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_max_value_of_equation(points: Vec>, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1499() { + } +} diff --git a/src/problem/p1509_minimum_difference_between_largest_and_smallest_value_in_three_moves.rs b/src/problem/p1509_minimum_difference_between_largest_and_smallest_value_in_three_moves.rs new file mode 100644 index 00000000..eba7e284 --- /dev/null +++ b/src/problem/p1509_minimum_difference_between_largest_and_smallest_value_in_three_moves.rs @@ -0,0 +1,50 @@ +/** + * [1509] Minimum Difference Between Largest and Smallest Value in Three Moves + * + * You are given an integer array nums. In one move, you can choose one element of nums and change it by any value. + * Return the minimum difference between the largest and smallest value of nums after performing at most three moves. + * + * Example 1: + * + * Input: nums = [5,3,2,4] + * Output: 0 + * Explanation: Change the array [5,3,2,4] to [2,2,2,2]. + * The difference between the maximum and minimum is 2-2 = 0. + * + * Example 2: + * + * Input: nums = [1,5,0,10,14] + * Output: 1 + * Explanation: Change the array [1,5,0,10,14] to [1,1,0,1,1]. + * The difference between the maximum and minimum is 1-0 = 1. + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * -10^9 <= nums[i] <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/ +// discuss: https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_difference(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1509() { + } +} diff --git a/src/problem/p1518_water_bottles.rs b/src/problem/p1518_water_bottles.rs new file mode 100644 index 00000000..dc8c0b5c --- /dev/null +++ b/src/problem/p1518_water_bottles.rs @@ -0,0 +1,51 @@ +/** + * [1518] Water Bottles + * + * There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle. + * The operation of drinking a full water bottle turns it into an empty bottle. + * Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink. + * + * Example 1: + * + * Input: numBottles = 9, numExchange = 3 + * Output: 13 + * Explanation: You can exchange 3 empty bottles to get 1 full water bottle. + * Number of water bottles you can drink: 9 + 3 + 1 = 13. + * + * Example 2: + * + * Input: numBottles = 15, numExchange = 4 + * Output: 19 + * Explanation: You can exchange 4 empty bottles to get 1 full water bottle. + * Number of water bottles you can drink: 15 + 3 + 1 = 19. + * + * + * Constraints: + * + * 1 <= numBottles <= 100 + * 2 <= numExchange <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/water-bottles/ +// discuss: https://leetcode.com/problems/water-bottles/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_water_bottles(num_bottles: i32, num_exchange: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1518() { + } +} diff --git a/src/problem/p1524_number_of_sub_arrays_with_odd_sum.rs b/src/problem/p1524_number_of_sub_arrays_with_odd_sum.rs new file mode 100644 index 00000000..b5f587fd --- /dev/null +++ b/src/problem/p1524_number_of_sub_arrays_with_odd_sum.rs @@ -0,0 +1,57 @@ +/** + * [1524] Number of Sub-arrays With Odd Sum + * + * Given an array of integers arr, return the number of subarrays with an odd sum. + * Since the answer can be very large, return it modulo 10^9 + 7. + * + * Example 1: + * + * Input: arr = [1,3,5] + * Output: 4 + * Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]] + * All sub-arrays sum are [1,4,9,3,8,5]. + * Odd sums are [1,9,3,5] so the answer is 4. + * + * Example 2: + * + * Input: arr = [2,4,6] + * Output: 0 + * Explanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]] + * All sub-arrays sum are [2,6,12,4,10,6]. + * All sub-arrays have even sum and the answer is 0. + * + * Example 3: + * + * Input: arr = [1,2,3,4,5,6,7] + * Output: 16 + * + * + * Constraints: + * + * 1 <= arr.length <= 10^5 + * 1 <= arr[i] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/ +// discuss: https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn num_of_subarrays(arr: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1524() { + } +} diff --git a/src/problem/p1534_count_good_triplets.rs b/src/problem/p1534_count_good_triplets.rs new file mode 100644 index 00000000..1f9571df --- /dev/null +++ b/src/problem/p1534_count_good_triplets.rs @@ -0,0 +1,67 @@ +/** + * [1534] Count Good Triplets + * + * Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets. + * + * A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true: + * + * + * 0 <= i < j < k < arr.length + * |arr[i] - arr[j]| <= a + * |arr[j] - arr[k]| <= b + * |arr[i] - arr[k]| <= c + * + * + * Where |x| denotes the absolute value of x. + * + * Return the number of good triplets. + * + * + * Example 1: + * + * + * Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3 + * Output: 4 + * Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)]. + * + * + * Example 2: + * + * + * Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1 + * Output: 0 + * Explanation: No triplet satisfies all conditions. + * + * + * + * Constraints: + * + * + * 3 <= arr.length <= 100 + * 0 <= arr[i] <= 1000 + * 0 <= a, b, c <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-good-triplets/ +// discuss: https://leetcode.com/problems/count-good-triplets/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_good_triplets(arr: Vec, a: i32, b: i32, c: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1534() { + } +} diff --git a/src/problem/p1540_can_convert_string_in_k_moves.rs b/src/problem/p1540_can_convert_string_in_k_moves.rs new file mode 100644 index 00000000..cd06af58 --- /dev/null +++ b/src/problem/p1540_can_convert_string_in_k_moves.rs @@ -0,0 +1,62 @@ +/** + * [1540] Can Convert String in K Moves + * + * Given two strings s and t, your goal is to convert s into t in k moves or less. + * During the i^th (1 <= i <= k) move you can: + * + * Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times. + * Do nothing. + * + * Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times. + * Remember that any index j can be picked at most once. + * Return true if it's possible to convert s into t in no more than k moves, otherwise return false. + * + * Example 1: + * + * Input: s = "input", t = "ouput", k = 9 + * Output: true + * Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'. + * + * Example 2: + * + * Input: s = "abc", t = "bcd", k = 10 + * Output: false + * Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s. + * + * Example 3: + * + * Input: s = "aab", t = "bbb", k = 27 + * Output: true + * Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'. + * + * + * Constraints: + * + * 1 <= s.length, t.length <= 10^5 + * 0 <= k <= 10^9 + * s, t contain only lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/can-convert-string-in-k-moves/ +// discuss: https://leetcode.com/problems/can-convert-string-in-k-moves/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn can_convert_string(s: String, t: String, k: i32) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1540() { + } +} diff --git a/src/problem/p1579_remove_max_number_of_edges_to_keep_graph_fully_traversable.rs b/src/problem/p1579_remove_max_number_of_edges_to_keep_graph_fully_traversable.rs new file mode 100644 index 00000000..1aac8fea --- /dev/null +++ b/src/problem/p1579_remove_max_number_of_edges_to_keep_graph_fully_traversable.rs @@ -0,0 +1,67 @@ +/** + * [1579] Remove Max Number of Edges to Keep Graph Fully Traversable + * + * Alice and Bob have an undirected graph of n nodes and three types of edges: + * + * Type 1: Can be traversed by Alice only. + * Type 2: Can be traversed by Bob only. + * Type 3: Can be traversed by both Alice and Bob. + * + * Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. + * Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph. + * + * Example 1: + * + * + * Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]] + * Output: 2 + * Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2. + * + * Example 2: + * + * + * Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]] + * Output: 0 + * Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob. + * + * Example 3: + * + * + * Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]] + * Output: -1 + * Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable. + * + * + * Constraints: + * + * 1 <= n <= 10^5 + * 1 <= edges.length <= min(10^5, 3 * n * (n - 1) / 2) + * edges[i].length == 3 + * 1 <= typei <= 3 + * 1 <= ui < vi <= n + * All tuples (typei, ui, vi) are distinct. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/ +// discuss: https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_num_edges_to_remove(n: i32, edges: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1579() { + } +} diff --git a/src/problem/p1600_throne_inheritance.rs b/src/problem/p1600_throne_inheritance.rs new file mode 100644 index 00000000..c393a3e7 --- /dev/null +++ b/src/problem/p1600_throne_inheritance.rs @@ -0,0 +1,113 @@ +/** + * [1600] Throne Inheritance + * + * A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born. + * The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance. + * + * Successor(x, curOrder): + * if x has no children or all of x's children are in curOrder: + * if x is the king return null + * else return Successor(x's parent, curOrder) + * else return x's oldest child who's not in curOrder + * + * For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack. + *
    + * In the beginning, curOrder will be ["king"]. + * Calling Successor(king, curOrder) will return Alice, so we append to curOrder to get ["king", "Alice"]. + * Calling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get ["king", "Alice", "Jack"]. + * Calling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get ["king", "Alice", "Jack", "Bob"]. + * Calling Successor(Bob, curOrder) will return null. Thus the order of inheritance will be ["king", "Alice", "Jack", "Bob"]. + *
+ * Using the above function, we can always obtain a unique order of inheritance. + * Implement the ThroneInheritance class: + * + * ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor. + * void birth(string parentName, string childName) Indicates that parentName gave birth to childName. + * void death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead. + * string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people. + * + * + * Example 1: + * + * Input + * ["ThroneInheritance", "birth", "birth", "birth", "birth", "birth", "birth", "getInheritanceOrder", "death", "getInheritanceOrder"] + * [["king"], ["king", "andy"], ["king", "bob"], ["king", "catherine"], ["andy", "matthew"], ["bob", "alex"], ["bob", "asha"], [null], ["bob"], [null]] + * Output + * [null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]] + * Explanation + * ThroneInheritance t= new ThroneInheritance("king"); // order: king + * t.birth("king", "andy"); // order: king > andy + * t.birth("king", "bob"); // order: king > andy > bob + * t.birth("king", "catherine"); // order: king > andy > bob > catherine + * t.birth("andy", "matthew"); // order: king > andy > matthew > bob > catherine + * t.birth("bob", "alex"); // order: king > andy > matthew > bob > alex > catherine + * t.birth("bob", "asha"); // order: king > andy > matthew > bob > alex > asha > catherine + * t.getInheritanceOrder(); // return ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"] + * t.death("bob"); // order: king > andy > matthew > bob > alex > asha > catherine + * t.getInheritanceOrder(); // return ["king", "andy", "matthew", "alex", "asha", "catherine"] + * + * + * Constraints: + * + * 1 <= kingName.length, parentName.length, childName.length, name.length <= 15 + * kingName, parentName, childName, and name consist of lowercase English letters only. + * All arguments childName and kingName are distinct. + * All name arguments of death will be passed to either the constructor or as childName to birth first. + * For each call to birth(parentName, childName), it is guaranteed that parentName is alive. + * At most 10^5 calls will be made to birth and death. + * At most 10 calls will be made to getInheritanceOrder. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/throne-inheritance/ +// discuss: https://leetcode.com/problems/throne-inheritance/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct ThroneInheritance { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl ThroneInheritance { + + fn new(kingName: String) -> Self { + + } + + fn birth(&self, parent_name: String, child_name: String) { + + } + + fn death(&self, name: String) { + + } + + fn get_inheritance_order(&self) -> Vec { + + } +} + +/** + * Your ThroneInheritance object will be instantiated and called as such: + * let obj = ThroneInheritance::new(kingName); + * obj.birth(parentName, childName); + * obj.death(name); + * let ret_3: Vec = obj.get_inheritance_order(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1600() { + } +} diff --git a/src/problem/p1605_find_valid_matrix_given_row_and_column_sums.rs b/src/problem/p1605_find_valid_matrix_given_row_and_column_sums.rs new file mode 100644 index 00000000..9334ff05 --- /dev/null +++ b/src/problem/p1605_find_valid_matrix_given_row_and_column_sums.rs @@ -0,0 +1,59 @@ +/** + * [1605] Find Valid Matrix Given Row and Column Sums + * + * You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the i^th row and colSum[j] is the sum of the elements of the j^th column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. + * Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements. + * Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists. + * + * Example 1: + * + * Input: rowSum = [3,8], colSum = [4,7] + * Output: [[3,0], + * [1,7]] + * Explanation: + * 0^th row: 3 + 0 = 3 == rowSum[0] + * 1^st row: 1 + 7 = 8 == rowSum[1] + * 0^th column: 3 + 1 = 4 == colSum[0] + * 1^st column: 0 + 7 = 7 == colSum[1] + * The row and column sums match, and all matrix elements are non-negative. + * Another possible matrix is: [[1,2], + * [3,5]] + * + * Example 2: + * + * Input: rowSum = [5,7,10], colSum = [8,6,8] + * Output: [[0,5,0], + * [6,1,0], + * [2,0,8]] + * + * + * Constraints: + * + * 1 <= rowSum.length, colSum.length <= 500 + * 0 <= rowSum[i], colSum[i] <= 10^8 + * sum(rows) == sum(columns) + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/ +// discuss: https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn restore_matrix(row_sum: Vec, col_sum: Vec) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1605() { + } +} diff --git a/src/problem/p1616_split_two_strings_to_make_palindrome.rs b/src/problem/p1616_split_two_strings_to_make_palindrome.rs new file mode 100644 index 00000000..537d873b --- /dev/null +++ b/src/problem/p1616_split_two_strings_to_make_palindrome.rs @@ -0,0 +1,62 @@ +/** + * [1616] Split Two Strings to Make Palindrome + * + * You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome. + * When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are valid splits. + * Return true if it is possible to form a palindrome string, otherwise return false. + * Notice that x + y denotes the concatenation of strings x and y. + * + * Example 1: + * + * Input: a = "x", b = "y" + * Output: true + * Explaination: If either a or b are palindromes the answer is true since you can split in the following way: + * aprefix = "", asuffix = "x" + * bprefix = "", bsuffix = "y" + * Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome. + * + * Example 2: + * + * Input: a = "xbdef", b = "xecab" + * Output: false + * + * Example 3: + * + * Input: a = "ulacfd", b = "jizalu" + * Output: true + * Explaination: Split them at index 3: + * aprefix = "ula", asuffix = "cfd" + * bprefix = "jiz", bsuffix = "alu" + * Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome. + * + * + * Constraints: + * + * 1 <= a.length, b.length <= 10^5 + * a.length == b.length + * a and b consist of lowercase English letters + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/split-two-strings-to-make-palindrome/ +// discuss: https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn check_palindrome_formation(a: String, b: String) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1616() { + } +} diff --git a/src/problem/p1620_coordinate_with_maximum_network_quality.rs b/src/problem/p1620_coordinate_with_maximum_network_quality.rs new file mode 100644 index 00000000..ed1731b3 --- /dev/null +++ b/src/problem/p1620_coordinate_with_maximum_network_quality.rs @@ -0,0 +1,71 @@ +/** + * [1620] Coordinate With Maximum Network Quality + * + * You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the i^th network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance. + * You are also given an integer radius where a tower is reachable if the distance is less than or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not reachable. + * The signal quality of the i^th tower at a coordinate (x, y) is calculated with the formula ⌊qi / (1 + d)⌋, where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers. + * Return the array [cx, cy] representing the integral coordinate (cx, cy) where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum non-negative coordinate. + * Note: + * + * A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either: + * + * x1 < x2, or + * x1 == x2 and y1 < y2. + * + * + * ⌊val⌋ is the greatest integer less than or equal to val (the floor function). + * + * + * Example 1: + * + * Input: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2 + * Output: [2,1] + * Explanation: At coordinate (2, 1) the total quality is 13. + * - Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7 + * - Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2 + * - Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4 + * No other coordinate has a higher network quality. + * Example 2: + * + * Input: towers = [[23,11,21]], radius = 9 + * Output: [23,11] + * Explanation: Since there is only one tower, the network quality is highest right at the tower's location. + * + * Example 3: + * + * Input: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2 + * Output: [1,2] + * Explanation: Coordinate (1, 2) has the highest network quality. + * + * + * Constraints: + * + * 1 <= towers.length <= 50 + * towers[i].length == 3 + * 0 <= xi, yi, qi <= 50 + * 1 <= radius <= 50 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/coordinate-with-maximum-network-quality/ +// discuss: https://leetcode.com/problems/coordinate-with-maximum-network-quality/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn best_coordinate(towers: Vec>, radius: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1620() { + } +} diff --git a/src/problem/p1624_largest_substring_between_two_equal_characters.rs b/src/problem/p1624_largest_substring_between_two_equal_characters.rs new file mode 100644 index 00000000..1b95fcce --- /dev/null +++ b/src/problem/p1624_largest_substring_between_two_equal_characters.rs @@ -0,0 +1,53 @@ +/** + * [1624] Largest Substring Between Two Equal Characters + * + * Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. + * A substring is a contiguous sequence of characters within a string. + * + * Example 1: + * + * Input: s = "aa" + * Output: 0 + * Explanation: The optimal substring here is an empty substring between the two 'a's. + * Example 2: + * + * Input: s = "abca" + * Output: 2 + * Explanation: The optimal substring here is "bc". + * + * Example 3: + * + * Input: s = "cbzxy" + * Output: -1 + * Explanation: There are no characters that appear twice in s. + * + * + * Constraints: + * + * 1 <= s.length <= 300 + * s contains only lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/largest-substring-between-two-equal-characters/ +// discuss: https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_length_between_equal_characters(s: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1624() { + } +} diff --git a/src/problem/p1632_rank_transform_of_a_matrix.rs b/src/problem/p1632_rank_transform_of_a_matrix.rs new file mode 100644 index 00000000..78f09d16 --- /dev/null +++ b/src/problem/p1632_rank_transform_of_a_matrix.rs @@ -0,0 +1,70 @@ +/** + * [1632] Rank Transform of a Matrix + * + * Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col]. + * The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules: + * + * The rank is an integer starting from 1. + * If two elements p and q are in the same row or column, then: + * + * If p < q then rank(p) < rank(q) + * If p == q then rank(p) == rank(q) + * If p > q then rank(p) > rank(q) + * + * + * The rank should be as small as possible. + * + * The test cases are generated so that answer is unique under the given rules. + * + * Example 1: + * + * Input: matrix = [[1,2],[3,4]] + * Output: [[1,2],[2,3]] + * Explanation: + * The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column. + * The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1. + * The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1. + * The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2. + * + * Example 2: + * + * Input: matrix = [[7,7],[7,7]] + * Output: [[1,1],[1,1]] + * + * Example 3: + * + * Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]] + * Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]] + * + * + * Constraints: + * + * m == matrix.length + * n == matrix[i].length + * 1 <= m, n <= 500 + * -10^9 <= matrix[row][col] <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/rank-transform-of-a-matrix/ +// discuss: https://leetcode.com/problems/rank-transform-of-a-matrix/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn matrix_rank_transform(matrix: Vec>) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1632() { + } +} diff --git a/src/problem/p1637_widest_vertical_area_between_two_points_containing_no_points.rs b/src/problem/p1637_widest_vertical_area_between_two_points_containing_no_points.rs new file mode 100644 index 00000000..51592524 --- /dev/null +++ b/src/problem/p1637_widest_vertical_area_between_two_points_containing_no_points.rs @@ -0,0 +1,50 @@ +/** + * [1637] Widest Vertical Area Between Two Points Containing No Points + * + * Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. + * A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. + * Note that points on the edge of a vertical area are not considered included in the area. + * + * Example 1: + * ​ + * Input: points = [[8,7],[9,9],[7,4],[9,7]] + * Output: 1 + * Explanation: Both the red and the blue area are optimal. + * + * Example 2: + * + * Input: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]] + * Output: 3 + * + * + * Constraints: + * + * n == points.length + * 2 <= n <= 10^5 + * points[i].length == 2 + * 0 <= xi, yi <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/ +// discuss: https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_width_of_vertical_area(points: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1637() { + } +} diff --git a/src/problem/p1638_count_substrings_that_differ_by_one_character.rs b/src/problem/p1638_count_substrings_that_differ_by_one_character.rs new file mode 100644 index 00000000..43f86272 --- /dev/null +++ b/src/problem/p1638_count_substrings_that_differ_by_one_character.rs @@ -0,0 +1,60 @@ +/** + * [1638] Count Substrings That Differ by One Character + * + * Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character. + * For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way. + * Return the number of substrings that satisfy the condition above. + * A substring is a contiguous sequence of characters within a string. + * + * Example 1: + * + * Input: s = "aba", t = "baba" + * Output: 6 + * Explanation: The following are the pairs of substrings from s and t that differ by exactly 1 character: + * ("aba", "baba") + * ("aba", "baba") + * ("aba", "baba") + * ("aba", "baba") + * ("aba", "baba") + * ("aba", "baba") + * The underlined portions are the substrings that are chosen from s and t. + * ​​Example 2: + * + * Input: s = "ab", t = "bb" + * Output: 3 + * Explanation: The following are the pairs of substrings from s and t that differ by 1 character: + * ("ab", "bb") + * ("ab", "bb") + * ("ab", "bb") + * ​​​​The underlined portions are the substrings that are chosen from s and t. + * + * + * Constraints: + * + * 1 <= s.length, t.length <= 100 + * s and t consist of lowercase English letters only. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-substrings-that-differ-by-one-character/ +// discuss: https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_substrings(s: String, t: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1638() { + } +} diff --git a/src/problem/p1663_smallest_string_with_a_given_numeric_value.rs b/src/problem/p1663_smallest_string_with_a_given_numeric_value.rs new file mode 100644 index 00000000..3e0d9aa5 --- /dev/null +++ b/src/problem/p1663_smallest_string_with_a_given_numeric_value.rs @@ -0,0 +1,49 @@ +/** + * [1663] Smallest String With A Given Numeric Value + * + * The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on. + * The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8. + * You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k. + * Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. + * + * Example 1: + * + * Input: n = 3, k = 27 + * Output: "aay" + * Explanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. + * + * Example 2: + * + * Input: n = 5, k = 73 + * Output: "aaszz" + * + * + * Constraints: + * + * 1 <= n <= 10^5 + * n <= k <= 26 * n + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/ +// discuss: https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn get_smallest_string(n: i32, k: i32) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1663() { + } +} diff --git a/src/problem/p1671_minimum_number_of_removals_to_make_mountain_array.rs b/src/problem/p1671_minimum_number_of_removals_to_make_mountain_array.rs new file mode 100644 index 00000000..85662e80 --- /dev/null +++ b/src/problem/p1671_minimum_number_of_removals_to_make_mountain_array.rs @@ -0,0 +1,58 @@ +/** + * [1671] Minimum Number of Removals to Make Mountain Array + * + * You may recall that an array arr is a mountain array if and only if: + * + * arr.length >= 3 + * There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: + * + * arr[0] < arr[1] < ... < arr[i - 1] < arr[i] + * arr[i] > arr[i + 1] > ... > arr[arr.length - 1] + * + * + * + * Given an integer array nums​​​, return the minimum number of elements to remove to make nums​​​ a mountain array. + * + * Example 1: + * + * Input: nums = [1,3,1] + * Output: 0 + * Explanation: The array itself is a mountain array so we do not need to remove any elements. + * + * Example 2: + * + * Input: nums = [2,1,1,5,6,2,3,1] + * Output: 3 + * Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1]. + * + * + * Constraints: + * + * 3 <= nums.length <= 1000 + * 1 <= nums[i] <= 10^9 + * It is guaranteed that you can make a mountain array out of nums. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/ +// discuss: https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn minimum_mountain_removals(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1671() { + } +} diff --git a/src/problem/p1679_max_number_of_k_sum_pairs.rs b/src/problem/p1679_max_number_of_k_sum_pairs.rs new file mode 100644 index 00000000..b7c0575f --- /dev/null +++ b/src/problem/p1679_max_number_of_k_sum_pairs.rs @@ -0,0 +1,53 @@ +/** + * [1679] Max Number of K-Sum Pairs + * + * You are given an integer array nums and an integer k. + * In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. + * Return the maximum number of operations you can perform on the array. + * + * Example 1: + * + * Input: nums = [1,2,3,4], k = 5 + * Output: 2 + * Explanation: Starting with nums = [1,2,3,4]: + * - Remove numbers 1 and 4, then nums = [2,3] + * - Remove numbers 2 and 3, then nums = [] + * There are no more pairs that sum up to 5, hence a total of 2 operations. + * Example 2: + * + * Input: nums = [3,1,3,4,3], k = 6 + * Output: 1 + * Explanation: Starting with nums = [3,1,3,4,3]: + * - Remove the first two 3's, then nums = [1,4,3] + * There are no more pairs that sum up to 6, hence a total of 1 operation. + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * 1 <= nums[i] <= 10^9 + * 1 <= k <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/max-number-of-k-sum-pairs/ +// discuss: https://leetcode.com/problems/max-number-of-k-sum-pairs/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_operations(nums: Vec, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1679() { + } +} diff --git a/src/problem/p1681_minimum_incompatibility.rs b/src/problem/p1681_minimum_incompatibility.rs new file mode 100644 index 00000000..482f3875 --- /dev/null +++ b/src/problem/p1681_minimum_incompatibility.rs @@ -0,0 +1,59 @@ +/** + * [1681] Minimum Incompatibility + * + * You are given an integer array nums​​​ and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset. + * A subset's incompatibility is the difference between the maximum and minimum elements in that array. + * Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible. + * A subset is a group integers that appear in the array with no particular order. + * + * Example 1: + * + * Input: nums = [1,2,1,4], k = 2 + * Output: 4 + * Explanation: The optimal distribution of subsets is [1,2] and [1,4]. + * The incompatibility is (2-1) + (4-1) = 4. + * Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements. + * Example 2: + * + * Input: nums = [6,3,8,1,3,1,2,2], k = 4 + * Output: 6 + * Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3]. + * The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6. + * + * Example 3: + * + * Input: nums = [5,3,3,6,3,3], k = 3 + * Output: -1 + * Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset. + * + * + * Constraints: + * + * 1 <= k <= nums.length <= 16 + * nums.length is divisible by k + * 1 <= nums[i] <= nums.length + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-incompatibility/ +// discuss: https://leetcode.com/problems/minimum-incompatibility/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn minimum_incompatibility(nums: Vec, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1681() { + } +} diff --git a/src/problem/p1686_stone_game_vi.rs b/src/problem/p1686_stone_game_vi.rs new file mode 100644 index 00000000..673a5be5 --- /dev/null +++ b/src/problem/p1686_stone_game_vi.rs @@ -0,0 +1,71 @@ +/** + * [1686] Stone Game VI + * + * Alice and Bob take turns playing a game, with Alice starting first. + * There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently. + * You are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the i^th stone. + * The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally. Both players know the other's values. + * Determine the result of the game, and: + * + * If Alice wins, return 1. + * If Bob wins, return -1. + * If the game results in a draw, return 0. + * + * + * Example 1: + * + * Input: aliceValues = [1,3], bobValues = [2,1] + * Output: 1 + * Explanation: + * If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points. + * Bob can only choose stone 0, and will only receive 2 points. + * Alice wins. + * + * Example 2: + * + * Input: aliceValues = [1,2], bobValues = [3,1] + * Output: 0 + * Explanation: + * If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point. + * Draw. + * + * Example 3: + * + * Input: aliceValues = [2,4,3], bobValues = [1,6,7] + * Output: -1 + * Explanation: + * Regardless of how Alice plays, Bob will be able to have more points than Alice. + * For example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7. + * Bob wins. + * + * + * Constraints: + * + * n == aliceValues.length == bobValues.length + * 1 <= n <= 10^5 + * 1 <= aliceValues[i], bobValues[i] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/stone-game-vi/ +// discuss: https://leetcode.com/problems/stone-game-vi/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn stone_game_vi(alice_values: Vec, bob_values: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1686() { + } +} diff --git a/src/problem/p1697_checking_existence_of_edge_length_limited_paths.rs b/src/problem/p1697_checking_existence_of_edge_length_limited_paths.rs new file mode 100644 index 00000000..bfd1893e --- /dev/null +++ b/src/problem/p1697_checking_existence_of_edge_length_limited_paths.rs @@ -0,0 +1,58 @@ +/** + * [1697] Checking Existence of Edge Length Limited Paths + * + * An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes. + * Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj . + * Return a boolean array answer, where answer.length == queries.length and the j^th value of answer is true if there is a path for queries[j] is true, and false otherwise. + * + * Example 1: + * + * Input: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]] + * Output: [false,true] + * Explanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16. + * For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query. + * For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query. + * + * Example 2: + * + * Input: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]] + * Output: [true,false] + * Exaplanation: The above figure shows the given graph. + * + * + * Constraints: + * + * 2 <= n <= 10^5 + * 1 <= edgeList.length, queries.length <= 10^5 + * edgeList[i].length == 3 + * queries[j].length == 3 + * 0 <= ui, vi, pj, qj <= n - 1 + * ui != vi + * pj != qj + * 1 <= disi, limitj <= 10^9 + * There may be multiple edges between two nodes. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/ +// discuss: https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn distance_limited_paths_exist(n: i32, edge_list: Vec>, queries: Vec>) -> Vec { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1697() { + } +} diff --git a/src/problem/p1703_minimum_adjacent_swaps_for_k_consecutive_ones.rs b/src/problem/p1703_minimum_adjacent_swaps_for_k_consecutive_ones.rs new file mode 100644 index 00000000..8cb081d8 --- /dev/null +++ b/src/problem/p1703_minimum_adjacent_swaps_for_k_consecutive_ones.rs @@ -0,0 +1,55 @@ +/** + * [1703] Minimum Adjacent Swaps for K Consecutive Ones + * + * You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values. + * Return the minimum number of moves required so that nums has k consecutive 1's. + * + * Example 1: + * + * Input: nums = [1,0,0,1,0,1], k = 2 + * Output: 1 + * Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's. + * + * Example 2: + * + * Input: nums = [1,0,0,0,0,0,1,1], k = 3 + * Output: 5 + * Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1]. + * + * Example 3: + * + * Input: nums = [1,1,0,1], k = 2 + * Output: 0 + * Explanation: nums already has 2 consecutive 1's. + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * nums[i] is 0 or 1. + * 1 <= k <= sum(nums) + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/ +// discuss: https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_moves(nums: Vec, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1703() { + } +} diff --git a/src/problem/p1711_count_good_meals.rs b/src/problem/p1711_count_good_meals.rs new file mode 100644 index 00000000..82cf0caa --- /dev/null +++ b/src/problem/p1711_count_good_meals.rs @@ -0,0 +1,50 @@ +/** + * [1711] Count Good Meals + * + * A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. + * You can pick any two different foods to make a good meal. + * Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i^​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 10^9 + 7. + * Note that items with different indices are considered different even if they have the same deliciousness value. + * + * Example 1: + * + * Input: deliciousness = [1,3,5,7,9] + * Output: 4 + * Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9). + * Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. + * + * Example 2: + * + * Input: deliciousness = [1,1,1,3,3,3,7] + * Output: 15 + * Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. + * + * Constraints: + * + * 1 <= deliciousness.length <= 10^5 + * 0 <= deliciousness[i] <= 2^20 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-good-meals/ +// discuss: https://leetcode.com/problems/count-good-meals/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_pairs(deliciousness: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1711() { + } +} diff --git a/src/problem/p1713_minimum_operations_to_make_a_subsequence.rs b/src/problem/p1713_minimum_operations_to_make_a_subsequence.rs new file mode 100644 index 00000000..7b3211c3 --- /dev/null +++ b/src/problem/p1713_minimum_operations_to_make_a_subsequence.rs @@ -0,0 +1,50 @@ +/** + * [1713] Minimum Operations to Make a Subsequence + * + * You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. + * In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array. + * Return the minimum number of operations needed to make target a subsequence of arr. + * A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not. + * + * Example 1: + * + * Input: target = [5,1,3], arr = [9,4,2,3,4] + * Output: 2 + * Explanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr. + * + * Example 2: + * + * Input: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1] + * Output: 3 + * + * + * Constraints: + * + * 1 <= target.length, arr.length <= 10^5 + * 1 <= target[i], arr[i] <= 10^9 + * target contains no duplicates. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/ +// discuss: https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_operations(target: Vec, arr: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1713() { + } +} diff --git a/src/problem/p1721_swapping_nodes_in_a_linked_list.rs b/src/problem/p1721_swapping_nodes_in_a_linked_list.rs new file mode 100644 index 00000000..408716d2 --- /dev/null +++ b/src/problem/p1721_swapping_nodes_in_a_linked_list.rs @@ -0,0 +1,64 @@ +/** + * [1721] Swapping Nodes in a Linked List + * + * You are given the head of a linked list, and an integer k. + * Return the head of the linked list after swapping the values of the k^th node from the beginning and the k^th node from the end (the list is 1-indexed). + * + * Example 1: + * + * Input: head = [1,2,3,4,5], k = 2 + * Output: [1,4,3,2,5] + * + * Example 2: + * + * Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5 + * Output: [7,9,6,6,8,7,3,0,9,5] + * + * + * Constraints: + * + * The number of nodes in the list is n. + * 1 <= k <= n <= 10^5 + * 0 <= Node.val <= 100 + * + */ +pub struct Solution {} +use crate::util::linked_list::{ListNode, to_list}; + +// problem: https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ +// discuss: https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn swap_nodes(head: Option>, k: i32) -> Option> { + Some(Box::new(ListNode::new(0))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1721() { + } +} diff --git a/src/problem/p1738_find_kth_largest_xor_coordinate_value.rs b/src/problem/p1738_find_kth_largest_xor_coordinate_value.rs new file mode 100644 index 00000000..02ebaa92 --- /dev/null +++ b/src/problem/p1738_find_kth_largest_xor_coordinate_value.rs @@ -0,0 +1,57 @@ +/** + * [1738] Find Kth Largest XOR Coordinate Value + * + * You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k. + * The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). + * Find the k^th largest value (1-indexed) of all the coordinates of matrix. + * + * Example 1: + * + * Input: matrix = [[5,2],[1,6]], k = 1 + * Output: 7 + * Explanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value. + * + * Example 2: + * + * Input: matrix = [[5,2],[1,6]], k = 2 + * Output: 5 + * Explanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value. + * + * Example 3: + * + * Input: matrix = [[5,2],[1,6]], k = 3 + * Output: 4 + * Explanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value. + * + * Constraints: + * + * m == matrix.length + * n == matrix[i].length + * 1 <= m, n <= 1000 + * 0 <= matrix[i][j] <= 10^6 + * 1 <= k <= m * n + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/ +// discuss: https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn kth_largest_value(matrix: Vec>, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1738() { + } +} diff --git a/src/problem/p1750_minimum_length_of_string_after_deleting_similar_ends.rs b/src/problem/p1750_minimum_length_of_string_after_deleting_similar_ends.rs new file mode 100644 index 00000000..d9f88c57 --- /dev/null +++ b/src/problem/p1750_minimum_length_of_string_after_deleting_similar_ends.rs @@ -0,0 +1,66 @@ +/** + * [1750] Minimum Length of String After Deleting Similar Ends + * + * Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times: + *
    + * Pick a non-empty prefix from the string s where all the characters in the prefix are equal. + * Pick a non-empty suffix from the string s where all the characters in this suffix are equal. + * The prefix and the suffix should not intersect at any index. + * The characters from the prefix and suffix must be the same. + * Delete both the prefix and the suffix. + *
+ * Return the minimum length of s after performing the above operation any number of times (possibly zero times). + * + * Example 1: + * + * Input: s = "ca" + * Output: 2 + * Explanation: You can't remove any characters, so the string stays as is. + * + * Example 2: + * + * Input: s = "cabaabac" + * Output: 0 + * Explanation: An optimal sequence of operations is: + * - Take prefix = "c" and suffix = "c" and remove them, s = "abaaba". + * - Take prefix = "a" and suffix = "a" and remove them, s = "baab". + * - Take prefix = "b" and suffix = "b" and remove them, s = "aa". + * - Take prefix = "a" and suffix = "a" and remove them, s = "". + * Example 3: + * + * Input: s = "aabccabba" + * Output: 3 + * Explanation: An optimal sequence of operations is: + * - Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". + * - Take prefix = "b" and suffix = "bb" and remove them, s = "cca". + * + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s only consists of characters 'a', 'b', and 'c'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/ +// discuss: https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn minimum_length(s: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1750() { + } +} diff --git a/src/problem/p1755_closest_subsequence_sum.rs b/src/problem/p1755_closest_subsequence_sum.rs new file mode 100644 index 00000000..ba1a088a --- /dev/null +++ b/src/problem/p1755_closest_subsequence_sum.rs @@ -0,0 +1,58 @@ +/** + * [1755] Closest Subsequence Sum + * + * You are given an integer array nums and an integer goal. + * You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal). + * Return the minimum possible value of abs(sum - goal). + * Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array. + * + * Example 1: + * + * Input: nums = [5,-7,3,5], goal = 6 + * Output: 0 + * Explanation: Choose the whole array as a subsequence, with a sum of 6. + * This is equal to the goal, so the absolute difference is 0. + * + * Example 2: + * + * Input: nums = [7,-9,15,-2], goal = -5 + * Output: 1 + * Explanation: Choose the subsequence [7,-9,-2], with a sum of -4. + * The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum. + * + * Example 3: + * + * Input: nums = [1,2,3], goal = -7 + * Output: 7 + * + * + * Constraints: + * + * 1 <= nums.length <= 40 + * -10^7 <= nums[i] <= 10^7 + * -10^9 <= goal <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/closest-subsequence-sum/ +// discuss: https://leetcode.com/problems/closest-subsequence-sum/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_abs_difference(nums: Vec, goal: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1755() { + } +} diff --git a/src/problem/p1761_minimum_degree_of_a_connected_trio_in_a_graph.rs b/src/problem/p1761_minimum_degree_of_a_connected_trio_in_a_graph.rs new file mode 100644 index 00000000..f2cf4b9b --- /dev/null +++ b/src/problem/p1761_minimum_degree_of_a_connected_trio_in_a_graph.rs @@ -0,0 +1,57 @@ +/** + * [1761] Minimum Degree of a Connected Trio in a Graph + * + * You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. + * A connected trio is a set of three nodes where there is an edge between every pair of them. + * The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. + * Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios. + * + * Example 1: + * + * Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]] + * Output: 3 + * Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above. + * + * Example 2: + * + * Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]] + * Output: 0 + * Explanation: There are exactly three trios: + * 1) [1,4,3] with degree 0. + * 2) [2,5,6] with degree 2. + * 3) [5,6,7] with degree 2. + * + * + * Constraints: + * + * 2 <= n <= 400 + * edges[i].length == 2 + * 1 <= edges.length <= n * (n-1) / 2 + * 1 <= ui, vi <= n + * ui != vi + * There are no repeated edges. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/ +// discuss: https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_trio_degree(n: i32, edges: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1761() { + } +} diff --git a/src/problem/p1766_tree_of_coprimes.rs b/src/problem/p1766_tree_of_coprimes.rs new file mode 100644 index 00000000..761e981f --- /dev/null +++ b/src/problem/p1766_tree_of_coprimes.rs @@ -0,0 +1,63 @@ +/** + * [1766] Tree of Coprimes + * + * There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0. + * To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the i^th node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree. + * Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y. + * An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself. + * Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor. + * + * Example 1: + * + * + * Input: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]] + * Output: [-1,0,0,1] + * Explanation: In the above figure, each node's value is in parentheses. + * - Node 0 has no coprime ancestors. + * - Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1). + * - Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's + * value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor. + * - Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its + * closest valid ancestor. + * + * Example 2: + * + * + * Input: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]] + * Output: [-1,0,-1,0,0,0,-1] + * + * + * Constraints: + * + * nums.length == n + * 1 <= nums[i] <= 50 + * 1 <= n <= 10^5 + * edges.length == n - 1 + * edges[j].length == 2 + * 0 <= uj, vj < n + * uj != vj + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/tree-of-coprimes/ +// discuss: https://leetcode.com/problems/tree-of-coprimes/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn get_coprimes(nums: Vec, edges: Vec>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1766() { + } +} diff --git a/src/problem/p1773_count_items_matching_a_rule.rs b/src/problem/p1773_count_items_matching_a_rule.rs new file mode 100644 index 00000000..6db28b3c --- /dev/null +++ b/src/problem/p1773_count_items_matching_a_rule.rs @@ -0,0 +1,55 @@ +/** + * [1773] Count Items Matching a Rule + * + * You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the i^th item. You are also given a rule represented by two strings, ruleKey and ruleValue. + * The i^th item is said to match the rule if one of the following is true: + * + * ruleKey == "type" and ruleValue == typei. + * ruleKey == "color" and ruleValue == colori. + * ruleKey == "name" and ruleValue == namei. + * + * Return the number of items that match the given rule. + * + * Example 1: + * + * Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver" + * Output: 1 + * Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"]. + * + * Example 2: + * + * Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone" + * Output: 2 + * Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match. + * + * Constraints: + * + * 1 <= items.length <= 10^4 + * 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10 + * ruleKey is equal to either "type", "color", or "name". + * All strings consist only of lowercase letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-items-matching-a-rule/ +// discuss: https://leetcode.com/problems/count-items-matching-a-rule/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_matches(items: Vec>, rule_key: String, rule_value: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1773() { + } +} diff --git a/src/problem/p1779_find_nearest_point_that_has_the_same_x_or_y_coordinate.rs b/src/problem/p1779_find_nearest_point_that_has_the_same_x_or_y_coordinate.rs new file mode 100644 index 00000000..93cf506f --- /dev/null +++ b/src/problem/p1779_find_nearest_point_that_has_the_same_x_or_y_coordinate.rs @@ -0,0 +1,53 @@ +/** + * [1779] Find Nearest Point That Has the Same X or Y Coordinate + * + * You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location. + * Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1. + * The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2). + * + * Example 1: + * + * Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]] + * Output: 2 + * Explanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2. + * Example 2: + * + * Input: x = 3, y = 4, points = [[3,4]] + * Output: 0 + * Explanation: The answer is allowed to be on the same location as your current location. + * Example 3: + * + * Input: x = 3, y = 4, points = [[2,3]] + * Output: -1 + * Explanation: There are no valid points. + * + * Constraints: + * + * 1 <= points.length <= 10^4 + * points[i].length == 2 + * 1 <= x, y, ai, bi <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/ +// discuss: https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn nearest_valid_point(x: i32, y: i32, points: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1779() { + } +} diff --git a/src/problem/p1780_check_if_number_is_a_sum_of_powers_of_three.rs b/src/problem/p1780_check_if_number_is_a_sum_of_powers_of_three.rs new file mode 100644 index 00000000..77127db8 --- /dev/null +++ b/src/problem/p1780_check_if_number_is_a_sum_of_powers_of_three.rs @@ -0,0 +1,52 @@ +/** + * [1780] Check if Number is a Sum of Powers of Three + * + * Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false. + * An integer y is a power of three if there exists an integer x such that y == 3^x. + * + * Example 1: + * + * Input: n = 12 + * Output: true + * Explanation: 12 = 3^1 + 3^2 + * + * Example 2: + * + * Input: n = 91 + * Output: true + * Explanation: 91 = 3^0 + 3^2 + 3^4 + * + * Example 3: + * + * Input: n = 21 + * Output: false + * + * + * Constraints: + * + * 1 <= n <= 10^7 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/ +// discuss: https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn check_powers_of_three(n: i32) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1780() { + } +} diff --git a/src/problem/p1786_number_of_restricted_paths_from_first_to_last_node.rs b/src/problem/p1786_number_of_restricted_paths_from_first_to_last_node.rs new file mode 100644 index 00000000..214429ac --- /dev/null +++ b/src/problem/p1786_number_of_restricted_paths_from_first_to_last_node.rs @@ -0,0 +1,59 @@ +/** + * [1786] Number of Restricted Paths From First to Last Node + * + * There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti. + * A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1. + * The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1. + * Return the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 10^9 + 7. + * + * Example 1: + * + * Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]] + * Output: 3 + * Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are: + * 1) 1 --> 2 --> 5 + * 2) 1 --> 2 --> 3 --> 5 + * 3) 1 --> 3 --> 5 + * + * Example 2: + * + * Input: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]] + * Output: 1 + * Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7. + * + * + * Constraints: + * + * 1 <= n <= 2 * 10^4 + * n - 1 <= edges.length <= 4 * 10^4 + * edges[i].length == 3 + * 1 <= ui, vi <= n + * ui != vi + * 1 <= weighti <= 10^5 + * There is at most one edge between any two nodes. + * There is at least one path between any two nodes. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/ +// discuss: https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_restricted_paths(n: i32, edges: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1786() { + } +} diff --git a/src/problem/p1802_maximum_value_at_a_given_index_in_a_bounded_array.rs b/src/problem/p1802_maximum_value_at_a_given_index_in_a_bounded_array.rs new file mode 100644 index 00000000..0c301005 --- /dev/null +++ b/src/problem/p1802_maximum_value_at_a_given_index_in_a_bounded_array.rs @@ -0,0 +1,56 @@ +/** + * [1802] Maximum Value at a Given Index in a Bounded Array + * + * You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions: + * + * nums.length == n + * nums[i] is a positive integer where 0 <= i < n. + * abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1. + * The sum of all the elements of nums does not exceed maxSum. + * nums[index] is maximized. + * + * Return nums[index] of the constructed array. + * Note that abs(x) equals x if x >= 0, and -x otherwise. + * + * Example 1: + * + * Input: n = 4, index = 2, maxSum = 6 + * Output: 2 + * Explanation: nums = [1,2,2,1] is one array that satisfies all the conditions. + * There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2]. + * + * Example 2: + * + * Input: n = 6, index = 1, maxSum = 10 + * Output: 3 + * + * + * Constraints: + * + * 1 <= n <= maxSum <= 10^9 + * 0 <= index < n + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/ +// discuss: https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_value(n: i32, index: i32, max_sum: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1802() { + } +} diff --git a/src/problem/p1818_minimum_absolute_sum_difference.rs b/src/problem/p1818_minimum_absolute_sum_difference.rs new file mode 100644 index 00000000..448efaaf --- /dev/null +++ b/src/problem/p1818_minimum_absolute_sum_difference.rs @@ -0,0 +1,68 @@ +/** + * [1818] Minimum Absolute Sum Difference + * + * You are given two positive integer arrays nums1 and nums2, both of length n. + * The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). + * You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference. + * Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 10^9 + 7. + * |x| is defined as: + * + * x if x >= 0, or + * -x if x < 0. + * + * + * Example 1: + * + * Input: nums1 = [1,7,5], nums2 = [2,3,5] + * Output: 3 + * Explanation: There are two possible optimal solutions: + * - Replace the second element with the first: [1,7,5] => [1,1,5], or + * - Replace the second element with the third: [1,7,5] => [1,5,5]. + * Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3. + * + * Example 2: + * + * Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10] + * Output: 0 + * Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an + * absolute sum difference of 0. + * + * Example 3: + * + * Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4] + * Output: 20 + * Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7]. + * This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20 + * + * + * Constraints: + * + * n == nums1.length + * n == nums2.length + * 1 <= n <= 10^5 + * 1 <= nums1[i], nums2[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-absolute-sum-difference/ +// discuss: https://leetcode.com/problems/minimum-absolute-sum-difference/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_absolute_sum_diff(nums1: Vec, nums2: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1818() { + } +} diff --git a/src/problem/p1822_sign_of_the_product_of_an_array.rs b/src/problem/p1822_sign_of_the_product_of_an_array.rs new file mode 100644 index 00000000..3bf03a63 --- /dev/null +++ b/src/problem/p1822_sign_of_the_product_of_an_array.rs @@ -0,0 +1,60 @@ +/** + * [1822] Sign of the Product of an Array + * + * There is a function signFunc(x) that returns: + * + * 1 if x is positive. + * -1 if x is negative. + * 0 if x is equal to 0. + * + * You are given an integer array nums. Let product be the product of all values in the array nums. + * Return signFunc(product). + * + * Example 1: + * + * Input: nums = [-1,-2,-3,-4,3,2,1] + * Output: 1 + * Explanation: The product of all values in the array is 144, and signFunc(144) = 1 + * + * Example 2: + * + * Input: nums = [1,5,0,2,-3] + * Output: 0 + * Explanation: The product of all values in the array is 0, and signFunc(0) = 0 + * + * Example 3: + * + * Input: nums = [-1,1,-1,1,-1] + * Output: -1 + * Explanation: The product of all values in the array is -1, and signFunc(-1) = -1 + * + * + * Constraints: + * + * 1 <= nums.length <= 1000 + * -100 <= nums[i] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/sign-of-the-product-of-an-array/ +// discuss: https://leetcode.com/problems/sign-of-the-product-of-an-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn array_sign(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1822() { + } +} diff --git a/src/problem/p1830_minimum_number_of_operations_to_make_string_sorted.rs b/src/problem/p1830_minimum_number_of_operations_to_make_string_sorted.rs new file mode 100644 index 00000000..c5dd0a2c --- /dev/null +++ b/src/problem/p1830_minimum_number_of_operations_to_make_string_sorted.rs @@ -0,0 +1,61 @@ +/** + * [1830] Minimum Number of Operations to Make String Sorted + * + * You are given a string s (0-indexed)​​​​​​. You are asked to perform the following operation on s​​​​​​ until you get a sorted string: + *
    + * Find the largest index i such that 1 <= i < s.length and s[i] < s[i - 1]. + * Find the largest index j such that i <= j < s.length and s[k] < s[i - 1] for all the possible values of k in the range [i, j] inclusive. + * Swap the two characters at indices i - 1​​​​ and j​​​​​. + * Reverse the suffix starting at index i​​​​​​. + *
+ * Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 10^9 + 7. + * + * Example 1: + * + * Input: s = "cba" + * Output: 5 + * Explanation: The simulation goes as follows: + * Operation 1: i=2, j=2. Swap s[1] and s[2] to get s="cab", then reverse the suffix starting at 2. Now, s="cab". + * Operation 2: i=1, j=2. Swap s[0] and s[2] to get s="bac", then reverse the suffix starting at 1. Now, s="bca". + * Operation 3: i=2, j=2. Swap s[1] and s[2] to get s="bac", then reverse the suffix starting at 2. Now, s="bac". + * Operation 4: i=1, j=1. Swap s[0] and s[1] to get s="abc", then reverse the suffix starting at 1. Now, s="acb". + * Operation 5: i=2, j=2. Swap s[1] and s[2] to get s="abc", then reverse the suffix starting at 2. Now, s="abc". + * + * Example 2: + * + * Input: s = "aabaa" + * Output: 2 + * Explanation: The simulation goes as follows: + * Operation 1: i=3, j=4. Swap s[2] and s[4] to get s="aaaab", then reverse the substring starting at 3. Now, s="aaaba". + * Operation 2: i=4, j=4. Swap s[3] and s[4] to get s="aaaab", then reverse the substring starting at 4. Now, s="aaaab". + * + * + * Constraints: + * + * 1 <= s.length <= 3000 + * s​​​​​​ consists only of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/ +// discuss: https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn make_string_sorted(s: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1830() { + } +} diff --git a/src/problem/p1838_frequency_of_the_most_frequent_element.rs b/src/problem/p1838_frequency_of_the_most_frequent_element.rs new file mode 100644 index 00000000..1add0bff --- /dev/null +++ b/src/problem/p1838_frequency_of_the_most_frequent_element.rs @@ -0,0 +1,58 @@ +/** + * [1838] Frequency of the Most Frequent Element + * + * The frequency of an element is the number of times it occurs in an array. + * You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1. + * Return the maximum possible frequency of an element after performing at most k operations. + * + * Example 1: + * + * Input: nums = [1,2,4], k = 5 + * Output: 3 + * Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4]. + * 4 has a frequency of 3. + * Example 2: + * + * Input: nums = [1,4,8,13], k = 5 + * Output: 2 + * Explanation: There are multiple optimal solutions: + * - Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2. + * - Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2. + * - Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2. + * + * Example 3: + * + * Input: nums = [3,9,6], k = 2 + * Output: 1 + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * 1 <= nums[i] <= 10^5 + * 1 <= k <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/frequency-of-the-most-frequent-element/ +// discuss: https://leetcode.com/problems/frequency-of-the-most-frequent-element/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_frequency(nums: Vec, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1838() { + } +} diff --git a/src/problem/p1845_seat_reservation_manager.rs b/src/problem/p1845_seat_reservation_manager.rs new file mode 100644 index 00000000..66a6f515 --- /dev/null +++ b/src/problem/p1845_seat_reservation_manager.rs @@ -0,0 +1,87 @@ +/** + * [1845] Seat Reservation Manager + * + * Design a system that manages the reservation state of n seats that are numbered from 1 to n. + * Implement the SeatManager class: + * + * SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available. + * int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number. + * void unreserve(int seatNumber) Unreserves the seat with the given seatNumber. + * + * + * Example 1: + * + * Input + * ["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"] + * [[5], [], [], [2], [], [], [], [], [5]] + * Output + * [null, 1, 2, null, 2, 3, 4, 5, null] + * Explanation + * SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats. + * seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1. + * seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2. + * seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5]. + * seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2. + * seatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3. + * seatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4. + * seatManager.reserve(); // The only available seat is seat 5, so return 5. + * seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5]. + * + * + * Constraints: + * + * 1 <= n <= 10^5 + * 1 <= seatNumber <= n + * For each call to reserve, it is guaranteed that there will be at least one unreserved seat. + * For each call to unreserve, it is guaranteed that seatNumber will be reserved. + * At most 10^5 calls in total will be made to reserve and unreserve. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/seat-reservation-manager/ +// discuss: https://leetcode.com/problems/seat-reservation-manager/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct SeatManager { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl SeatManager { + + fn new(n: i32) -> Self { + + } + + fn reserve(&self) -> i32 { + + } + + fn unreserve(&self, seat_number: i32) { + + } +} + +/** + * Your SeatManager object will be instantiated and called as such: + * let obj = SeatManager::new(n); + * let ret_1: i32 = obj.reserve(); + * obj.unreserve(seatNumber); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1845() { + } +} diff --git a/src/problem/p1855_maximum_distance_between_a_pair_of_values.rs b/src/problem/p1855_maximum_distance_between_a_pair_of_values.rs new file mode 100644 index 00000000..8d275567 --- /dev/null +++ b/src/problem/p1855_maximum_distance_between_a_pair_of_values.rs @@ -0,0 +1,60 @@ +/** + * [1855] Maximum Distance Between a Pair of Values + * + * You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​. + * A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i​​​​. + * Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0. + * An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length. + * + * Example 1: + * + * Input: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5] + * Output: 2 + * Explanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4). + * The maximum distance is 2 with pair (2,4). + * + * Example 2: + * + * Input: nums1 = [2,2,2], nums2 = [10,10,1] + * Output: 1 + * Explanation: The valid pairs are (0,0), (0,1), and (1,1). + * The maximum distance is 1 with pair (0,1). + * + * Example 3: + * + * Input: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25] + * Output: 2 + * Explanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4). + * The maximum distance is 2 with pair (2,4). + * + * + * Constraints: + * + * 1 <= nums1.length, nums2.length <= 10^5 + * 1 <= nums1[i], nums2[j] <= 10^5 + * Both nums1 and nums2 are non-increasing. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/ +// discuss: https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_distance(nums1: Vec, nums2: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1855() { + } +} diff --git a/src/problem/p1860_incremental_memory_leak.rs b/src/problem/p1860_incremental_memory_leak.rs new file mode 100644 index 00000000..fee05cb9 --- /dev/null +++ b/src/problem/p1860_incremental_memory_leak.rs @@ -0,0 +1,57 @@ +/** + * [1860] Incremental Memory Leak + * + * You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. + * At the i^th second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes. + * Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively. + * + * Example 1: + * + * Input: memory1 = 2, memory2 = 2 + * Output: [3,1,0] + * Explanation: The memory is allocated as follows: + * - At the 1^st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory. + * - At the 2^nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory. + * - At the 3^rd second, the program crashes. The sticks have 1 and 0 bits available respectively. + * + * Example 2: + * + * Input: memory1 = 8, memory2 = 11 + * Output: [6,0,4] + * Explanation: The memory is allocated as follows: + * - At the 1^st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory. + * - At the 2^nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory. + * - At the 3^rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory. + * - At the 4^th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory. + * - At the 5^th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory. + * - At the 6^th second, the program crashes. The sticks have 0 and 4 bits available respectively. + * + * + * Constraints: + * + * 0 <= memory1, memory2 <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/incremental-memory-leak/ +// discuss: https://leetcode.com/problems/incremental-memory-leak/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn mem_leak(memory1: i32, memory2: i32) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1860() { + } +} diff --git a/src/problem/p1871_jump_game_vii.rs b/src/problem/p1871_jump_game_vii.rs new file mode 100644 index 00000000..9a0b1f1a --- /dev/null +++ b/src/problem/p1871_jump_game_vii.rs @@ -0,0 +1,55 @@ +/** + * [1871] Jump Game VII + * + * You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled: + * + * i + minJump <= j <= min(i + maxJump, s.length - 1), and + * s[j] == '0'. + * + * Return true if you can reach index s.length - 1 in s, or false otherwise. + * + * Example 1: + * + * Input: s = "011010", minJump = 2, maxJump = 3 + * Output: true + * Explanation: + * In the first step, move from index 0 to index 3. + * In the second step, move from index 3 to index 5. + * + * Example 2: + * + * Input: s = "01101110", minJump = 2, maxJump = 3 + * Output: false + * + * + * Constraints: + * + * 2 <= s.length <= 10^5 + * s[i] is either '0' or '1'. + * s[0] == '0' + * 1 <= minJump <= maxJump < s.length + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/jump-game-vii/ +// discuss: https://leetcode.com/problems/jump-game-vii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn can_reach(s: String, min_jump: i32, max_jump: i32) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1871() { + } +} diff --git a/src/problem/p1886_determine_whether_matrix_can_be_obtained_by_rotation.rs b/src/problem/p1886_determine_whether_matrix_can_be_obtained_by_rotation.rs new file mode 100644 index 00000000..f7476b6f --- /dev/null +++ b/src/problem/p1886_determine_whether_matrix_can_be_obtained_by_rotation.rs @@ -0,0 +1,55 @@ +/** + * [1886] Determine Whether Matrix Can Be Obtained By Rotation + * + * Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise. + * + * Example 1: + * + * Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]] + * Output: true + * Explanation: We can rotate mat 90 degrees clockwise to make mat equal target. + * + * Example 2: + * + * Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]] + * Output: false + * Explanation: It is impossible to make mat equal to target by rotating mat. + * + * Example 3: + * + * Input: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]] + * Output: true + * Explanation: We can rotate mat 90 degrees clockwise two times to make mat equal target. + * + * + * Constraints: + * + * n == mat.length == target.length + * n == mat[i].length == target[i].length + * 1 <= n <= 10 + * mat[i][j] and target[i][j] are either 0 or 1. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/ +// discuss: https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_rotation(mat: Vec>, target: Vec>) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1886() { + } +} diff --git a/src/problem/p1901_find_a_peak_element_ii.rs b/src/problem/p1901_find_a_peak_element_ii.rs new file mode 100644 index 00000000..c149f926 --- /dev/null +++ b/src/problem/p1901_find_a_peak_element_ii.rs @@ -0,0 +1,55 @@ +/** + * [1901] Find a Peak Element II + * + * A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. + * Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j]. + * You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell. + * You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time. + * + * Example 1: + * + * + * Input: mat = [[1,4],[3,2]] + * Output: [0,1] + * Explanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers. + * + * Example 2: + * + * + * Input: mat = [[10,20,15],[21,30,14],[7,16,32]] + * Output: [1,1] + * Explanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers. + * + * + * Constraints: + * + * m == mat.length + * n == mat[i].length + * 1 <= m, n <= 500 + * 1 <= mat[i][j] <= 10^5 + * No two adjacent cells are equal. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-a-peak-element-ii/ +// discuss: https://leetcode.com/problems/find-a-peak-element-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_peak_grid(mat: Vec>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1901() { + } +} diff --git a/src/problem/p1905_count_sub_islands.rs b/src/problem/p1905_count_sub_islands.rs new file mode 100644 index 00000000..f33e84a5 --- /dev/null +++ b/src/problem/p1905_count_sub_islands.rs @@ -0,0 +1,53 @@ +/** + * [1905] Count Sub Islands + * + * You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. + * An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. + * Return the number of islands in grid2 that are considered sub-islands. + * + * Example 1: + * + * Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]] + * Output: 3 + * Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2. + * The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands. + * + * Example 2: + * + * Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]] + * Output: 2 + * Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2. + * The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands. + * + * + * Constraints: + * + * m == grid1.length == grid2.length + * n == grid1[i].length == grid2[i].length + * 1 <= m, n <= 500 + * grid1[i][j] and grid2[i][j] are either 0 or 1. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-sub-islands/ +// discuss: https://leetcode.com/problems/count-sub-islands/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_sub_islands(grid1: Vec>, grid2: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1905() { + } +} diff --git a/src/problem/p1910_remove_all_occurrences_of_a_substring.rs b/src/problem/p1910_remove_all_occurrences_of_a_substring.rs new file mode 100644 index 00000000..2cdf3932 --- /dev/null +++ b/src/problem/p1910_remove_all_occurrences_of_a_substring.rs @@ -0,0 +1,62 @@ +/** + * [1910] Remove All Occurrences of a Substring + * + * Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: + * + * Find the leftmost occurrence of the substring part and remove it from s. + * + * Return s after removing all occurrences of part. + * A substring is a contiguous sequence of characters in a string. + * + * Example 1: + * + * Input: s = "daabcbaabcbc", part = "abc" + * Output: "dab" + * Explanation: The following operations are done: + * - s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". + * - s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc". + * - s = "dababc", remove "abc" starting at index 3, so s = "dab". + * Now s has no occurrences of "abc". + * + * Example 2: + * + * Input: s = "axxxxyyyyb", part = "xy" + * Output: "ab" + * Explanation: The following operations are done: + * - s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb". + * - s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb". + * - s = "axxyyb", remove "xy" starting at index 2 so s = "axyb". + * - s = "axyb", remove "xy" starting at index 1 so s = "ab". + * Now s has no occurrences of "xy". + * + * + * Constraints: + * + * 1 <= s.length <= 1000 + * 1 <= part.length <= 1000 + * s​​​​​​ and part consists of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/remove-all-occurrences-of-a-substring/ +// discuss: https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn remove_occurrences(s: String, part: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1910() { + } +} diff --git a/src/problem/p1911_maximum_alternating_subsequence_sum.rs b/src/problem/p1911_maximum_alternating_subsequence_sum.rs new file mode 100644 index 00000000..c3ecdb5e --- /dev/null +++ b/src/problem/p1911_maximum_alternating_subsequence_sum.rs @@ -0,0 +1,72 @@ +/** + * [1911] Maximum Alternating Subsequence Sum + * + * The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. + * + * + * For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4. + * + * + * Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence). + * + * + * + * + * A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not. + * + * + * Example 1: + * + * + * Input: nums = [4,2,5,3] + * Output: 7 + * Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7. + * + * + * Example 2: + * + * + * Input: nums = [5,6,7,8] + * Output: 8 + * Explanation: It is optimal to choose the subsequence [8] with alternating sum 8. + * + * + * Example 3: + * + * + * Input: nums = [6,2,1,2,4,5] + * Output: 10 + * Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10. + * + * + * + * Constraints: + * + * + * 1 <= nums.length <= 10^5 + * 1 <= nums[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-alternating-subsequence-sum/ +// discuss: https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn max_alternating_sum(nums: Vec) -> i64 { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1911() { + } +} diff --git a/src/problem/p1914_cyclically_rotating_a_grid.rs b/src/problem/p1914_cyclically_rotating_a_grid.rs new file mode 100644 index 00000000..8e3fa377 --- /dev/null +++ b/src/problem/p1914_cyclically_rotating_a_grid.rs @@ -0,0 +1,66 @@ +/** + * [1914] Cyclically Rotating a Grid + * + * You are given an m x n integer matrix grid​​​, where m and n are both even integers, and an integer k. + * + * The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: + * + * + * + * A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below: + * + * Return the matrix after applying k cyclic rotations to it. + * + * + * Example 1: + * + * + * Input: grid = [[40,10],[30,20]], k = 1 + * Output: [[10,20],[40,30]] + * Explanation: The figures above represent the grid at every state. + * + * + * Example 2: + * + * + * + * Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2 + * Output: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]] + * Explanation: The figures above represent the grid at every state. + * + * + * + * Constraints: + * + * + * m == grid.length + * n == grid[i].length + * 2 <= m, n <= 50 + * Both m and n are even integers. + * 1 <= grid[i][j] <=^ 5000 + * 1 <= k <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/cyclically-rotating-a-grid/ +// discuss: https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn rotate_grid(grid: Vec>, k: i32) -> Vec> { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1914() { + } +} diff --git a/src/problem/p1930_unique_length_3_palindromic_subsequences.rs b/src/problem/p1930_unique_length_3_palindromic_subsequences.rs new file mode 100644 index 00000000..4f8c0846 --- /dev/null +++ b/src/problem/p1930_unique_length_3_palindromic_subsequences.rs @@ -0,0 +1,66 @@ +/** + * [1930] Unique Length-3 Palindromic Subsequences + * + * Given a string s, return the number of unique palindromes of length three that are a subsequence of s. + * Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. + * A palindrome is a string that reads the same forwards and backwards. + * A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + * + * For example, "ace" is a subsequence of "abcde". + * + * + * Example 1: + * + * Input: s = "aabca" + * Output: 3 + * Explanation: The 3 palindromic subsequences of length 3 are: + * - "aba" (subsequence of "aabca") + * - "aaa" (subsequence of "aabca") + * - "aca" (subsequence of "aabca") + * + * Example 2: + * + * Input: s = "adc" + * Output: 0 + * Explanation: There are no palindromic subsequences of length 3 in "adc". + * + * Example 3: + * + * Input: s = "bbcbaba" + * Output: 4 + * Explanation: The 4 palindromic subsequences of length 3 are: + * - "bbb" (subsequence of "bbcbaba") + * - "bcb" (subsequence of "bbcbaba") + * - "bab" (subsequence of "bbcbaba") + * - "aba" (subsequence of "bbcbaba") + * + * + * Constraints: + * + * 3 <= s.length <= 10^5 + * s consists of only lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/unique-length-3-palindromic-subsequences/ +// discuss: https://leetcode.com/problems/unique-length-3-palindromic-subsequences/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_palindromic_subsequence(s: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1930() { + } +} diff --git a/src/problem/p1931_painting_a_grid_with_three_different_colors.rs b/src/problem/p1931_painting_a_grid_with_three_different_colors.rs new file mode 100644 index 00000000..3372fc31 --- /dev/null +++ b/src/problem/p1931_painting_a_grid_with_three_different_colors.rs @@ -0,0 +1,53 @@ +/** + * [1931] Painting a Grid With Three Different Colors + * + * You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted. + * Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 10^9 + 7. + * + * Example 1: + * + * Input: m = 1, n = 1 + * Output: 3 + * Explanation: The three possible colorings are shown in the image above. + * + * Example 2: + * + * Input: m = 1, n = 2 + * Output: 6 + * Explanation: The six possible colorings are shown in the image above. + * + * Example 3: + * + * Input: m = 5, n = 5 + * Output: 580986 + * + * + * Constraints: + * + * 1 <= m <= 5 + * 1 <= n <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/painting-a-grid-with-three-different-colors/ +// discuss: https://leetcode.com/problems/painting-a-grid-with-three-different-colors/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn color_the_grid(m: i32, n: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1931() { + } +} diff --git a/src/problem/p1948_delete_duplicate_folders_in_system.rs b/src/problem/p1948_delete_duplicate_folders_in_system.rs new file mode 100644 index 00000000..ceaa387f --- /dev/null +++ b/src/problem/p1948_delete_duplicate_folders_in_system.rs @@ -0,0 +1,84 @@ +/** + * [1948] Delete Duplicate Folders in System + * + * Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the i^th folder in the file system. + * + * For example, ["one", "two", "three"] represents the path "/one/two/three". + * + * Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders. + * + * For example, folders "/a" and "/b" in the file structure below are identical. They (as well as their subfolders) should all be marked: + * + * /a + * /a/x + * /a/x/y + * /a/z + * /b + * /b/x + * /b/x/y + * /b/z + * + * + * However, if the file structure also included the path "/b/w", then the folders "/a" and "/b" would not be identical. Note that "/a/x" and "/b/x" would still be considered identical even with the added folder. + * + * Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted. + * Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order. + * + * Example 1: + * + * Input: paths = [["a"],["c"],["d"],["a","b"],["c","b"],["d","a"]] + * Output: [["d"],["d","a"]] + * Explanation: The file structure is as shown. + * Folders "/a" and "/c" (and their subfolders) are marked for deletion because they both contain an empty + * folder named "b". + * + * Example 2: + * + * Input: paths = [["a"],["c"],["a","b"],["c","b"],["a","b","x"],["a","b","x","y"],["w"],["w","y"]] + * Output: [["c"],["c","b"],["a"],["a","b"]] + * Explanation: The file structure is as shown. + * Folders "/a/b/x" and "/w" (and their subfolders) are marked for deletion because they both contain an empty folder named "y". + * Note that folders "/a" and "/c" are identical after the deletion, but they are not deleted because they were not marked beforehand. + * + * Example 3: + * + * Input: paths = [["a","b"],["c","d"],["c"],["a"]] + * Output: [["c"],["c","d"],["a"],["a","b"]] + * Explanation: All folders are unique in the file system. + * Note that the returned array can be in a different order as the order does not matter. + * + * + * Constraints: + * + * 1 <= paths.length <= 2 * 10^4 + * 1 <= paths[i].length <= 500 + * 1 <= paths[i][j].length <= 10 + * 1 <= sum(paths[i][j].length) <= 2 * 10^5 + * path[i][j] consists of lowercase English letters. + * No two paths lead to the same folder. + * For any folder not at the root level, its parent folder will also be in the input. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/delete-duplicate-folders-in-system/ +// discuss: https://leetcode.com/problems/delete-duplicate-folders-in-system/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn delete_duplicate_folder(paths: Vec>) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1948() { + } +} diff --git a/src/problem/p1957_delete_characters_to_make_fancy_string.rs b/src/problem/p1957_delete_characters_to_make_fancy_string.rs new file mode 100644 index 00000000..b3f121ab --- /dev/null +++ b/src/problem/p1957_delete_characters_to_make_fancy_string.rs @@ -0,0 +1,60 @@ +/** + * [1957] Delete Characters to Make Fancy String + * + * A fancy string is a string where no three consecutive characters are equal. + * Given a string s, delete the minimum possible number of characters from s to make it fancy. + * Return the final string after the deletion. It can be shown that the answer will always be unique. + * + * Example 1: + * + * Input: s = "leeetcode" + * Output: "leetcode" + * Explanation: + * Remove an 'e' from the first group of 'e's to create "leetcode". + * No three consecutive characters are equal, so return "leetcode". + * + * Example 2: + * + * Input: s = "aaabaaaa" + * Output: "aabaa" + * Explanation: + * Remove an 'a' from the first group of 'a's to create "aabaaaa". + * Remove two 'a's from the second group of 'a's to create "aabaa". + * No three consecutive characters are equal, so return "aabaa". + * + * Example 3: + * + * Input: s = "aab" + * Output: "aab" + * Explanation: No three consecutive characters are equal, so return "aab". + * + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s consists only of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/delete-characters-to-make-fancy-string/ +// discuss: https://leetcode.com/problems/delete-characters-to-make-fancy-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn make_fancy_string(s: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1957() { + } +} diff --git a/src/problem/p1961_check_if_string_is_a_prefix_of_array.rs b/src/problem/p1961_check_if_string_is_a_prefix_of_array.rs new file mode 100644 index 00000000..9a032029 --- /dev/null +++ b/src/problem/p1961_check_if_string_is_a_prefix_of_array.rs @@ -0,0 +1,52 @@ +/** + * [1961] Check If String Is a Prefix of Array + * + * Given a string s and an array of strings words, determine whether s is a prefix string of words. + * A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length. + * Return true if s is a prefix string of words, or false otherwise. + * + * Example 1: + * + * Input: s = "iloveleetcode", words = ["i","love","leetcode","apples"] + * Output: true + * Explanation: + * s can be made by concatenating "i", "love", and "leetcode" together. + * + * Example 2: + * + * Input: s = "iloveleetcode", words = ["apples","i","love","leetcode"] + * Output: false + * Explanation: + * It is impossible to make s using a prefix of arr. + * + * Constraints: + * + * 1 <= words.length <= 100 + * 1 <= words[i].length <= 20 + * 1 <= s.length <= 1000 + * words[i] and s consist of only lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/ +// discuss: https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn is_prefix_string(s: String, words: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1961() { + } +} diff --git a/src/problem/p1968_array_with_elements_not_equal_to_average_of_neighbors.rs b/src/problem/p1968_array_with_elements_not_equal_to_average_of_neighbors.rs new file mode 100644 index 00000000..7c2ba199 --- /dev/null +++ b/src/problem/p1968_array_with_elements_not_equal_to_average_of_neighbors.rs @@ -0,0 +1,55 @@ +/** + * [1968] Array With Elements Not Equal to Average of Neighbors + * + * You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors. + * More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i]. + * Return any rearrangement of nums that meets the requirements. + * + * Example 1: + * + * Input: nums = [1,2,3,4,5] + * Output: [1,2,4,5,3] + * Explanation: + * When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5. + * When i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5. + * When i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5. + * + * Example 2: + * + * Input: nums = [6,2,0,9,7] + * Output: [9,7,6,2,0] + * Explanation: + * When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5. + * When i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5. + * When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3. + * + * + * Constraints: + * + * 3 <= nums.length <= 10^5 + * 0 <= nums[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/ +// discuss: https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn rearrange_array(nums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1968() { + } +} diff --git a/src/problem/p1982_find_array_given_subset_sums.rs b/src/problem/p1982_find_array_given_subset_sums.rs new file mode 100644 index 00000000..f7a29949 --- /dev/null +++ b/src/problem/p1982_find_array_given_subset_sums.rs @@ -0,0 +1,66 @@ +/** + * [1982] Find Array Given Subset Sums + * + * You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2^n subset sums of the unknown array (in no particular order). + * Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them. + * An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0. + * Note: Test cases are generated such that there will always be at least one correct answer. + * + * Example 1: + * + * Input: n = 3, sums = [-3,-2,-1,0,0,1,2,3] + * Output: [1,2,-3] + * Explanation: [1,2,-3] is able to achieve the given subset sums: + * - []: sum is 0 + * - [1]: sum is 1 + * - [2]: sum is 2 + * - [1,2]: sum is 3 + * - [-3]: sum is -3 + * - [1,-3]: sum is -2 + * - [2,-3]: sum is -1 + * - [1,2,-3]: sum is 0 + * Note that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted. + * + * Example 2: + * + * Input: n = 2, sums = [0,0,0,0] + * Output: [0,0] + * Explanation: The only correct answer is [0,0]. + * + * Example 3: + * + * Input: n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8] + * Output: [0,-1,4,5] + * Explanation: [0,-1,4,5] is able to achieve the given subset sums. + * + * + * Constraints: + * + * 1 <= n <= 15 + * sums.length == 2^n + * -10^4 <= sums[i] <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-array-given-subset-sums/ +// discuss: https://leetcode.com/problems/find-array-given-subset-sums/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn recover_array(n: i32, sums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1982() { + } +} diff --git a/src/problem/p1987_number_of_unique_good_subsequences.rs b/src/problem/p1987_number_of_unique_good_subsequences.rs new file mode 100644 index 00000000..5f61d40b --- /dev/null +++ b/src/problem/p1987_number_of_unique_good_subsequences.rs @@ -0,0 +1,61 @@ +/** + * [1987] Number of Unique Good Subsequences + * + * You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of "0"). + * Find the number of unique good subsequences of binary. + * + * For example, if binary = "001", then all the good subsequences are ["0", "0", "1"], so the unique good subsequences are "0" and "1". Note that subsequences "00", "01", and "001" are not good because they have leading zeros. + * + * Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 10^9 + 7. + * A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. + * + * Example 1: + * + * Input: binary = "001" + * Output: 2 + * Explanation: The good subsequences of binary are ["0", "0", "1"]. + * The unique good subsequences are "0" and "1". + * + * Example 2: + * + * Input: binary = "11" + * Output: 2 + * Explanation: The good subsequences of binary are ["1", "1", "11"]. + * The unique good subsequences are "1" and "11". + * Example 3: + * + * Input: binary = "101" + * Output: 5 + * Explanation: The good subsequences of binary are ["1", "0", "1", "10", "11", "101"]. + * The unique good subsequences are "0", "1", "10", "11", and "101". + * + * + * Constraints: + * + * 1 <= binary.length <= 10^5 + * binary consists of only '0's and '1's. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-unique-good-subsequences/ +// discuss: https://leetcode.com/problems/number-of-unique-good-subsequences/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn number_of_unique_good_subsequences(binary: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1987() { + } +} diff --git a/src/problem/p1991_find_the_middle_index_in_array.rs b/src/problem/p1991_find_the_middle_index_in_array.rs new file mode 100644 index 00000000..76fb567f --- /dev/null +++ b/src/problem/p1991_find_the_middle_index_in_array.rs @@ -0,0 +1,61 @@ +/** + * [1991] Find the Middle Index in Array + * + * Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). + * A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. + * If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0. + * Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index. + * + * Example 1: + * + * Input: nums = [2,3,-1,8,4] + * Output: 3 + * Explanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4 + * The sum of the numbers after index 3 is: 4 = 4 + * + * Example 2: + * + * Input: nums = [1,-1,4] + * Output: 2 + * Explanation: The sum of the numbers before index 2 is: 1 + -1 = 0 + * The sum of the numbers after index 2 is: 0 + * + * Example 3: + * + * Input: nums = [2,5] + * Output: -1 + * Explanation: There is no valid middleIndex. + * + * + * Constraints: + * + * 1 <= nums.length <= 100 + * -1000 <= nums[i] <= 1000 + * + * + * Note: This question is the same as 724: https://leetcode.com/problems/find-pivot-index/ + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-the-middle-index-in-array/ +// discuss: https://leetcode.com/problems/find-the-middle-index-in-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_middle_index(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1991() { + } +} diff --git a/src/problem/p1992_find_all_groups_of_farmland.rs b/src/problem/p1992_find_all_groups_of_farmland.rs new file mode 100644 index 00000000..445da364 --- /dev/null +++ b/src/problem/p1992_find_all_groups_of_farmland.rs @@ -0,0 +1,63 @@ +/** + * [1992] Find All Groups of Farmland + * + * You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. + * To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. + * land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2]. + * Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order. + * + * Example 1: + * + * Input: land = [[1,0,0],[0,1,1],[0,1,1]] + * Output: [[0,0,0,0],[1,1,2,2]] + * Explanation: + * The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0]. + * The second group has a top left corner at land[1][1] and a bottom right corner at land[2][2]. + * + * Example 2: + * + * Input: land = [[1,1],[1,1]] + * Output: [[0,0,1,1]] + * Explanation: + * The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1]. + * + * Example 3: + * + * Input: land = [[0]] + * Output: [] + * Explanation: + * There are no groups of farmland. + * + * + * Constraints: + * + * m == land.length + * n == land[i].length + * 1 <= m, n <= 300 + * land consists of only 0's and 1's. + * Groups of farmland are rectangular in shape. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-all-groups-of-farmland/ +// discuss: https://leetcode.com/problems/find-all-groups-of-farmland/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_farmland(land: Vec>) -> Vec> { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1992() { + } +} diff --git a/src/problem/p2000_reverse_prefix_of_word.rs b/src/problem/p2000_reverse_prefix_of_word.rs new file mode 100644 index 00000000..9b049be7 --- /dev/null +++ b/src/problem/p2000_reverse_prefix_of_word.rs @@ -0,0 +1,61 @@ +/** + * [2000] Reverse Prefix of Word + * + * Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. + * + * For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd". + * + * Return the resulting string. + * + * Example 1: + * + * Input: word = "abcdefd", ch = "d" + * Output: "dcbaefd" + * Explanation: The first occurrence of "d" is at index 3. + * Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd". + * + * Example 2: + * + * Input: word = "xyxzxe", ch = "z" + * Output: "zxyxxe" + * Explanation: The first and only occurrence of "z" is at index 3. + * Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe". + * + * Example 3: + * + * Input: word = "abcd", ch = "z" + * Output: "abcd" + * Explanation: "z" does not exist in word. + * You should not do any reverse operation, the resulting string is "abcd". + * + * + * Constraints: + * + * 1 <= word.length <= 250 + * word consists of lowercase English letters. + * ch is a lowercase English letter. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/reverse-prefix-of-word/ +// discuss: https://leetcode.com/problems/reverse-prefix-of-word/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn reverse_prefix(word: String, ch: char) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2000() { + } +} diff --git a/src/problem/p2011_final_value_of_variable_after_performing_operations.rs b/src/problem/p2011_final_value_of_variable_after_performing_operations.rs new file mode 100644 index 00000000..494919c9 --- /dev/null +++ b/src/problem/p2011_final_value_of_variable_after_performing_operations.rs @@ -0,0 +1,72 @@ +/** + * [2011] Final Value of Variable After Performing Operations + * + * There is a programming language with only four operations and one variable X: + * + * ++X and X++ increments the value of the variable X by 1. + * --X and X-- decrements the value of the variable X by 1. + * + * Initially, the value of X is 0. + * Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations. + * + * Example 1: + * + * Input: operations = ["--X","X++","X++"] + * Output: 1 + * Explanation: The operations are performed as follows: + * Initially, X = 0. + * --X: X is decremented by 1, X = 0 - 1 = -1. + * X++: X is incremented by 1, X = -1 + 1 = 0. + * X++: X is incremented by 1, X = 0 + 1 = 1. + * + * Example 2: + * + * Input: operations = ["++X","++X","X++"] + * Output: 3 + * Explanation: The operations are performed as follows: + * Initially, X = 0. + * ++X: X is incremented by 1, X = 0 + 1 = 1. + * ++X: X is incremented by 1, X = 1 + 1 = 2. + * X++: X is incremented by 1, X = 2 + 1 = 3. + * + * Example 3: + * + * Input: operations = ["X++","++X","--X","X--"] + * Output: 0 + * Explanation: The operations are performed as follows: + * Initially, X = 0. + * X++: X is incremented by 1, X = 0 + 1 = 1. + * ++X: X is incremented by 1, X = 1 + 1 = 2. + * --X: X is decremented by 1, X = 2 - 1 = 1. + * X--: X is decremented by 1, X = 1 - 1 = 0. + * + * + * Constraints: + * + * 1 <= operations.length <= 100 + * operations[i] will be either "++X", "X++", "--X", or "X--". + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/final-value-of-variable-after-performing-operations/ +// discuss: https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn final_value_after_operations(operations: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2011() { + } +} diff --git a/src/problem/p2013_detect_squares.rs b/src/problem/p2013_detect_squares.rs new file mode 100644 index 00000000..72eb8038 --- /dev/null +++ b/src/problem/p2013_detect_squares.rs @@ -0,0 +1,92 @@ +/** + * [2013] Detect Squares + * + * You are given a stream of points on the X-Y plane. Design an algorithm that: + * + * Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points. + * Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area. + * + * An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis. + * Implement the DetectSquares class: + * + * DetectSquares() Initializes the object with an empty data structure. + * void add(int[] point) Adds a new point point = [x, y] to the data structure. + * int count(int[] point) Counts the number of ways to form axis-aligned squares with point point = [x, y] as described above. + * + * + * Example 1: + * + * Input + * ["DetectSquares", "add", "add", "add", "count", "count", "add", "count"] + * [[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]] + * Output + * [null, null, null, null, 1, 0, null, 2] + * Explanation + * DetectSquares detectSquares = new DetectSquares(); + * detectSquares.add([3, 10]); + * detectSquares.add([11, 2]); + * detectSquares.add([3, 2]); + * detectSquares.count([11, 10]); // return 1. You can choose: + * // - The first, second, and third points + * detectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure. + * detectSquares.add([11, 2]); // Adding duplicate points is allowed. + * detectSquares.count([11, 10]); // return 2. You can choose: + * // - The first, second, and third points + * // - The first, third, and fourth points + * + * + * Constraints: + * + * point.length == 2 + * 0 <= x, y <= 1000 + * At most 3000 calls in total will be made to add and count. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/detect-squares/ +// discuss: https://leetcode.com/problems/detect-squares/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct DetectSquares { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl DetectSquares { + + fn new() -> Self { + + } + + fn add(&self, point: Vec) { + + } + + fn count(&self, point: Vec) -> i32 { + + } +} + +/** + * Your DetectSquares object will be instantiated and called as such: + * let obj = DetectSquares::new(); + * obj.add(point); + * let ret_2: i32 = obj.count(point); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2013() { + } +} diff --git a/src/problem/p2035_partition_array_into_two_arrays_to_minimize_sum_difference.rs b/src/problem/p2035_partition_array_into_two_arrays_to_minimize_sum_difference.rs new file mode 100644 index 00000000..7a647871 --- /dev/null +++ b/src/problem/p2035_partition_array_into_two_arrays_to_minimize_sum_difference.rs @@ -0,0 +1,58 @@ +/** + * [2035] Partition Array Into Two Arrays to Minimize Sum Difference + * + * You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays. + * Return the minimum possible absolute difference. + * + * Example 1: + * example-1 + * Input: nums = [3,9,7,3] + * Output: 2 + * Explanation: One optimal partition is: [3,9] and [7,3]. + * The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2. + * + * Example 2: + * + * Input: nums = [-36,36] + * Output: 72 + * Explanation: One optimal partition is: [-36] and [36]. + * The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72. + * + * Example 3: + * example-3 + * Input: nums = [2,-1,0,4,-2,-9] + * Output: 0 + * Explanation: One optimal partition is: [2,4,-9] and [-1,0,-2]. + * The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0. + * + * + * Constraints: + * + * 1 <= n <= 15 + * nums.length == 2 * n + * -10^7 <= nums[i] <= 10^7 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/ +// discuss: https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn minimum_difference(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2035() { + } +} diff --git a/src/problem/p2042_check_if_numbers_are_ascending_in_a_sentence.rs b/src/problem/p2042_check_if_numbers_are_ascending_in_a_sentence.rs new file mode 100644 index 00000000..6497c431 --- /dev/null +++ b/src/problem/p2042_check_if_numbers_are_ascending_in_a_sentence.rs @@ -0,0 +1,64 @@ +/** + * [2042] Check if Numbers Are Ascending in a Sentence + * + * A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters. + * + * For example, "a puppy has 2 eyes 4 legs" is a sentence with seven tokens: "2" and "4" are numbers and the other tokens such as "puppy" are words. + * + * Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s). + * Return true if so, or false otherwise. + * + * Example 1: + * example-1 + * Input: s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles" + * Output: true + * Explanation: The numbers in s are: 1, 3, 4, 6, 12. + * They are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12. + * + * Example 2: + * + * Input: s = "hello world 5 x 5" + * Output: false + * Explanation: The numbers in s are: 5, 5. They are not strictly increasing. + * + * Example 3: + * example-3 + * Input: s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s" + * Output: false + * Explanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing. + * + * + * Constraints: + * + * 3 <= s.length <= 200 + * s consists of lowercase English letters, spaces, and digits from 0 to 9, inclusive. + * The number of tokens in s is between 2 and 100, inclusive. + * The tokens in s are separated by a single space. + * There are at least two numbers in s. + * Each number in s is a positive number less than 100, with no leading zeros. + * s contains no leading or trailing spaces. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/ +// discuss: https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn are_numbers_ascending(s: String) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2042() { + } +} diff --git a/src/problem/p2057_smallest_index_with_equal_value.rs b/src/problem/p2057_smallest_index_with_equal_value.rs new file mode 100644 index 00000000..b9193c81 --- /dev/null +++ b/src/problem/p2057_smallest_index_with_equal_value.rs @@ -0,0 +1,63 @@ +/** + * [2057] Smallest Index With Equal Value + * + * Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist. + * x mod y denotes the remainder when x is divided by y. + * + * Example 1: + * + * Input: nums = [0,1,2] + * Output: 0 + * Explanation: + * i=0: 0 mod 10 = 0 == nums[0]. + * i=1: 1 mod 10 = 1 == nums[1]. + * i=2: 2 mod 10 = 2 == nums[2]. + * All indices have i mod 10 == nums[i], so we return the smallest index 0. + * + * Example 2: + * + * Input: nums = [4,3,2,1] + * Output: 2 + * Explanation: + * i=0: 0 mod 10 = 0 != nums[0]. + * i=1: 1 mod 10 = 1 != nums[1]. + * i=2: 2 mod 10 = 2 == nums[2]. + * i=3: 3 mod 10 = 3 != nums[3]. + * 2 is the only index which has i mod 10 == nums[i]. + * + * Example 3: + * + * Input: nums = [1,2,3,4,5,6,7,8,9,0] + * Output: -1 + * Explanation: No index satisfies i mod 10 == nums[i]. + * + * + * Constraints: + * + * 1 <= nums.length <= 100 + * 0 <= nums[i] <= 9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/smallest-index-with-equal-value/ +// discuss: https://leetcode.com/problems/smallest-index-with-equal-value/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn smallest_equal(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2057() { + } +} diff --git a/src/problem/p2059_minimum_operations_to_convert_number.rs b/src/problem/p2059_minimum_operations_to_convert_number.rs new file mode 100644 index 00000000..ccbd97b8 --- /dev/null +++ b/src/problem/p2059_minimum_operations_to_convert_number.rs @@ -0,0 +1,69 @@ +/** + * [2059] Minimum Operations to Convert Number + * + * You are given a 0-indexed integer array nums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal. You can perform the following operation repeatedly on the number x: + * If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following: + * + * x + nums[i] + * x - nums[i] + * x ^ nums[i] (bitwise-XOR) + * + * Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward. + * Return the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible. + * + * Example 1: + * + * Input: nums = [2,4,12], start = 2, goal = 12 + * Output: 2 + * Explanation: We can go from 2 → 14 → 12 with the following 2 operations. + * - 2 + 12 = 14 + * - 14 - 2 = 12 + * + * Example 2: + * + * Input: nums = [3,5,7], start = 0, goal = -4 + * Output: 2 + * Explanation: We can go from 0 → 3 → -4 with the following 2 operations. + * - 0 + 3 = 3 + * - 3 - 7 = -4 + * Note that the last operation sets x out of the range 0 <= x <= 1000, which is valid. + * + * Example 3: + * + * Input: nums = [2,8,16], start = 0, goal = 1 + * Output: -1 + * Explanation: There is no way to convert 0 into 1. + * + * + * Constraints: + * + * 1 <= nums.length <= 1000 + * -10^9 <= nums[i], goal <= 10^9 + * 0 <= start <= 1000 + * start != goal + * All the integers in nums are distinct. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-operations-to-convert-number/ +// discuss: https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn minimum_operations(nums: Vec, start: i32, goal: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2059() { + } +} diff --git a/src/problem/p2079_watering_plants.rs b/src/problem/p2079_watering_plants.rs new file mode 100644 index 00000000..4aec4f65 --- /dev/null +++ b/src/problem/p2079_watering_plants.rs @@ -0,0 +1,76 @@ +/** + * [2079] Watering Plants + * + * You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the i^th plant is located at x = i. There is a river at x = -1 that you can refill your watering can at. + * Each plant needs a specific amount of water. You will water the plants in the following way: + * + * Water the plants in order from left to right. + * After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can. + * You cannot refill the watering can early. + * + * You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis. + * Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the i^th plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants. + * + * Example 1: + * + * Input: plants = [2,2,3,3], capacity = 5 + * Output: 14 + * Explanation: Start at the river with a full watering can: + * - Walk to plant 0 (1 step) and water it. Watering can has 3 units of water. + * - Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water. + * - Since you cannot completely water plant 2, walk back to the river to refill (2 steps). + * - Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water. + * - Since you cannot completely water plant 3, walk back to the river to refill (3 steps). + * - Walk to plant 3 (4 steps) and water it. + * Steps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14. + * + * Example 2: + * + * Input: plants = [1,1,1,4,2,3], capacity = 4 + * Output: 30 + * Explanation: Start at the river with a full watering can: + * - Water plants 0, 1, and 2 (3 steps). Return to river (3 steps). + * - Water plant 3 (4 steps). Return to river (4 steps). + * - Water plant 4 (5 steps). Return to river (5 steps). + * - Water plant 5 (6 steps). + * Steps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30. + * + * Example 3: + * + * Input: plants = [7,7,7,7,7,7,7], capacity = 8 + * Output: 49 + * Explanation: You have to refill before watering each plant. + * Steps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49. + * + * + * Constraints: + * + * n == plants.length + * 1 <= n <= 1000 + * 1 <= plants[i] <= 10^6 + * max(plants[i]) <= capacity <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/watering-plants/ +// discuss: https://leetcode.com/problems/watering-plants/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn watering_plants(plants: Vec, capacity: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2079() { + } +} diff --git a/src/problem/p2087_minimum_cost_homecoming_of_a_robot_in_a_grid.rs b/src/problem/p2087_minimum_cost_homecoming_of_a_robot_in_a_grid.rs new file mode 100644 index 00000000..cebc5de1 --- /dev/null +++ b/src/problem/p2087_minimum_cost_homecoming_of_a_robot_in_a_grid.rs @@ -0,0 +1,64 @@ +/** + * [2087] Minimum Cost Homecoming of a Robot in a Grid + * + * There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol). + * The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n. + * + * If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r]. + * If the robot moves left or right into a cell whose column is c, then this move costs colCosts[c]. + * + * Return the minimum total cost for this robot to return home. + * + * Example 1: + * + * Input: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7] + * Output: 18 + * Explanation: One optimal path is that: + * Starting from (1, 0) + * -> It goes down to (2, 0). This move costs rowCosts[2] = 3. + * -> It goes right to (2, 1). This move costs colCosts[1] = 2. + * -> It goes right to (2, 2). This move costs colCosts[2] = 6. + * -> It goes right to (2, 3). This move costs colCosts[3] = 7. + * The total cost is 3 + 2 + 6 + 7 = 18 + * Example 2: + * + * Input: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26] + * Output: 0 + * Explanation: The robot is already at its home. Since no moves occur, the total cost is 0. + * + * + * Constraints: + * + * m == rowCosts.length + * n == colCosts.length + * 1 <= m, n <= 10^5 + * 0 <= rowCosts[r], colCosts[c] <= 10^4 + * startPos.length == 2 + * homePos.length == 2 + * 0 <= startrow, homerow < m + * 0 <= startcol, homecol < n + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/ +// discuss: https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_cost(start_pos: Vec, home_pos: Vec, row_costs: Vec, col_costs: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2087() { + } +} diff --git a/src/problem/p2094_finding_3_digit_even_numbers.rs b/src/problem/p2094_finding_3_digit_even_numbers.rs new file mode 100644 index 00000000..f4e68dee --- /dev/null +++ b/src/problem/p2094_finding_3_digit_even_numbers.rs @@ -0,0 +1,63 @@ +/** + * [2094] Finding 3-Digit Even Numbers + * + * You are given an integer array digits, where each element is a digit. The array may contain duplicates. + * You need to find all the unique integers that follow the given requirements: + * + * The integer consists of the concatenation of three elements from digits in any arbitrary order. + * The integer does not have leading zeros. + * The integer is even. + * + * For example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements. + * Return a sorted array of the unique integers. + * + * Example 1: + * + * Input: digits = [2,1,3,0] + * Output: [102,120,130,132,210,230,302,310,312,320] + * Explanation: All the possible integers that follow the requirements are in the output array. + * Notice that there are no odd integers or integers with leading zeros. + * + * Example 2: + * + * Input: digits = [2,2,8,8,2] + * Output: [222,228,282,288,822,828,882] + * Explanation: The same digit can be used as many times as it appears in digits. + * In this example, the digit 8 is used twice each time in 288, 828, and 882. + * + * Example 3: + * + * Input: digits = [3,7,5] + * Output: [] + * Explanation: No even integers can be formed using the given digits. + * + * + * Constraints: + * + * 3 <= digits.length <= 100 + * 0 <= digits[i] <= 9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/finding-3-digit-even-numbers/ +// discuss: https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_even_numbers(digits: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2094() { + } +} diff --git a/src/problem/p2095_delete_the_middle_node_of_a_linked_list.rs b/src/problem/p2095_delete_the_middle_node_of_a_linked_list.rs new file mode 100644 index 00000000..1c7e6ec8 --- /dev/null +++ b/src/problem/p2095_delete_the_middle_node_of_a_linked_list.rs @@ -0,0 +1,81 @@ +/** + * [2095] Delete the Middle Node of a Linked List + * + * You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list. + * The middle node of a linked list of size n is the ⌊n / 2⌋^th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x. + * + * For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively. + * + * + * Example 1: + * + * Input: head = [1,3,4,7,1,2,6] + * Output: [1,3,4,1,2,6] + * Explanation: + * The above figure represents the given linked list. The indices of the nodes are written below. + * Since n = 7, node 3 with value 7 is the middle node, which is marked in red. + * We return the new list after removing this node. + * + * Example 2: + * + * Input: head = [1,2,3,4] + * Output: [1,2,4] + * Explanation: + * The above figure represents the given linked list. + * For n = 4, node 2 with value 3 is the middle node, which is marked in red. + * + * Example 3: + * + * Input: head = [2,1] + * Output: [2] + * Explanation: + * The above figure represents the given linked list. + * For n = 2, node 1 with value 1 is the middle node, which is marked in red. + * Node 0 with value 2 is the only node remaining after removing node 1. + * + * Constraints: + * + * The number of nodes in the list is in the range [1, 10^5]. + * 1 <= Node.val <= 10^5 + * + */ +pub struct Solution {} +use crate::util::linked_list::{ListNode, to_list}; + +// problem: https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/ +// discuss: https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn delete_middle(head: Option>) -> Option> { + Some(Box::new(ListNode::new(0))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2095() { + } +} diff --git a/src/problem/p2111_minimum_operations_to_make_the_array_k_increasing.rs b/src/problem/p2111_minimum_operations_to_make_the_array_k_increasing.rs new file mode 100644 index 00000000..1ebfde41 --- /dev/null +++ b/src/problem/p2111_minimum_operations_to_make_the_array_k_increasing.rs @@ -0,0 +1,77 @@ +/** + * [2111] Minimum Operations to Make the Array K-Increasing + * + * You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. + * The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1. + * + * For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: + * + * arr[0] <= arr[2] (4 <= 5) + * arr[1] <= arr[3] (1 <= 2) + * arr[2] <= arr[4] (5 <= 6) + * arr[3] <= arr[5] (2 <= 2) + * + * + * However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1]) or k = 3 (because arr[0] > arr[3]). + * + * In one operation, you can choose an index i and change arr[i] into any positive integer. + * Return the minimum number of operations required to make the array K-increasing for the given k. + * + * Example 1: + * + * Input: arr = [5,4,3,2,1], k = 1 + * Output: 4 + * Explanation: + * For k = 1, the resultant array has to be non-decreasing. + * Some of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations. + * It is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations. + * It can be shown that we cannot make the array K-increasing in less than 4 operations. + * + * Example 2: + * + * Input: arr = [4,1,5,2,6,2], k = 2 + * Output: 0 + * Explanation: + * This is the same example as the one in the problem description. + * Here, for every index i where 2 <= i <= 5, arr[i-2] <= arr[i]. + * Since the given array is already K-increasing, we do not need to perform any operations. + * Example 3: + * + * Input: arr = [4,1,5,2,6,2], k = 3 + * Output: 2 + * Explanation: + * Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5. + * One of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5. + * The array will now be [4,1,5,4,6,5]. + * Note that there can be other ways to make the array K-increasing, but none of them require less than 2 operations. + * + * + * Constraints: + * + * 1 <= arr.length <= 10^5 + * 1 <= arr[i], k <= arr.length + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-operations-to-make-the-array-k-increasing/ +// discuss: https://leetcode.com/problems/minimum-operations-to-make-the-array-k-increasing/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn k_increasing(arr: Vec, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2111() { + } +} diff --git a/src/problem/p2131_longest_palindrome_by_concatenating_two_letter_words.rs b/src/problem/p2131_longest_palindrome_by_concatenating_two_letter_words.rs new file mode 100644 index 00000000..a2b6db8f --- /dev/null +++ b/src/problem/p2131_longest_palindrome_by_concatenating_two_letter_words.rs @@ -0,0 +1,60 @@ +/** + * [2131] Longest Palindrome by Concatenating Two Letter Words + * + * You are given an array of strings words. Each element of words consists of two lowercase English letters. + * Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once. + * Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0. + * A palindrome is a string that reads the same forward and backward. + * + * Example 1: + * + * Input: words = ["lc","cl","gg"] + * Output: 6 + * Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6. + * Note that "clgglc" is another longest palindrome that can be created. + * + * Example 2: + * + * Input: words = ["ab","ty","yt","lc","cl","ab"] + * Output: 8 + * Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8. + * Note that "lcyttycl" is another longest palindrome that can be created. + * + * Example 3: + * + * Input: words = ["cc","ll","xx"] + * Output: 2 + * Explanation: One longest palindrome is "cc", of length 2. + * Note that "ll" is another longest palindrome that can be created, and so is "xx". + * + * + * Constraints: + * + * 1 <= words.length <= 10^5 + * words[i].length == 2 + * words[i] consists of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/ +// discuss: https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn longest_palindrome(words: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2131() { + } +} diff --git a/src/problem/p2134_minimum_swaps_to_group_all_1s_together_ii.rs b/src/problem/p2134_minimum_swaps_to_group_all_1s_together_ii.rs new file mode 100644 index 00000000..b3b1370c --- /dev/null +++ b/src/problem/p2134_minimum_swaps_to_group_all_1s_together_ii.rs @@ -0,0 +1,65 @@ +/** + * [2134] Minimum Swaps to Group All 1's Together II + * + * A swap is defined as taking two distinct positions in an array and swapping the values in them. + * A circular array is defined as an array where we consider the first element and the last element to be adjacent. + * Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location. + * + * Example 1: + * + * Input: nums = [0,1,0,1,1,0,0] + * Output: 1 + * Explanation: Here are a few of the ways to group all the 1's together: + * [0,0,1,1,1,0,0] using 1 swap. + * [0,1,1,1,0,0,0] using 1 swap. + * [1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array). + * There is no way to group all 1's together with 0 swaps. + * Thus, the minimum number of swaps required is 1. + * + * Example 2: + * + * Input: nums = [0,1,1,1,0,0,1,1,0] + * Output: 2 + * Explanation: Here are a few of the ways to group all the 1's together: + * [1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array). + * [1,1,1,1,1,0,0,0,0] using 2 swaps. + * There is no way to group all 1's together with 0 or 1 swaps. + * Thus, the minimum number of swaps required is 2. + * + * Example 3: + * + * Input: nums = [1,1,0,0,1] + * Output: 0 + * Explanation: All the 1's are already grouped together due to the circular property of the array. + * Thus, the minimum number of swaps required is 0. + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * nums[i] is either 0 or 1. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/ +// discuss: https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn min_swaps(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2134() { + } +} diff --git a/src/problem/p2136_earliest_possible_day_of_full_bloom.rs b/src/problem/p2136_earliest_possible_day_of_full_bloom.rs new file mode 100644 index 00000000..c34b4dff --- /dev/null +++ b/src/problem/p2136_earliest_possible_day_of_full_bloom.rs @@ -0,0 +1,72 @@ +/** + * [2136] Earliest Possible Day of Full Bloom + * + * You have n flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime and growTime, of length n each: + * + * plantTime[i] is the number of full days it takes you to plant the i^th seed. Every day, you can work on planting exactly one seed. You do not have to work on planting the same seed on consecutive days, but the planting of a seed is not complete until you have worked plantTime[i] days on planting it in total. + * growTime[i] is the number of full days it takes the i^th seed to grow after being completely planted. After the last day of its growth, the flower blooms and stays bloomed forever. + * + * From the beginning of day 0, you can plant the seeds in any order. + * Return the earliest possible day where all seeds are blooming. + * + * Example 1: + * + * Input: plantTime = [1,4,3], growTime = [2,3,1] + * Output: 9 + * Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms. + * One optimal way is: + * On day 0, plant the 0^th seed. The seed grows for 2 full days and blooms on day 3. + * On days 1, 2, 3, and 4, plant the 1^st seed. The seed grows for 3 full days and blooms on day 8. + * On days 5, 6, and 7, plant the 2^nd seed. The seed grows for 1 full day and blooms on day 9. + * Thus, on day 9, all the seeds are blooming. + * + * Example 2: + * + * Input: plantTime = [1,2,3,2], growTime = [2,1,2,1] + * Output: 9 + * Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms. + * One optimal way is: + * On day 1, plant the 0^th seed. The seed grows for 2 full days and blooms on day 4. + * On days 0 and 3, plant the 1^st seed. The seed grows for 1 full day and blooms on day 5. + * On days 2, 4, and 5, plant the 2^nd seed. The seed grows for 2 full days and blooms on day 8. + * On days 6 and 7, plant the 3^rd seed. The seed grows for 1 full day and blooms on day 9. + * Thus, on day 9, all the seeds are blooming. + * + * Example 3: + * + * Input: plantTime = [1], growTime = [1] + * Output: 2 + * Explanation: On day 0, plant the 0^th seed. The seed grows for 1 full day and blooms on day 2. + * Thus, on day 2, all the seeds are blooming. + * + * + * Constraints: + * + * n == plantTime.length == growTime.length + * 1 <= n <= 10^5 + * 1 <= plantTime[i], growTime[i] <= 10^4 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/earliest-possible-day-of-full-bloom/ +// discuss: https://leetcode.com/problems/earliest-possible-day-of-full-bloom/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn earliest_full_bloom(plant_time: Vec, grow_time: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2136() { + } +} diff --git a/src/problem/p2177_find_three_consecutive_integers_that_sum_to_a_given_number.rs b/src/problem/p2177_find_three_consecutive_integers_that_sum_to_a_given_number.rs new file mode 100644 index 00000000..7eda0fe0 --- /dev/null +++ b/src/problem/p2177_find_three_consecutive_integers_that_sum_to_a_given_number.rs @@ -0,0 +1,47 @@ +/** + * [2177] Find Three Consecutive Integers That Sum to a Given Number + * + * Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array. + * + * Example 1: + * + * Input: num = 33 + * Output: [10,11,12] + * Explanation: 33 can be expressed as 10 + 11 + 12 = 33. + * 10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12]. + * + * Example 2: + * + * Input: num = 4 + * Output: [] + * Explanation: There is no way to express 4 as the sum of 3 consecutive integers. + * + * + * Constraints: + * + * 0 <= num <= 10^15 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/ +// discuss: https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn sum_of_three(num: i64) -> Vec { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2177() { + } +} diff --git a/src/problem/p2179_count_good_triplets_in_an_array.rs b/src/problem/p2179_count_good_triplets_in_an_array.rs new file mode 100644 index 00000000..8f2a0774 --- /dev/null +++ b/src/problem/p2179_count_good_triplets_in_an_array.rs @@ -0,0 +1,53 @@ +/** + * [2179] Count Good Triplets in an Array + * + * You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. + * A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. + * Return the total number of good triplets. + * + * Example 1: + * + * Input: nums1 = [2,0,1,3], nums2 = [0,1,2,3] + * Output: 1 + * Explanation: + * There are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). + * Out of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. Hence, there is only 1 good triplet. + * + * Example 2: + * + * Input: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3] + * Output: 4 + * Explanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2). + * + * + * Constraints: + * + * n == nums1.length == nums2.length + * 3 <= n <= 10^5 + * 0 <= nums1[i], nums2[i] <= n - 1 + * nums1 and nums2 are permutations of [0, 1, ..., n - 1]. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-good-triplets-in-an-array/ +// discuss: https://leetcode.com/problems/count-good-triplets-in-an-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn good_triplets(nums1: Vec, nums2: Vec) -> i64 { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2179() { + } +} diff --git a/src/problem/p2181_merge_nodes_in_between_zeros.rs b/src/problem/p2181_merge_nodes_in_between_zeros.rs new file mode 100644 index 00000000..e969f5b5 --- /dev/null +++ b/src/problem/p2181_merge_nodes_in_between_zeros.rs @@ -0,0 +1,75 @@ +/** + * [2181] Merge Nodes in Between Zeros + * + * You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. + * For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. + * Return the head of the modified linked list. + * + * Example 1: + * + * Input: head = [0,3,1,0,4,5,2,0] + * Output: [4,11] + * Explanation: + * The above figure represents the given linked list. The modified list contains + * - The sum of the nodes marked in green: 3 + 1 = 4. + * - The sum of the nodes marked in red: 4 + 5 + 2 = 11. + * + * Example 2: + * + * Input: head = [0,1,0,3,0,2,2,0] + * Output: [1,3,4] + * Explanation: + * The above figure represents the given linked list. The modified list contains + * - The sum of the nodes marked in green: 1 = 1. + * - The sum of the nodes marked in red: 3 = 3. + * - The sum of the nodes marked in yellow: 2 + 2 = 4. + * + * + * Constraints: + * + * The number of nodes in the list is in the range [3, 2 * 10^5]. + * 0 <= Node.val <= 1000 + * There are no two consecutive nodes with Node.val == 0. + * The beginning and end of the linked list have Node.val == 0. + * + */ +pub struct Solution {} +use crate::util::linked_list::{ListNode, to_list}; + +// problem: https://leetcode.com/problems/merge-nodes-in-between-zeros/ +// discuss: https://leetcode.com/problems/merge-nodes-in-between-zeros/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn merge_nodes(head: Option>) -> Option> { + Some(Box::new(ListNode::new(0))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2181() { + } +} diff --git a/src/problem/p2191_sort_the_jumbled_numbers.rs b/src/problem/p2191_sort_the_jumbled_numbers.rs new file mode 100644 index 00000000..52c51b40 --- /dev/null +++ b/src/problem/p2191_sort_the_jumbled_numbers.rs @@ -0,0 +1,65 @@ +/** + * [2191] Sort the Jumbled Numbers + * + * You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled decimal system. mapping[i] = j means digit i should be mapped to digit j in this system. + * The mapped value of an integer is the new integer obtained by replacing each occurrence of digit i in the integer with mapping[i] for all 0 <= i <= 9. + * You are also given another integer array nums. Return the array nums sorted in non-decreasing order based on the mapped values of its elements. + * Notes: + * + * Elements with the same mapped values should appear in the same relative order as in the input. + * The elements of nums should only be sorted based on their mapped values and not be replaced by them. + * + * + * Example 1: + * + * Input: mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38] + * Output: [338,38,991] + * Explanation: + * Map the number 991 as follows: + * 1. mapping[9] = 6, so all occurrences of the digit 9 will become 6. + * 2. mapping[1] = 9, so all occurrences of the digit 1 will become 9. + * Therefore, the mapped value of 991 is 669. + * 338 maps to 007, or 7 after removing the leading zeros. + * 38 maps to 07, which is also 7 after removing leading zeros. + * Since 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38. + * Thus, the sorted array is [338,38,991]. + * + * Example 2: + * + * Input: mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123] + * Output: [123,456,789] + * Explanation: 789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789]. + * + * + * Constraints: + * + * mapping.length == 10 + * 0 <= mapping[i] <= 9 + * All the values of mapping[i] are unique. + * 1 <= nums.length <= 3 * 10^4 + * 0 <= nums[i] < 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/sort-the-jumbled-numbers/ +// discuss: https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn sort_jumbled(mapping: Vec, nums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2191() { + } +} diff --git a/src/problem/p2194_cells_in_a_range_on_an_excel_sheet.rs b/src/problem/p2194_cells_in_a_range_on_an_excel_sheet.rs new file mode 100644 index 00000000..3978e9ab --- /dev/null +++ b/src/problem/p2194_cells_in_a_range_on_an_excel_sheet.rs @@ -0,0 +1,63 @@ +/** + * [2194] Cells in a Range on an Excel Sheet + * + * A cell (r, c) of an excel sheet is represented as a string "" where: + * + * denotes the column number c of the cell. It is represented by alphabetical letters. + * + * For example, the 1^st column is denoted by 'A', the 2^nd by 'B', the 3^rd by 'C', and so on. + * + * + * is the row number r of the cell. The r^th row is represented by the integer r. + * + * You are given a string s in the format ":", where represents the column c1, represents the row r1, represents the column c2, and represents the row r2, such that r1 <= r2 and c1 <= c2. + * Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows. + * + * Example 1: + * + * Input: s = "K1:L2" + * Output: ["K1","K2","L1","L2"] + * Explanation: + * The above diagram shows the cells which should be present in the list. + * The red arrows denote the order in which the cells should be presented. + * + * Example 2: + * + * Input: s = "A1:F1" + * Output: ["A1","B1","C1","D1","E1","F1"] + * Explanation: + * The above diagram shows the cells which should be present in the list. + * The red arrow denotes the order in which the cells should be presented. + * + * + * Constraints: + * + * s.length == 5 + * 'A' <= s[0] <= s[3] <= 'Z' + * '1' <= s[1] <= s[4] <= '9' + * s consists of uppercase English letters, digits and ':'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/ +// discuss: https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn cells_in_range(s: String) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2194() { + } +} diff --git a/src/problem/p2196_create_binary_tree_from_descriptions.rs b/src/problem/p2196_create_binary_tree_from_descriptions.rs new file mode 100644 index 00000000..8abd3e54 --- /dev/null +++ b/src/problem/p2196_create_binary_tree_from_descriptions.rs @@ -0,0 +1,79 @@ +/** + * [2196] Create Binary Tree From Descriptions + * + * You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, + * + * If isLefti == 1, then childi is the left child of parenti. + * If isLefti == 0, then childi is the right child of parenti. + * + * Construct the binary tree described by descriptions and return its root. + * The test cases will be generated such that the binary tree is valid. + * + * Example 1: + * + * Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]] + * Output: [50,20,80,15,17,19] + * Explanation: The root node is the node with value 50 since it has no parent. + * The resulting binary tree is shown in the diagram. + * + * Example 2: + * + * Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]] + * Output: [1,2,null,null,3,4] + * Explanation: The root node is the node with value 1 since it has no parent. + * The resulting binary tree is shown in the diagram. + * + * + * Constraints: + * + * 1 <= descriptions.length <= 10^4 + * descriptions[i].length == 3 + * 1 <= parenti, childi <= 10^5 + * 0 <= isLefti <= 1 + * The binary tree described by descriptions is valid. + * + */ +pub struct Solution {} +use crate::util::tree::{TreeNode, to_tree}; + +// problem: https://leetcode.com/problems/create-binary-tree-from-descriptions/ +// discuss: https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn create_binary_tree(descriptions: Vec>) -> Option>> { + Some(Rc::new(RefCell::new(TreeNode::new(0)))) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2196() { + } +} diff --git a/src/problem/p2197_replace_non_coprime_numbers_in_array.rs b/src/problem/p2197_replace_non_coprime_numbers_in_array.rs new file mode 100644 index 00000000..d513b857 --- /dev/null +++ b/src/problem/p2197_replace_non_coprime_numbers_in_array.rs @@ -0,0 +1,70 @@ +/** + * [2197] Replace Non-Coprime Numbers in Array + * + * You are given an array of integers nums. Perform the following steps: + *
    + * Find any two adjacent numbers in nums that are non-coprime. + * If no such numbers are found, stop the process. + * Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple). + * Repeat this process as long as you keep finding two adjacent non-coprime numbers. + *
+ * Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. + * The test cases are generated such that the values in the final array are less than or equal to 10^8. + * Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y. + * + * Example 1: + * + * Input: nums = [6,4,3,2,7,6,2] + * Output: [12,7,6] + * Explanation: + * - (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2]. + * - (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2]. + * - (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2]. + * - (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6]. + * There are no more adjacent non-coprime numbers in nums. + * Thus, the final modified array is [12,7,6]. + * Note that there are other ways to obtain the same resultant array. + * + * Example 2: + * + * Input: nums = [2,2,1,1,3,3,3] + * Output: [2,1,1,3] + * Explanation: + * - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3]. + * - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3]. + * - (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3]. + * There are no more adjacent non-coprime numbers in nums. + * Thus, the final modified array is [2,1,1,3]. + * Note that there are other ways to obtain the same resultant array. + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * 1 <= nums[i] <= 10^5 + * The test cases are generated such that the values in the final array are less than or equal to 10^8. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/replace-non-coprime-numbers-in-array/ +// discuss: https://leetcode.com/problems/replace-non-coprime-numbers-in-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn replace_non_coprimes(nums: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2197() { + } +} diff --git a/src/problem/p2201_count_artifacts_that_can_be_extracted.rs b/src/problem/p2201_count_artifacts_that_can_be_extracted.rs new file mode 100644 index 00000000..7541f35e --- /dev/null +++ b/src/problem/p2201_count_artifacts_that_can_be_extracted.rs @@ -0,0 +1,71 @@ +/** + * [2201] Count Artifacts That Can Be Extracted + * + * There is an n x n 0-indexed grid with some artifacts buried in it. You are given the integer n and a 0-indexed 2D integer array artifacts describing the positions of the rectangular artifacts where artifacts[i] = [r1i, c1i, r2i, c2i] denotes that the i^th artifact is buried in the subgrid where: + * + * (r1i, c1i) is the coordinate of the top-left cell of the i^th artifact and + * (r2i, c2i) is the coordinate of the bottom-right cell of the i^th artifact. + * + * You will excavate some cells of the grid and remove all the mud from them. If the cell has a part of an artifact buried underneath, it will be uncovered. If all the parts of an artifact are uncovered, you can extract it. + * Given a 0-indexed 2D integer array dig where dig[i] = [ri, ci] indicates that you will excavate the cell (ri, ci), return the number of artifacts that you can extract. + * The test cases are generated such that: + * + * No two artifacts overlap. + * Each artifact only covers at most 4 cells. + * The entries of dig are unique. + * + * + * Example 1: + * + * Input: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1]] + * Output: 1 + * Explanation: + * The different colors represent different artifacts. Excavated cells are labeled with a 'D' in the grid. + * There is 1 artifact that can be extracted, namely the red artifact. + * The blue artifact has one part in cell (1,1) which remains uncovered, so we cannot extract it. + * Thus, we return 1. + * + * Example 2: + * + * Input: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1],[1,1]] + * Output: 2 + * Explanation: Both the red and blue artifacts have all parts uncovered (labeled with a 'D') and can be extracted, so we return 2. + * + * + * Constraints: + * + * 1 <= n <= 1000 + * 1 <= artifacts.length, dig.length <= min(n^2, 10^5) + * artifacts[i].length == 4 + * dig[i].length == 2 + * 0 <= r1i, c1i, r2i, c2i, ri, ci <= n - 1 + * r1i <= r2i + * c1i <= c2i + * No two artifacts will overlap. + * The number of cells covered by an artifact is at most 4. + * The entries of dig are unique. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-artifacts-that-can-be-extracted/ +// discuss: https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn dig_artifacts(n: i32, artifacts: Vec>, dig: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2201() { + } +} diff --git a/src/problem/p2206_divide_array_into_equal_pairs.rs b/src/problem/p2206_divide_array_into_equal_pairs.rs new file mode 100644 index 00000000..7f160d51 --- /dev/null +++ b/src/problem/p2206_divide_array_into_equal_pairs.rs @@ -0,0 +1,57 @@ +/** + * [2206] Divide Array Into Equal Pairs + * + * You are given an integer array nums consisting of 2 * n integers. + * You need to divide nums into n pairs such that: + * + * Each element belongs to exactly one pair. + * The elements present in a pair are equal. + * + * Return true if nums can be divided into n pairs, otherwise return false. + * + * Example 1: + * + * Input: nums = [3,2,3,2,2,2] + * Output: true + * Explanation: + * There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs. + * If nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions. + * + * Example 2: + * + * Input: nums = [1,2,3,4] + * Output: false + * Explanation: + * There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition. + * + * + * Constraints: + * + * nums.length == 2 * n + * 1 <= n <= 500 + * 1 <= nums[i] <= 500 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/divide-array-into-equal-pairs/ +// discuss: https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn divide_array(nums: Vec) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2206() { + } +} diff --git a/src/problem/p2207_maximize_number_of_subsequences_in_a_string.rs b/src/problem/p2207_maximize_number_of_subsequences_in_a_string.rs new file mode 100644 index 00000000..66e8073a --- /dev/null +++ b/src/problem/p2207_maximize_number_of_subsequences_in_a_string.rs @@ -0,0 +1,56 @@ +/** + * [2207] Maximize Number of Subsequences in a String + * + * You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. + * You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. + * Return the maximum number of times pattern can occur as a subsequence of the modified text. + * A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. + * + * Example 1: + * + * Input: text = "abdcdbc", pattern = "ac" + * Output: 4 + * Explanation: + * If we add pattern[0] = 'a' in between text[1] and text[2], we get "abadcdbc". Now, the number of times "ac" occurs as a subsequence is 4. + * Some other strings which have 4 subsequences "ac" after adding a character to text are "aabdcdbc" and "abdacdbc". + * However, strings such as "abdcadbc", "abdccdbc", and "abdcdbcc", although obtainable, have only 3 subsequences "ac" and are thus suboptimal. + * It can be shown that it is not possible to get more than 4 subsequences "ac" by adding only one character. + * + * Example 2: + * + * Input: text = "aabb", pattern = "ab" + * Output: 6 + * Explanation: + * Some of the strings which can be obtained from text and have 6 subsequences "ab" are "aaabb", "aaabb", and "aabbb". + * + * + * Constraints: + * + * 1 <= text.length <= 10^5 + * pattern.length == 2 + * text and pattern consist only of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/ +// discuss: https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn maximum_subsequence_count(text: String, pattern: String) -> i64 { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2207() { + } +} diff --git a/src/problem/p2213_longest_substring_of_one_repeating_character.rs b/src/problem/p2213_longest_substring_of_one_repeating_character.rs new file mode 100644 index 00000000..b0502905 --- /dev/null +++ b/src/problem/p2213_longest_substring_of_one_repeating_character.rs @@ -0,0 +1,61 @@ +/** + * [2213] Longest Substring of One Repeating Character + * + * You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. + * The i^th query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. + * Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the i^th query is performed. + * + * Example 1: + * + * Input: s = "babacc", queryCharacters = "bcb", queryIndices = [1,3,3] + * Output: [3,3,4] + * Explanation: + * - 1^st query updates s = "bbbacc". The longest substring consisting of one repeating character is "bbb" with length 3. + * - 2^nd query updates s = "bbbccc". + * The longest substring consisting of one repeating character can be "bbb" or "ccc" with length 3. + * - 3^rd query updates s = "bbbbcc". The longest substring consisting of one repeating character is "bbbb" with length 4. + * Thus, we return [3,3,4]. + * + * Example 2: + * + * Input: s = "abyzz", queryCharacters = "aa", queryIndices = [2,1] + * Output: [2,3] + * Explanation: + * - 1^st query updates s = "abazz". The longest substring consisting of one repeating character is "zz" with length 2. + * - 2^nd query updates s = "aaazz". The longest substring consisting of one repeating character is "aaa" with length 3. + * Thus, we return [2,3]. + * + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s consists of lowercase English letters. + * k == queryCharacters.length == queryIndices.length + * 1 <= k <= 10^5 + * queryCharacters consists of lowercase English letters. + * 0 <= queryIndices[i] < s.length + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/longest-substring-of-one-repeating-character/ +// discuss: https://leetcode.com/problems/longest-substring-of-one-repeating-character/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn longest_repeating(s: String, query_characters: String, query_indices: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2213() { + } +} diff --git a/src/problem/p2233_maximum_product_after_k_increments.rs b/src/problem/p2233_maximum_product_after_k_increments.rs new file mode 100644 index 00000000..de245533 --- /dev/null +++ b/src/problem/p2233_maximum_product_after_k_increments.rs @@ -0,0 +1,54 @@ +/** + * [2233] Maximum Product After K Increments + * + * You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. + * Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 10^9 + 7. Note that you should maximize the product before taking the modulo. + * + * Example 1: + * + * Input: nums = [0,4], k = 5 + * Output: 20 + * Explanation: Increment the first number 5 times. + * Now nums = [5, 4], with a product of 5 * 4 = 20. + * It can be shown that 20 is maximum product possible, so we return 20. + * Note that there may be other ways to increment nums to have the maximum product. + * + * Example 2: + * + * Input: nums = [6,3,3,2], k = 2 + * Output: 216 + * Explanation: Increment the second number 1 time and increment the fourth number 1 time. + * Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216. + * It can be shown that 216 is maximum product possible, so we return 216. + * Note that there may be other ways to increment nums to have the maximum product. + * + * + * Constraints: + * + * 1 <= nums.length, k <= 10^5 + * 0 <= nums[i] <= 10^6 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-product-after-k-increments/ +// discuss: https://leetcode.com/problems/maximum-product-after-k-increments/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn maximum_product(nums: Vec, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2233() { + } +} diff --git a/src/problem/p2235_add_two_integers.rs b/src/problem/p2235_add_two_integers.rs new file mode 100644 index 00000000..661d2279 --- /dev/null +++ b/src/problem/p2235_add_two_integers.rs @@ -0,0 +1,46 @@ +/** + * [2235] Add Two Integers + * + * Given two integers num1 and num2, return the sum of the two integers. + * + * Example 1: + * + * Input: num1 = 12, num2 = 5 + * Output: 17 + * Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. + * + * Example 2: + * + * Input: num1 = -10, num2 = 4 + * Output: -6 + * Explanation: num1 + num2 = -6, so -6 is returned. + * + * + * Constraints: + * + * -100 <= num1, num2 <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/add-two-integers/ +// discuss: https://leetcode.com/problems/add-two-integers/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn sum(num1: i32, num2: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2235() { + } +} diff --git a/src/problem/p2239_find_closest_number_to_zero.rs b/src/problem/p2239_find_closest_number_to_zero.rs new file mode 100644 index 00000000..d613f10b --- /dev/null +++ b/src/problem/p2239_find_closest_number_to_zero.rs @@ -0,0 +1,53 @@ +/** + * [2239] Find Closest Number to Zero + * + * Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value. + * + * Example 1: + * + * Input: nums = [-4,-2,1,4,8] + * Output: 1 + * Explanation: + * The distance from -4 to 0 is |-4| = 4. + * The distance from -2 to 0 is |-2| = 2. + * The distance from 1 to 0 is |1| = 1. + * The distance from 4 to 0 is |4| = 4. + * The distance from 8 to 0 is |8| = 8. + * Thus, the closest number to 0 in the array is 1. + * + * Example 2: + * + * Input: nums = [2,-1,1] + * Output: 1 + * Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned. + * + * + * Constraints: + * + * 1 <= n <= 1000 + * -10^5 <= nums[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-closest-number-to-zero/ +// discuss: https://leetcode.com/problems/find-closest-number-to-zero/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn find_closest_number(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2239() { + } +} diff --git a/src/problem/p2262_total_appeal_of_a_string.rs b/src/problem/p2262_total_appeal_of_a_string.rs new file mode 100644 index 00000000..204103c4 --- /dev/null +++ b/src/problem/p2262_total_appeal_of_a_string.rs @@ -0,0 +1,63 @@ +/** + * [2262] Total Appeal of A String + * + * The appeal of a string is the number of distinct characters found in the string. + * + * For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'. + * + * Given a string s, return the total appeal of all of its substrings. + * A substring is a contiguous sequence of characters within a string. + * + * Example 1: + * + * Input: s = "abbca" + * Output: 28 + * Explanation: The following are the substrings of "abbca": + * - Substrings of length 1: "a", "b", "b", "c", "a" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5. + * - Substrings of length 2: "ab", "bb", "bc", "ca" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7. + * - Substrings of length 3: "abb", "bbc", "bca" have an appeal of 2, 2, and 3 respectively. The sum is 7. + * - Substrings of length 4: "abbc", "bbca" have an appeal of 3 and 3 respectively. The sum is 6. + * - Substrings of length 5: "abbca" has an appeal of 3. The sum is 3. + * The total sum is 5 + 7 + 7 + 6 + 3 = 28. + * + * Example 2: + * + * Input: s = "code" + * Output: 20 + * Explanation: The following are the substrings of "code": + * - Substrings of length 1: "c", "o", "d", "e" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4. + * - Substrings of length 2: "co", "od", "de" have an appeal of 2, 2, and 2 respectively. The sum is 6. + * - Substrings of length 3: "cod", "ode" have an appeal of 3 and 3 respectively. The sum is 6. + * - Substrings of length 4: "code" has an appeal of 4. The sum is 4. + * The total sum is 4 + 6 + 6 + 4 = 20. + * + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s consists of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/total-appeal-of-a-string/ +// discuss: https://leetcode.com/problems/total-appeal-of-a-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn appeal_sum(s: String) -> i64 { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2262() { + } +} diff --git a/src/problem/p2264_largest_3_same_digit_number_in_string.rs b/src/problem/p2264_largest_3_same_digit_number_in_string.rs new file mode 100644 index 00000000..358213fb --- /dev/null +++ b/src/problem/p2264_largest_3_same_digit_number_in_string.rs @@ -0,0 +1,64 @@ +/** + * [2264] Largest 3-Same-Digit Number in String + * + * You are given a string num representing a large integer. An integer is good if it meets the following conditions: + * + * It is a substring of num with length 3. + * It consists of only one unique digit. + * + * Return the maximum good integer as a string or an empty string "" if no such integer exists. + * Note: + * + * A substring is a contiguous sequence of characters within a string. + * There may be leading zeroes in num or a good integer. + * + * + * Example 1: + * + * Input: num = "6777133339" + * Output: "777" + * Explanation: There are two distinct good integers: "777" and "333". + * "777" is the largest, so we return "777". + * + * Example 2: + * + * Input: num = "2300019" + * Output: "000" + * Explanation: "000" is the only good integer. + * + * Example 3: + * + * Input: num = "42352338" + * Output: "" + * Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers. + * + * + * Constraints: + * + * 3 <= num.length <= 1000 + * num only consists of digits. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/largest-3-same-digit-number-in-string/ +// discuss: https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn largest_good_integer(num: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2264() { + } +} diff --git a/src/problem/p2269_find_the_k_beauty_of_a_number.rs b/src/problem/p2269_find_the_k_beauty_of_a_number.rs new file mode 100644 index 00000000..c6a6c5a9 --- /dev/null +++ b/src/problem/p2269_find_the_k_beauty_of_a_number.rs @@ -0,0 +1,67 @@ +/** + * [2269] Find the K-Beauty of a Number + * + * The k-beauty of an integer num is defined as the number of substrings of num when it is read as a string that meet the following conditions: + * + * It has a length of k. + * It is a divisor of num. + * + * Given integers num and k, return the k-beauty of num. + * Note: + * + * Leading zeros are allowed. + * 0 is not a divisor of any value. + * + * A substring is a contiguous sequence of characters in a string. + * + * Example 1: + * + * Input: num = 240, k = 2 + * Output: 2 + * Explanation: The following are the substrings of num of length k: + * - "24" from "240": 24 is a divisor of 240. + * - "40" from "240": 40 is a divisor of 240. + * Therefore, the k-beauty is 2. + * + * Example 2: + * + * Input: num = 430043, k = 2 + * Output: 2 + * Explanation: The following are the substrings of num of length k: + * - "43" from "430043": 43 is a divisor of 430043. + * - "30" from "430043": 30 is not a divisor of 430043. + * - "00" from "430043": 0 is not a divisor of 430043. + * - "04" from "430043": 4 is not a divisor of 430043. + * - "43" from "430043": 43 is a divisor of 430043. + * Therefore, the k-beauty is 2. + * + * + * Constraints: + * + * 1 <= num <= 10^9 + * 1 <= k <= num.length (taking num as a string) + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-the-k-beauty-of-a-number/ +// discuss: https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn divisor_substrings(num: i32, k: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2269() { + } +} diff --git a/src/problem/p2271_maximum_white_tiles_covered_by_a_carpet.rs b/src/problem/p2271_maximum_white_tiles_covered_by_a_carpet.rs new file mode 100644 index 00000000..07a70c3d --- /dev/null +++ b/src/problem/p2271_maximum_white_tiles_covered_by_a_carpet.rs @@ -0,0 +1,56 @@ +/** + * [2271] Maximum White Tiles Covered by a Carpet + * + * You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range li <= j <= ri is colored white. + * You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere. + * Return the maximum number of white tiles that can be covered by the carpet. + * + * Example 1: + * + * Input: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10 + * Output: 9 + * Explanation: Place the carpet starting on tile 10. + * It covers 9 white tiles, so we return 9. + * Note that there may be other places where the carpet covers 9 white tiles. + * It can be shown that the carpet cannot cover more than 9 white tiles. + * + * Example 2: + * + * Input: tiles = [[10,11],[1,1]], carpetLen = 2 + * Output: 2 + * Explanation: Place the carpet starting on tile 10. + * It covers 2 white tiles, so we return 2. + * + * + * Constraints: + * + * 1 <= tiles.length <= 5 * 10^4 + * tiles[i].length == 2 + * 1 <= li <= ri <= 10^9 + * 1 <= carpetLen <= 10^9 + * The tiles are non-overlapping. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet/ +// discuss: https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn maximum_white_tiles(tiles: Vec>, carpet_len: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2271() { + } +} diff --git a/src/problem/p2273_find_resultant_array_after_removing_anagrams.rs b/src/problem/p2273_find_resultant_array_after_removing_anagrams.rs new file mode 100644 index 00000000..02ba594d --- /dev/null +++ b/src/problem/p2273_find_resultant_array_after_removing_anagrams.rs @@ -0,0 +1,58 @@ +/** + * [2273] Find Resultant Array After Removing Anagrams + * + * You are given a 0-indexed string array words, where words[i] consists of lowercase English letters. + * In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions. + * Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result. + * An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb" is an anagram of "abdc". + * + * Example 1: + * + * Input: words = ["abba","baba","bbaa","cd","cd"] + * Output: ["abba","cd"] + * Explanation: + * One of the ways we can obtain the resultant array is by using the following operations: + * - Since words[2] = "bbaa" and words[1] = "baba" are anagrams, we choose index 2 and delete words[2]. + * Now words = ["abba","baba","cd","cd"]. + * - Since words[1] = "baba" and words[0] = "abba" are anagrams, we choose index 1 and delete words[1]. + * Now words = ["abba","cd","cd"]. + * - Since words[2] = "cd" and words[1] = "cd" are anagrams, we choose index 2 and delete words[2]. + * Now words = ["abba","cd"]. + * We can no longer perform any operations, so ["abba","cd"] is the final answer. + * Example 2: + * + * Input: words = ["a","b","c","d","e"] + * Output: ["a","b","c","d","e"] + * Explanation: + * No two adjacent strings in words are anagrams of each other, so no operations are performed. + * + * Constraints: + * + * 1 <= words.length <= 100 + * 1 <= words[i].length <= 10 + * words[i] consists of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-resultant-array-after-removing-anagrams/ +// discuss: https://leetcode.com/problems/find-resultant-array-after-removing-anagrams/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn remove_anagrams(words: Vec) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2273() { + } +} diff --git a/src/problem/p2287_rearrange_characters_to_make_target_string.rs b/src/problem/p2287_rearrange_characters_to_make_target_string.rs new file mode 100644 index 00000000..1dc544e1 --- /dev/null +++ b/src/problem/p2287_rearrange_characters_to_make_target_string.rs @@ -0,0 +1,64 @@ +/** + * [2287] Rearrange Characters to Make Target String + * + * You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings. + * Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them. + * + * Example 1: + * + * Input: s = "ilovecodingonleetcode", target = "code" + * Output: 2 + * Explanation: + * For the first copy of "code", take the letters at indices 4, 5, 6, and 7. + * For the second copy of "code", take the letters at indices 17, 18, 19, and 20. + * The strings that are formed are "ecod" and "code" which can both be rearranged into "code". + * We can make at most two copies of "code", so we return 2. + * + * Example 2: + * + * Input: s = "abcba", target = "abc" + * Output: 1 + * Explanation: + * We can make one copy of "abc" by taking the letters at indices 0, 1, and 2. + * We can make at most one copy of "abc", so we return 1. + * Note that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of "abc". + * + * Example 3: + * + * Input: s = "abbaccaddaeea", target = "aaaaa" + * Output: 1 + * Explanation: + * We can make one copy of "aaaaa" by taking the letters at indices 0, 3, 6, 9, and 12. + * We can make at most one copy of "aaaaa", so we return 1. + * + * + * Constraints: + * + * 1 <= s.length <= 100 + * 1 <= target.length <= 10 + * s and target consist of lowercase English letters. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/rearrange-characters-to-make-target-string/ +// discuss: https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn rearrange_characters(s: String, target: String) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2287() { + } +} diff --git a/src/problem/p2295_replace_elements_in_an_array.rs b/src/problem/p2295_replace_elements_in_an_array.rs new file mode 100644 index 00000000..5ca3cd23 --- /dev/null +++ b/src/problem/p2295_replace_elements_in_an_array.rs @@ -0,0 +1,67 @@ +/** + * [2295] Replace Elements in an Array + * + * You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the i^th operation you replace the number operations[i][0] with operations[i][1]. + * It is guaranteed that in the i^th operation: + * + * operations[i][0] exists in nums. + * operations[i][1] does not exist in nums. + * + * Return the array obtained after applying all the operations. + * + * Example 1: + * + * Input: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]] + * Output: [3,2,7,1] + * Explanation: We perform the following operations on nums: + * - Replace the number 1 with 3. nums becomes [3,2,4,6]. + * - Replace the number 4 with 7. nums becomes [3,2,7,6]. + * - Replace the number 6 with 1. nums becomes [3,2,7,1]. + * We return the final array [3,2,7,1]. + * + * Example 2: + * + * Input: nums = [1,2], operations = [[1,3],[2,1],[3,2]] + * Output: [2,1] + * Explanation: We perform the following operations to nums: + * - Replace the number 1 with 3. nums becomes [3,2]. + * - Replace the number 2 with 1. nums becomes [3,1]. + * - Replace the number 3 with 2. nums becomes [2,1]. + * We return the array [2,1]. + * + * + * Constraints: + * + * n == nums.length + * m == operations.length + * 1 <= n, m <= 10^5 + * All the values of nums are distinct. + * operations[i].length == 2 + * 1 <= nums[i], operations[i][0], operations[i][1] <= 10^6 + * operations[i][0] will exist in nums when applying the i^th operation. + * operations[i][1] will not exist in nums when applying the i^th operation. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/replace-elements-in-an-array/ +// discuss: https://leetcode.com/problems/replace-elements-in-an-array/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn array_change(nums: Vec, operations: Vec>) -> Vec { + vec![] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2295() { + } +} diff --git a/src/problem/p2299_strong_password_checker_ii.rs b/src/problem/p2299_strong_password_checker_ii.rs new file mode 100644 index 00000000..587529d1 --- /dev/null +++ b/src/problem/p2299_strong_password_checker_ii.rs @@ -0,0 +1,61 @@ +/** + * [2299] Strong Password Checker II + * + * A password is said to be strong if it satisfies all the following criteria: + * + * It has at least 8 characters. + * It contains at least one lowercase letter. + * It contains at least one uppercase letter. + * It contains at least one digit. + * It contains at least one special character. The special characters are the characters in the following string: "!@#$%^&*()-+". + * It does not contain 2 of the same character in adjacent positions (i.e., "aab" violates this condition, but "aba" does not). + * + * Given a string password, return true if it is a strong password. Otherwise, return false. + * + * Example 1: + * + * Input: password = "IloveLe3tcode!" + * Output: true + * Explanation: The password meets all the requirements. Therefore, we return true. + * + * Example 2: + * + * Input: password = "Me+You--IsMyDream" + * Output: false + * Explanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false. + * + * Example 3: + * + * Input: password = "1aB!" + * Output: false + * Explanation: The password does not meet the length requirement. Therefore, we return false. + * + * Constraints: + * + * 1 <= password.length <= 100 + * password consists of letters, digits, and special characters: "!@#$%^&*()-+". + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/strong-password-checker-ii/ +// discuss: https://leetcode.com/problems/strong-password-checker-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn strong_password_checker_ii(password: String) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2299() { + } +} diff --git a/src/problem/p2301_match_substring_after_replacement.rs b/src/problem/p2301_match_substring_after_replacement.rs new file mode 100644 index 00000000..f4cff230 --- /dev/null +++ b/src/problem/p2301_match_substring_after_replacement.rs @@ -0,0 +1,65 @@ +/** + * [2301] Match Substring After Replacement + * + * You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times: + * + * Replace a character oldi of sub with newi. + * + * Each character in sub cannot be replaced more than once. + * Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false. + * A substring is a contiguous non-empty sequence of characters within a string. + * + * Example 1: + * + * Input: s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]] + * Output: true + * Explanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'. + * Now sub = "l3e7" is a substring of s, so we return true. + * Example 2: + * + * Input: s = "fooleetbar", sub = "f00l", mappings = [["o","0"]] + * Output: false + * Explanation: The string "f00l" is not a substring of s and no replacements can be made. + * Note that we cannot replace '0' with 'o'. + * + * Example 3: + * + * Input: s = "Fool33tbaR", sub = "leetd", mappings = [["e","3"],["t","7"],["t","8"],["d","b"],["p","b"]] + * Output: true + * Explanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'. + * Now sub = "l33tb" is a substring of s, so we return true. + * + * + * Constraints: + * + * 1 <= sub.length <= s.length <= 5000 + * 0 <= mappings.length <= 1000 + * mappings[i].length == 2 + * oldi != newi + * s and sub consist of uppercase and lowercase English letters and digits. + * oldi and newi are either uppercase or lowercase English letters or digits. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/match-substring-after-replacement/ +// discuss: https://leetcode.com/problems/match-substring-after-replacement/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn match_replacement(s: String, sub: String, mappings: Vec>) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2301() { + } +} diff --git a/src/problem/p2316_count_unreachable_pairs_of_nodes_in_an_undirected_graph.rs b/src/problem/p2316_count_unreachable_pairs_of_nodes_in_an_undirected_graph.rs new file mode 100644 index 00000000..23de5d40 --- /dev/null +++ b/src/problem/p2316_count_unreachable_pairs_of_nodes_in_an_undirected_graph.rs @@ -0,0 +1,54 @@ +/** + * [2316] Count Unreachable Pairs of Nodes in an Undirected Graph + * + * You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. + * Return the number of pairs of different nodes that are unreachable from each other. + * + * Example 1: + * + * Input: n = 3, edges = [[0,1],[0,2],[1,2]] + * Output: 0 + * Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0. + * + * Example 2: + * + * Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]] + * Output: 14 + * Explanation: There are 14 pairs of nodes that are unreachable from each other: + * [[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]]. + * Therefore, we return 14. + * + * + * Constraints: + * + * 1 <= n <= 10^5 + * 0 <= edges.length <= 2 * 10^5 + * edges[i].length == 2 + * 0 <= ai, bi < n + * ai != bi + * There are no repeated edges. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/ +// discuss: https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_pairs(n: i32, edges: Vec>) -> i64 { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2316() { + } +} diff --git a/src/problem/p2325_decode_the_message.rs b/src/problem/p2325_decode_the_message.rs new file mode 100644 index 00000000..d34960fa --- /dev/null +++ b/src/problem/p2325_decode_the_message.rs @@ -0,0 +1,62 @@ +/** + * [2325] Decode the Message + * + * You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows: + *
    + * Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table. + * Align the substitution table with the regular English alphabet. + * Each letter in message is then substituted using the table. + * Spaces ' ' are transformed to themselves. + *
+ * + * For example, given key = "happy boy" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b', 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f'). + * + * Return the decoded message. + * + * Example 1: + * + * Input: key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv" + * Output: "this is a secret" + * Explanation: The diagram above shows the substitution table. + * It is obtained by taking the first appearance of each letter in "the quick brown fox jumps over the lazy dog". + * + * Example 2: + * + * Input: key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb" + * Output: "the five boxing wizards jump quickly" + * Explanation: The diagram above shows the substitution table. + * It is obtained by taking the first appearance of each letter in "eljuxhpwnyrdgtqkviszcfmabo". + * + * + * Constraints: + * + * 26 <= key.length <= 2000 + * key consists of lowercase English letters and ' '. + * key contains every letter in the English alphabet ('a' to 'z') at least once. + * 1 <= message.length <= 2000 + * message consists of lowercase English letters and ' '. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/decode-the-message/ +// discuss: https://leetcode.com/problems/decode-the-message/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn decode_message(key: String, message: String) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2325() { + } +} diff --git a/src/problem/p2328_number_of_increasing_paths_in_a_grid.rs b/src/problem/p2328_number_of_increasing_paths_in_a_grid.rs new file mode 100644 index 00000000..487cad10 --- /dev/null +++ b/src/problem/p2328_number_of_increasing_paths_in_a_grid.rs @@ -0,0 +1,59 @@ +/** + * [2328] Number of Increasing Paths in a Grid + * + * You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions. + * Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 10^9 + 7. + * Two paths are considered different if they do not have exactly the same sequence of visited cells. + * + * Example 1: + * + * Input: grid = [[1,1],[3,4]] + * Output: 8 + * Explanation: The strictly increasing paths are: + * - Paths with length 1: [1], [1], [3], [4]. + * - Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4]. + * - Paths with length 3: [1 -> 3 -> 4]. + * The total number of paths is 4 + 3 + 1 = 8. + * + * Example 2: + * + * Input: grid = [[1],[2]] + * Output: 3 + * Explanation: The strictly increasing paths are: + * - Paths with length 1: [1], [2]. + * - Paths with length 2: [1 -> 2]. + * The total number of paths is 2 + 1 = 3. + * + * + * Constraints: + * + * m == grid.length + * n == grid[i].length + * 1 <= m, n <= 1000 + * 1 <= m * n <= 10^5 + * 1 <= grid[i][j] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/ +// discuss: https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_paths(grid: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2328() { + } +} diff --git a/src/problem/p2337_move_pieces_to_obtain_a_string.rs b/src/problem/p2337_move_pieces_to_obtain_a_string.rs new file mode 100644 index 00000000..b788b28b --- /dev/null +++ b/src/problem/p2337_move_pieces_to_obtain_a_string.rs @@ -0,0 +1,63 @@ +/** + * [2337] Move Pieces to Obtain a String + * + * You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where: + * + * The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right. + * The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces. + * + * Return true if it is possible to obtain the string target by moving the pieces of the string start any number of times. Otherwise, return false. + * + * Example 1: + * + * Input: start = "_L__R__R_", target = "L______RR" + * Output: true + * Explanation: We can obtain the string target from start by doing the following moves: + * - Move the first piece one step to the left, start becomes equal to "L___R__R_". + * - Move the last piece one step to the right, start becomes equal to "L___R___R". + * - Move the second piece three steps to the right, start becomes equal to "L______RR". + * Since it is possible to get the string target from start, we return true. + * + * Example 2: + * + * Input: start = "R_L_", target = "__LR" + * Output: false + * Explanation: The 'R' piece in the string start can move one step to the right to obtain "_RL_". + * After that, no pieces can move anymore, so it is impossible to obtain the string target from start. + * + * Example 3: + * + * Input: start = "_R", target = "R_" + * Output: false + * Explanation: The piece in the string start can move only to the right, so it is impossible to obtain the string target from start. + * + * Constraints: + * + * n == start.length == target.length + * 1 <= n <= 10^5 + * start and target consist of the characters 'L', 'R', and '_'. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/move-pieces-to-obtain-a-string/ +// discuss: https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn can_change(start: String, target: String) -> bool { + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2337() { + } +} diff --git a/src/problem/p2342_max_sum_of_a_pair_with_equal_sum_of_digits.rs b/src/problem/p2342_max_sum_of_a_pair_with_equal_sum_of_digits.rs new file mode 100644 index 00000000..447e2ce2 --- /dev/null +++ b/src/problem/p2342_max_sum_of_a_pair_with_equal_sum_of_digits.rs @@ -0,0 +1,51 @@ +/** + * [2342] Max Sum of a Pair With Equal Sum of Digits + * + * You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j]. + * Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions. + * + * Example 1: + * + * Input: nums = [18,43,36,13,7] + * Output: 54 + * Explanation: The pairs (i, j) that satisfy the conditions are: + * - (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54. + * - (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50. + * So the maximum sum that we can obtain is 54. + * + * Example 2: + * + * Input: nums = [10,12,19,14] + * Output: -1 + * Explanation: There are no two numbers that satisfy the conditions, so we return -1. + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * 1 <= nums[i] <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/ +// discuss: https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn maximum_sum(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2342() { + } +} diff --git a/src/problem/p2347_best_poker_hand.rs b/src/problem/p2347_best_poker_hand.rs new file mode 100644 index 00000000..8bd2e8f2 --- /dev/null +++ b/src/problem/p2347_best_poker_hand.rs @@ -0,0 +1,66 @@ +/** + * [2347] Best Poker Hand + * + * You are given an integer array ranks and a character array suits. You have 5 cards where the i^th card has a rank of ranks[i] and a suit of suits[i]. + * The following are the types of poker hands you can make from best to worst: + *
    + * "Flush": Five cards of the same suit. + * "Three of a Kind": Three cards of the same rank. + * "Pair": Two cards of the same rank. + * "High Card": Any single card. + *
+ * Return a string representing the best type of poker hand you can make with the given cards. + * Note that the return values are case-sensitive. + * + * Example 1: + * + * Input: ranks = [13,2,3,1,9], suits = ["a","a","a","a","a"] + * Output: "Flush" + * Explanation: The hand with all the cards consists of 5 cards with the same suit, so we have a "Flush". + * + * Example 2: + * + * Input: ranks = [4,4,2,4,4], suits = ["d","a","a","b","c"] + * Output: "Three of a Kind" + * Explanation: The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a "Three of a Kind". + * Note that we could also make a "Pair" hand but "Three of a Kind" is a better hand. + * Also note that other cards could be used to make the "Three of a Kind" hand. + * Example 3: + * + * Input: ranks = [10,10,2,12,9], suits = ["a","b","c","a","d"] + * Output: "Pair" + * Explanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a "Pair". + * Note that we cannot make a "Flush" or a "Three of a Kind". + * + * + * Constraints: + * + * ranks.length == suits.length == 5 + * 1 <= ranks[i] <= 13 + * 'a' <= suits[i] <= 'd' + * No two cards have the same rank and suit. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/best-poker-hand/ +// discuss: https://leetcode.com/problems/best-poker-hand/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn best_hand(ranks: Vec, suits: Vec) -> String { + String::new() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2347() { + } +} diff --git a/src/problem/p2348_number_of_zero_filled_subarrays.rs b/src/problem/p2348_number_of_zero_filled_subarrays.rs new file mode 100644 index 00000000..5c738f22 --- /dev/null +++ b/src/problem/p2348_number_of_zero_filled_subarrays.rs @@ -0,0 +1,60 @@ +/** + * [2348] Number of Zero-Filled Subarrays + * + * Given an integer array nums, return the number of subarrays filled with 0. + * A subarray is a contiguous non-empty sequence of elements within an array. + * + * Example 1: + * + * Input: nums = [1,3,0,0,2,0,0,4] + * Output: 6 + * Explanation: + * There are 4 occurrences of [0] as a subarray. + * There are 2 occurrences of [0,0] as a subarray. + * There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6. + * Example 2: + * + * Input: nums = [0,0,0,2,0,0] + * Output: 9 + * Explanation: + * There are 5 occurrences of [0] as a subarray. + * There are 3 occurrences of [0,0] as a subarray. + * There is 1 occurrence of [0,0,0] as a subarray. + * There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9. + * + * Example 3: + * + * Input: nums = [2,10,2019] + * Output: 0 + * Explanation: There is no subarray filled with 0. Therefore, we return 0. + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * -10^9 <= nums[i] <= 10^9 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-zero-filled-subarrays/ +// discuss: https://leetcode.com/problems/number-of-zero-filled-subarrays/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn zero_filled_subarray(nums: Vec) -> i64 { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2348() { + } +} diff --git a/src/problem/p2349_design_a_number_container_system.rs b/src/problem/p2349_design_a_number_container_system.rs new file mode 100644 index 00000000..f37b8fcc --- /dev/null +++ b/src/problem/p2349_design_a_number_container_system.rs @@ -0,0 +1,88 @@ +/** + * [2349] Design a Number Container System + * + * Design a number container system that can do the following: + * + * Insert or Replace a number at the given index in the system. + * Return the smallest index for the given number in the system. + * + * Implement the NumberContainers class: + * + * NumberContainers() Initializes the number container system. + * void change(int index, int number) Fills the container at index with the number. If there is already a number at that index, replace it. + * int find(int number) Returns the smallest index for the given number, or -1 if there is no index that is filled by number in the system. + * + * + * Example 1: + * + * Input + * ["NumberContainers", "find", "change", "change", "change", "change", "find", "change", "find"] + * [[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]] + * Output + * [null, -1, null, null, null, null, 1, null, 2] + * Explanation + * NumberContainers nc = new NumberContainers(); + * nc.find(10); // There is no index that is filled with number 10. Therefore, we return -1. + * nc.change(2, 10); // Your container at index 2 will be filled with number 10. + * nc.change(1, 10); // Your container at index 1 will be filled with number 10. + * nc.change(3, 10); // Your container at index 3 will be filled with number 10. + * nc.change(5, 10); // Your container at index 5 will be filled with number 10. + * nc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1. + * nc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. + * nc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2. + * + * + * Constraints: + * + * 1 <= index, number <= 10^9 + * At most 10^5 calls will be made in total to change and find. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/design-a-number-container-system/ +// discuss: https://leetcode.com/problems/design-a-number-container-system/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct NumberContainers { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl NumberContainers { + + fn new() -> Self { + + } + + fn change(&self, index: i32, number: i32) { + + } + + fn find(&self, number: i32) -> i32 { + + } +} + +/** + * Your NumberContainers object will be instantiated and called as such: + * let obj = NumberContainers::new(); + * obj.change(index, number); + * let ret_2: i32 = obj.find(number); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2349() { + } +} diff --git a/src/problem/p2352_equal_row_and_column_pairs.rs b/src/problem/p2352_equal_row_and_column_pairs.rs new file mode 100644 index 00000000..8432a150 --- /dev/null +++ b/src/problem/p2352_equal_row_and_column_pairs.rs @@ -0,0 +1,53 @@ +/** + * [2352] Equal Row and Column Pairs + * + * Given a 0-indexed n x n integer matrix grid, return the number of pairs (Ri, Cj) such that row Ri and column Cj are equal. + * A row and column pair is considered equal if they contain the same elements in the same order (i.e. an equal array). + * + * Example 1: + * + * Input: grid = [[3,2,1],[1,7,6],[2,7,7]] + * Output: 1 + * Explanation: There is 1 equal row and column pair: + * - (Row 2, Column 1): [2,7,7] + * + * Example 2: + * + * Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]] + * Output: 3 + * Explanation: There are 3 equal row and column pairs: + * - (Row 0, Column 0): [3,1,2,2] + * - (Row 2, Column 2): [2,4,2,2] + * - (Row 3, Column 2): [2,4,2,2] + * + * + * Constraints: + * + * n == grid.length == grid[i].length + * 1 <= n <= 200 + * 1 <= grid[i][j] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/equal-row-and-column-pairs/ +// discuss: https://leetcode.com/problems/equal-row-and-column-pairs/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn equal_pairs(grid: Vec>) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2352() { + } +} diff --git a/src/problem/p2353_design_a_food_rating_system.rs b/src/problem/p2353_design_a_food_rating_system.rs new file mode 100644 index 00000000..0b3f94b5 --- /dev/null +++ b/src/problem/p2353_design_a_food_rating_system.rs @@ -0,0 +1,105 @@ +/** + * [2353] Design a Food Rating System + * + * Design a food rating system that can do the following: + * + * Modify the rating of a food item listed in the system. + * Return the highest-rated food item for a type of cuisine in the system. + * + * Implement the FoodRatings class: + * + * FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n. + * + * foods[i] is the name of the i^th food, + * cuisines[i] is the type of cuisine of the i^th food, and + * ratings[i] is the initial rating of the i^th food. + * + * + * void changeRating(String food, int newRating) Changes the rating of the food item with the name food. + * String highestRated(String cuisine) Returns the name of the food item that has the highest rating for the given type of cuisine. If there is a tie, return the item with the lexicographically smaller name. + * + * Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. + * + * Example 1: + * + * Input + * ["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"] + * [[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]] + * Output + * [null, "kimchi", "ramen", null, "sushi", null, "ramen"] + * Explanation + * FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]); + * foodRatings.highestRated("korean"); // return "kimchi" + * // "kimchi" is the highest rated korean food with a rating of 9. + * foodRatings.highestRated("japanese"); // return "ramen" + * // "ramen" is the highest rated japanese food with a rating of 14. + * foodRatings.changeRating("sushi", 16); // "sushi" now has a rating of 16. + * foodRatings.highestRated("japanese"); // return "sushi" + * // "sushi" is the highest rated japanese food with a rating of 16. + * foodRatings.changeRating("ramen", 16); // "ramen" now has a rating of 16. + * foodRatings.highestRated("japanese"); // return "ramen" + * // Both "sushi" and "ramen" have a rating of 16. + * // However, "ramen" is lexicographically smaller than "sushi". + * + * + * Constraints: + * + * 1 <= n <= 2 * 10^4 + * n == foods.length == cuisines.length == ratings.length + * 1 <= foods[i].length, cuisines[i].length <= 10 + * foods[i], cuisines[i] consist of lowercase English letters. + * 1 <= ratings[i] <= 10^8 + * All the strings in foods are distinct. + * food will be the name of a food item in the system across all calls to changeRating. + * cuisine will be a type of cuisine of at least one food item in the system across all calls to highestRated. + * At most 2 * 10^4 calls in total will be made to changeRating and highestRated. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/design-a-food-rating-system/ +// discuss: https://leetcode.com/problems/design-a-food-rating-system/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +struct FoodRatings { + false + } + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl FoodRatings { + + fn new(foods: Vec, cuisines: Vec, ratings: Vec) -> Self { + + } + + fn change_rating(&self, food: String, new_rating: i32) { + + } + + fn highest_rated(&self, cuisine: String) -> String { + + } +} + +/** + * Your FoodRatings object will be instantiated and called as such: + * let obj = FoodRatings::new(foods, cuisines, ratings); + * obj.change_rating(food, newRating); + * let ret_2: String = obj.highest_rated(cuisine); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2353() { + } +} diff --git a/src/problem/p2354_number_of_excellent_pairs.rs b/src/problem/p2354_number_of_excellent_pairs.rs new file mode 100644 index 00000000..2f1b0bbf --- /dev/null +++ b/src/problem/p2354_number_of_excellent_pairs.rs @@ -0,0 +1,59 @@ +/** + * [2354] Number of Excellent Pairs + * + * You are given a 0-indexed positive integer array nums and a positive integer k. + * A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied: + * + * Both the numbers num1 and num2 exist in the array nums. + * The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k, where OR is the bitwise OR operation and AND is the bitwise AND operation. + * + * Return the number of distinct excellent pairs. + * Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct. + * Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array. + * + * Example 1: + * + * Input: nums = [1,2,3,1], k = 3 + * Output: 5 + * Explanation: The excellent pairs are the following: + * - (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3. + * - (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3. + * - (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3. + * So the number of excellent pairs is 5. + * Example 2: + * + * Input: nums = [5,1,1], k = 10 + * Output: 0 + * Explanation: There are no excellent pairs for this array. + * + * + * Constraints: + * + * 1 <= nums.length <= 10^5 + * 1 <= nums[i] <= 10^9 + * 1 <= k <= 60 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-excellent-pairs/ +// discuss: https://leetcode.com/problems/number-of-excellent-pairs/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn count_excellent_pairs(nums: Vec, k: i32) -> i64 { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2354() { + } +} diff --git a/src/problem/p2357_make_array_zero_by_subtracting_equal_amounts.rs b/src/problem/p2357_make_array_zero_by_subtracting_equal_amounts.rs new file mode 100644 index 00000000..a592f3f3 --- /dev/null +++ b/src/problem/p2357_make_array_zero_by_subtracting_equal_amounts.rs @@ -0,0 +1,55 @@ +/** + * [2357] Make Array Zero by Subtracting Equal Amounts + * + * You are given a non-negative integer array nums. In one operation, you must: + * + * Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums. + * Subtract x from every positive element in nums. + * + * Return the minimum number of operations to make every element in nums equal to 0. + * + * Example 1: + * + * Input: nums = [1,5,0,3,5] + * Output: 3 + * Explanation: + * In the first operation, choose x = 1. Now, nums = [0,4,0,2,4]. + * In the second operation, choose x = 2. Now, nums = [0,2,0,0,2]. + * In the third operation, choose x = 2. Now, nums = [0,0,0,0,0]. + * + * Example 2: + * + * Input: nums = [0] + * Output: 0 + * Explanation: Each element in nums is already 0 so no operations are needed. + * + * + * Constraints: + * + * 1 <= nums.length <= 100 + * 0 <= nums[i] <= 100 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/ +// discuss: https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn minimum_operations(nums: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2357() { + } +} diff --git a/src/problem/p2358_maximum_number_of_groups_entering_a_competition.rs b/src/problem/p2358_maximum_number_of_groups_entering_a_competition.rs new file mode 100644 index 00000000..0f91e891 --- /dev/null +++ b/src/problem/p2358_maximum_number_of_groups_entering_a_competition.rs @@ -0,0 +1,56 @@ +/** + * [2358] Maximum Number of Groups Entering a Competition + * + * You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions: + * + * The sum of the grades of students in the i^th group is less than the sum of the grades of students in the (i + 1)^th group, for all groups (except the last). + * The total number of students in the i^th group is less than the total number of students in the (i + 1)^th group, for all groups (except the last). + * + * Return the maximum number of groups that can be formed. + * + * Example 1: + * + * Input: grades = [10,6,12,7,3,5] + * Output: 3 + * Explanation: The following is a possible way to form 3 groups of students: + * - 1^st group has the students with grades = [12]. Sum of grades: 12. Student count: 1 + * - 2^nd group has the students with grades = [6,7]. Sum of grades: 6 + 7 = 13. Student count: 2 + * - 3^rd group has the students with grades = [10,3,5]. Sum of grades: 10 + 3 + 5 = 18. Student count: 3 + * It can be shown that it is not possible to form more than 3 groups. + * + * Example 2: + * + * Input: grades = [8,8] + * Output: 1 + * Explanation: We can only form 1 group, since forming 2 groups would lead to an equal number of students in both groups. + * + * + * Constraints: + * + * 1 <= grades.length <= 10^5 + * 1 <= grades[i] <= 10^5 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/ +// discuss: https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn maximum_groups(grades: Vec) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2358() { + } +} diff --git a/src/problem/p2359_find_closest_node_to_given_two_nodes.rs b/src/problem/p2359_find_closest_node_to_given_two_nodes.rs new file mode 100644 index 00000000..f64bb600 --- /dev/null +++ b/src/problem/p2359_find_closest_node_to_given_two_nodes.rs @@ -0,0 +1,56 @@ +/** + * [2359] Find Closest Node to Given Two Nodes + * + * You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. + * The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then edges[i] == -1. + * You are also given two integers node1 and node2. + * Return the index of the node that can be reached from both node1 and node2, such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1. + * Note that edges may contain cycles. + * + * Example 1: + * + * Input: edges = [2,2,3,-1], node1 = 0, node2 = 1 + * Output: 2 + * Explanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1. + * The maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2. + * + * Example 2: + * + * Input: edges = [1,2,-1], node1 = 0, node2 = 2 + * Output: 2 + * Explanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0. + * The maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2. + * + * + * Constraints: + * + * n == edges.length + * 2 <= n <= 10^5 + * -1 <= edges[i] < n + * edges[i] != i + * 0 <= node1, node2 < n + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/find-closest-node-to-given-two-nodes/ +// discuss: https://leetcode.com/problems/find-closest-node-to-given-two-nodes/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn closest_meeting_node(edges: Vec, node1: i32, node2: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2359() { + } +} diff --git a/src/problem/p2365_task_scheduler_ii.rs b/src/problem/p2365_task_scheduler_ii.rs new file mode 100644 index 00000000..6da57dc0 --- /dev/null +++ b/src/problem/p2365_task_scheduler_ii.rs @@ -0,0 +1,74 @@ +/** + * [2365] Task Scheduler II + * + * You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the i^th task. + * You are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed. + * Each day, until all tasks have been completed, you must either: + * + * Complete the next task from tasks, or + * Take a break. + * + * Return the minimum number of days needed to complete all tasks. + * + * Example 1: + * + * Input: tasks = [1,2,1,2,3,1], space = 3 + * Output: 9 + * Explanation: + * One way to complete all tasks in 9 days is as follows: + * Day 1: Complete the 0th task. + * Day 2: Complete the 1st task. + * Day 3: Take a break. + * Day 4: Take a break. + * Day 5: Complete the 2nd task. + * Day 6: Complete the 3rd task. + * Day 7: Take a break. + * Day 8: Complete the 4th task. + * Day 9: Complete the 5th task. + * It can be shown that the tasks cannot be completed in less than 9 days. + * + * Example 2: + * + * Input: tasks = [5,8,8,5], space = 2 + * Output: 6 + * Explanation: + * One way to complete all tasks in 6 days is as follows: + * Day 1: Complete the 0th task. + * Day 2: Complete the 1st task. + * Day 3: Take a break. + * Day 4: Take a break. + * Day 5: Complete the 2nd task. + * Day 6: Complete the 3rd task. + * It can be shown that the tasks cannot be completed in less than 6 days. + * + * + * Constraints: + * + * 1 <= tasks.length <= 10^5 + * 1 <= tasks[i] <= 10^9 + * 1 <= space <= tasks.length + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/task-scheduler-ii/ +// discuss: https://leetcode.com/problems/task-scheduler-ii/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn task_scheduler_ii(tasks: Vec, space: i32) -> i64 { + + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2365() { + } +} diff --git a/src/problem/p2367_number_of_arithmetic_triplets.rs b/src/problem/p2367_number_of_arithmetic_triplets.rs new file mode 100644 index 00000000..eb38f4f1 --- /dev/null +++ b/src/problem/p2367_number_of_arithmetic_triplets.rs @@ -0,0 +1,59 @@ +/** + * [2367] Number of Arithmetic Triplets + * + * You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met: + * + * i < j < k, + * nums[j] - nums[i] == diff, and + * nums[k] - nums[j] == diff. + * + * Return the number of unique arithmetic triplets. + * + * Example 1: + * + * Input: nums = [0,1,4,6,7,10], diff = 3 + * Output: 2 + * Explanation: + * (1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3. + * (2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3. + * + * Example 2: + * + * Input: nums = [4,5,6,7,8,9], diff = 2 + * Output: 2 + * Explanation: + * (0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2. + * (1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2. + * + * + * Constraints: + * + * 3 <= nums.length <= 200 + * 0 <= nums[i] <= 200 + * 1 <= diff <= 50 + * nums is strictly increasing. + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-arithmetic-triplets/ +// discuss: https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn arithmetic_triplets(nums: Vec, diff: i32) -> i32 { + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2367() { + } +} diff --git a/src/solution/mod.rs b/src/solution/mod.rs index bc982de9..1479076c 100644 --- a/src/solution/mod.rs +++ b/src/solution/mod.rs @@ -1,237 +1,28 @@ mod s0001_two_sum; -mod s0002_add_two_numbers; -mod s0003_longest_substring_without_repeating_characters; mod s0004_median_of_two_sorted_arrays; -mod s0005_longest_palindromic_substring; mod s0006_zigzag_conversion; -mod s0007_reverse_integer; mod s0008_string_to_integer_atoi; -mod s0009_palindrome_number; -mod s0010_regular_expression_matching; mod s0011_container_with_most_water; mod s0012_integer_to_roman; -mod s0013_roman_to_integer; -mod s0014_longest_common_prefix; -mod s0015_3sum; -mod s0016_3sum_closest; -mod s0017_letter_combinations_of_a_phone_number; -mod s0018_4sum; -mod s0019_remove_nth_node_from_end_of_list; -mod s0020_valid_parentheses; -mod s0021_merge_two_sorted_lists; -mod s0022_generate_parentheses; -mod s0023_merge_k_sorted_lists; -mod s0024_swap_nodes_in_pairs; -mod s0025_reverse_nodes_in_k_group; -mod s0026_remove_duplicates_from_sorted_array; -mod s0027_remove_element; -mod s0028_implement_strstr; -mod s0029_divide_two_integers; -mod s0030_substring_with_concatenation_of_all_words; -mod s0031_next_permutation; -mod s0032_longest_valid_parentheses; -mod s0033_search_in_rotated_sorted_array; -mod s0034_find_first_and_last_position_of_element_in_sorted_array; -mod s0035_search_insert_position; -mod s0036_valid_sudoku; -mod s0037_sudoku_solver; -mod s0038_count_and_say; -mod s0039_combination_sum; -mod s0040_combination_sum_ii; -mod s0041_first_missing_positive; -mod s0042_trapping_rain_water; -mod s0043_multiply_strings; -mod s0044_wildcard_matching; -mod s0045_jump_game_ii; -mod s0046_permutations; -mod s0047_permutations_ii; -mod s0048_rotate_image; -mod s0049_group_anagrams; -mod s0050_powx_n; -mod s0051_n_queens; -mod s0052_n_queens_ii; -mod s0053_maximum_subarray; -mod s0054_spiral_matrix; -mod s0055_jump_game; -mod s0056_merge_intervals; -mod s0057_insert_interval; -mod s0058_length_of_last_word; -mod s0059_spiral_matrix_ii; -mod s0060_permutation_sequence; -mod s0061_rotate_list; -mod s0062_unique_paths; -mod s0063_unique_paths_ii; -mod s0064_minimum_path_sum; -mod s0065_valid_number; -mod s0066_plus_one; -mod s0067_add_binary; -mod s0068_text_justification; -mod s0069_sqrtx; -mod s0070_climbing_stairs; -mod s0071_simplify_path; -mod s0072_edit_distance; -mod s0073_set_matrix_zeroes; -mod s0074_search_a_2d_matrix; -mod s0075_sort_colors; -mod s0076_minimum_window_substring; -mod s0077_combinations; -mod s0078_subsets; -mod s0079_word_search; -mod s0080_remove_duplicates_from_sorted_array_ii; -mod s0081_search_in_rotated_sorted_array_ii; -mod s0082_remove_duplicates_from_sorted_list_ii; -mod s0083_remove_duplicates_from_sorted_list; -mod s0084_largest_rectangle_in_histogram; -mod s0085_maximal_rectangle; -mod s0086_partition_list; -mod s0087_scramble_string; -mod s0088_merge_sorted_array; -mod s0089_gray_code; -mod s0090_subsets_ii; -mod s0091_decode_ways; -mod s0092_reverse_linked_list_ii; -mod s0093_restore_ip_addresses; -mod s0094_binary_tree_inorder_traversal; -mod s0095_unique_binary_search_trees_ii; -mod s0096_unique_binary_search_trees; -mod s0097_interleaving_string; -mod s0098_validate_binary_search_tree; -mod s0099_recover_binary_search_tree; -mod s0100_same_tree; -mod s0101_symmetric_tree; -mod s0102_binary_tree_level_order_traversal; -mod s0103_binary_tree_zigzag_level_order_traversal; -mod s0104_maximum_depth_of_binary_tree; -mod s0105_construct_binary_tree_from_preorder_and_inorder_traversal; -mod s0106_construct_binary_tree_from_inorder_and_postorder_traversal; -mod s0107_binary_tree_level_order_traversal_ii; mod s0108_convert_sorted_array_to_binary_search_tree; -mod s0109_convert_sorted_list_to_binary_search_tree; -mod s0110_balanced_binary_tree; -mod s0111_minimum_depth_of_binary_tree; -mod s0112_path_sum; -mod s0113_path_sum_ii; -mod s0114_flatten_binary_tree_to_linked_list; -mod s0115_distinct_subsequences; -mod s0118_pascals_triangle; -mod s0119_pascals_triangle_ii; -mod s0120_triangle; -mod s0121_best_time_to_buy_and_sell_stock; -mod s0122_best_time_to_buy_and_sell_stock_ii; -mod s0123_best_time_to_buy_and_sell_stock_iii; -mod s0124_binary_tree_maximum_path_sum; -mod s0125_valid_palindrome; -mod s0126_word_ladder_ii; -mod s0127_word_ladder; -mod s0128_longest_consecutive_sequence; -mod s0129_sum_root_to_leaf_numbers; -mod s0130_surrounded_regions; -mod s0131_palindrome_partitioning; -mod s0132_palindrome_partitioning_ii; -mod s0134_gas_station; -mod s0135_candy; mod s0136_single_number; -mod s0137_single_number_ii; -mod s0139_word_break; -mod s0140_word_break_ii; -mod s0143_reorder_list; -mod s0144_binary_tree_preorder_traversal; -mod s0145_binary_tree_postorder_traversal; -mod s0146_lru_cache; -mod s0147_insertion_sort_list; -mod s0148_sort_list; -mod s0149_max_points_on_a_line; -mod s0150_evaluate_reverse_polish_notation; -mod s0151_reverse_words_in_a_string; -mod s0152_maximum_product_subarray; -mod s0153_find_minimum_in_rotated_sorted_array; -mod s0154_find_minimum_in_rotated_sorted_array_ii; -mod s0155_min_stack; -mod s0162_find_peak_element; -mod s0164_maximum_gap; -mod s0165_compare_version_numbers; -mod s0166_fraction_to_recurring_decimal; -mod s0167_two_sum_ii_input_array_is_sorted; -mod s0168_excel_sheet_column_title; -mod s0169_majority_element; -mod s0171_excel_sheet_column_number; -mod s0172_factorial_trailing_zeroes; -mod s0173_binary_search_tree_iterator; -mod s0174_dungeon_game; -mod s0179_largest_number; -mod s0187_repeated_dna_sequences; -mod s0188_best_time_to_buy_and_sell_stock_iv; -mod s0189_rotate_array; -mod s0198_house_robber; -mod s0199_binary_tree_right_side_view; -mod s0200_number_of_islands; -mod s0201_bitwise_and_of_numbers_range; -mod s0202_happy_number; -mod s0203_remove_linked_list_elements; -mod s0204_count_primes; -mod s0205_isomorphic_strings; -mod s0206_reverse_linked_list; -mod s0207_course_schedule; -mod s0208_implement_trie_prefix_tree; -mod s0209_minimum_size_subarray_sum; -mod s0210_course_schedule_ii; -mod s0211_add_and_search_word_data_structure_design; -mod s0212_word_search_ii; -mod s0213_house_robber_ii; -mod s0214_shortest_palindrome; -mod s0215_kth_largest_element_in_an_array; -mod s0216_combination_sum_iii; -mod s0217_contains_duplicate; -mod s0218_the_skyline_problem; -mod s0219_contains_duplicate_ii; -mod s0220_contains_duplicate_iii; -mod s0221_maximal_square; -mod s0222_count_complete_tree_nodes; -mod s0223_rectangle_area; -mod s0224_basic_calculator; -mod s0225_implement_stack_using_queues; -mod s0226_invert_binary_tree; -mod s0227_basic_calculator_ii; -mod s0228_summary_ranges; -mod s0229_majority_element_ii; -mod s0230_kth_smallest_element_in_a_bst; -mod s0231_power_of_two; -mod s0232_implement_queue_using_stacks; -mod s0233_number_of_digit_one; -mod s0238_product_of_array_except_self; -mod s0239_sliding_window_maximum; -mod s0241_different_ways_to_add_parentheses; -mod s0242_valid_anagram; -mod s0257_binary_tree_paths; -mod s0258_add_digits; -mod s0260_single_number_iii; -mod s0263_ugly_number; -mod s0264_ugly_number_ii; -mod s0268_missing_number; -mod s0273_integer_to_english_words; -mod s0274_h_index; -mod s0275_h_index_ii; -mod s0279_perfect_squares; -mod s0282_expression_add_operators; -mod s0283_move_zeroes; -mod s0287_find_the_duplicate_number; -mod s0289_game_of_life; -mod s0290_word_pattern; -mod s0292_nim_game; -mod s0295_find_median_from_data_stream; -mod s0299_bulls_and_cows; -mod s0300_longest_increasing_subsequence; -mod s0301_remove_invalid_parentheses; -mod s0303_range_sum_query_immutable; -mod s0304_range_sum_query_2d_immutable; -mod s0306_additive_number; -mod s0307_range_sum_query_mutable; -mod s0309_best_time_to_buy_and_sell_stock_with_cooldown; -mod s0310_minimum_height_trees; -mod s0312_burst_balloons; -mod s0313_super_ugly_number; -mod s0509_fibonacci_number; -mod s0704_binary_search; -mod s0969_pancake_sorting; -mod s1018_binary_prefix_divisible_by_5; -mod s1046_last_stone_weight; +mod s0622_design_circular_queue; +mod s0623_add_one_row_to_tree; +mod s0636_exclusive_time_of_function; +mod s0640_solve_the_equation; +mod s0641_design_circular_deque; +mod s0735_asteroid_collision; +mod s0761_special_binary_string; +mod s0768_max_chunks_to_make_sorted_ii; +mod s0769_max_chunks_to_make_sorted; +mod s0899_orderly_queue; +mod s1282_group_the_people_given_the_group_size_they_belong_to; +mod s1302_deepest_leaves_sum; +mod s1374_generate_a_string_with_characters_that_have_odd_counts; +mod s1403_minimum_subsequence_in_non_increasing_order; +mod s1408_string_matching_in_an_array; +mod s1413_minimum_value_to_get_positive_step_by_step_sum; +mod s1417_reformat_the_string; +mod s1422_maximum_score_after_splitting_a_string; +mod s1450_number_of_students_doing_homework_at_a_given_time; +mod s1656_design_an_ordered_stream; diff --git a/src/solution/s0001_two_sum.rs b/src/solution/s0001_two_sum.rs index 4a44a732..ae240a18 100644 --- a/src/solution/s0001_two_sum.rs +++ b/src/solution/s0001_two_sum.rs @@ -1,29 +1,36 @@ /** - * [1] Two Sum - * - * Given an array of integers, return indices of the two numbers such that they - * add up to a specific target. - * - * You may assume that each input would have exactly one solution, and you may - * not use the same element twice. - * - * Example: - * - * - * Given nums = [2, 7, 11, 15], target = 9, - * - * Because nums[0] + nums[1] = 2 + 7 = 9, - * return [0, 1]. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/two-sum/ -// discuss: https://leetcode.com/problems/two-sum/discuss/?currentPage=1&orderBy=most_votes&query= +* [0001] two sum +* +* 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。 +* 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 +* 你可以按任意顺序返回答案。 +* +* 示例 1: +* +* 输入:nums = [2,7,11,15], target = 9 +* 输出:[0,1] +* 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。 +* 示例 2: +* +* 输入:nums = [3,2,4], target = 6 +* 输出:[1,2] +* 示例 3: +* +* 输入:nums = [3,3], target = 6 +* 输出:[0,1] +* +* +* 提示: +* +* 2 <= nums.length <= 104 +* -109 <= nums[i] <= 109 +* -109 <= target <= 109 +* 只会存在一个有效答案 +*/ +use std::collections::HashMap; -// submission codes start here +pub struct Solution {} -use std::collections::HashMap; impl Solution { pub fn two_sum(nums: Vec, target: i32) -> Vec { let mut map = HashMap::with_capacity(nums.len()); @@ -38,16 +45,3 @@ impl Solution { vec![] } } - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_1() { - assert_eq!(vec![0, 1], Solution::two_sum(vec![2, 7, 11, 15], 9)); - assert_eq!(vec![1, 2], Solution::two_sum(vec![3, 2, 4], 6)); - } -} diff --git a/src/solution/s0002_add_two_numbers.rs b/src/solution/s0002_add_two_numbers.rs deleted file mode 100644 index d8bfc2d8..00000000 --- a/src/solution/s0002_add_two_numbers.rs +++ /dev/null @@ -1,98 +0,0 @@ -/** - * [2] Add Two Numbers - * - * You are given two non-empty linked lists representing two non-negative - * integers. The digits are stored in reverse order and each of their nodes - * contain a single digit. Add the two numbers and return it as a linked list. - * - * You may assume the two numbers do not contain any leading zero, except the - * number 0 itself. - * - * Example: - * - * - * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) - * Output: 7 -> 0 -> 8 - * Explanation: 342 + 465 = 807. - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/add-two-numbers/ -// discuss: https://leetcode.com/problems/add-two-numbers/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn add_two_numbers( - l1: Option>, - l2: Option>, - ) -> Option> { - let (mut l1, mut l2) = (l1, l2); - let mut dummy_head = Some(Box::new(ListNode::new(0))); - let mut tail = &mut dummy_head; - let (mut l1_end, mut l2_end, mut overflow) = (false, false, false); - loop { - let lhs = match l1 { - Some(node) => { - l1 = node.next; - node.val - } - None => { - l1_end = true; - 0 - } - }; - let rhs = match l2 { - Some(node) => { - l2 = node.next; - node.val - } - None => { - l2_end = true; - 0 - } - }; - // if l1, l2 end and there is not overflow from previous operation, return the result - if l1_end && l2_end && !overflow { - break dummy_head.unwrap().next; - } - let sum = lhs + rhs + if overflow { 1 } else { 0 }; - let sum = if sum >= 10 { - overflow = true; - sum - 10 - } else { - overflow = false; - sum - }; - tail.as_mut().unwrap().next = Some(Box::new(ListNode::new(sum))); - tail = &mut tail.as_mut().unwrap().next - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_2() { - assert_eq!( - Solution::add_two_numbers(to_list(vec![2, 4, 3]), to_list(vec![5, 6, 4])), - to_list(vec![7, 0, 8]) - ); - - assert_eq!( - Solution::add_two_numbers(to_list(vec![9, 9, 9, 9]), to_list(vec![9, 9, 9, 9, 9, 9])), - to_list(vec![8, 9, 9, 9, 0, 0, 1]) - ); - - assert_eq!( - Solution::add_two_numbers(to_list(vec![0]), to_list(vec![0])), - to_list(vec![0]) - ) - } -} diff --git a/src/solution/s0003_longest_substring_without_repeating_characters.rs b/src/solution/s0003_longest_substring_without_repeating_characters.rs deleted file mode 100644 index 0ad6903d..00000000 --- a/src/solution/s0003_longest_substring_without_repeating_characters.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [3] Longest Substring Without Repeating Characters - * - * Given a string, find the length of the longest substring without repeating characters. - * - * Example: - * - * Input: "abcabcbb" - * Output: 3 - * Explanation: The answer is "abc", with the length of 3. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-substring-without-repeating-characters/ -// discuss: https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn length_of_longest_substring(s: String) -> i32 { - let seq: Vec = s.chars().collect(); - let len = seq.len(); - let (mut start, mut end, mut max) = (0, 0, 0); - - while end < len { - for idx in start..end { - if seq[end] == seq[idx] { - start = idx + 1; - break; - } - } - let curr = end - start + 1; - if curr > max { - max = curr - } - end += 1 - } - max as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_3() { - assert_eq!( - Solution::length_of_longest_substring("abcabcbb".to_string()), - 3 - ); - assert_eq!(Solution::length_of_longest_substring("bbbb".to_string()), 1); - assert_eq!( - Solution::length_of_longest_substring("pwwkew".to_string()), - 3 - ); - } -} diff --git a/src/solution/s0004_median_of_two_sorted_arrays.rs b/src/solution/s0004_median_of_two_sorted_arrays.rs index e3c2d014..a8261237 100644 --- a/src/solution/s0004_median_of_two_sorted_arrays.rs +++ b/src/solution/s0004_median_of_two_sorted_arrays.rs @@ -1,62 +1,109 @@ +use std::num; + /** - * [4] Median of Two Sorted Arrays - * - * There are two sorted arrays nums1 and nums2 of size m and n respectively. - * - * Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). - * - * You may assume nums1 and nums2 cannot be both empty. + * [004] median of two sorted arrays * - * Example 1: + * 给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。 * + * 算法的时间复杂度应该为 O(log (m+n)) 。 * - * nums1 = [1, 3] - * nums2 = [2] * - * The median is 2.0 + * 示例 1: * + * 输入:nums1 = [1,3], nums2 = [2] + * 输出:2.00000 + * 解释:合并数组 = [1,2,3] ,中位数 2 + * 示例 2: * - * Example 2: - * - * - * nums1 = [1, 2] - * nums2 = [3, 4] - * - * The median is (2 + 3)/2 = 2.5 + * 输入:nums1 = [1,2], nums2 = [3,4] + * 输出:2.50000 + * 解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5 * + * 提示: * + * nums1.length == m + * nums2.length == n + * 0 <= m <= 1000 + * 0 <= n <= 1000 + * 1 <= m + n <= 2000 + * -106 <= nums1[i], nums2[i] <= 106 */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/median-of-two-sorted-arrays/ -// discuss: https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/?currentPage=1&orderBy=most_votes&query= +use std::cmp; -// submission codes start here +struct Solution; -// TODO: nth slice +/** + * 思路: + * 1. 归并排序,取中位数,时间复杂度 O(m+n),空间复杂度 O(m+n) + * 2. 找到两个数组的中位数的位置,时间复杂度 O(m+n),空间复杂度 O(1) + * 3. 二分法找到两个数组的中位数的位置,时间复杂度 O(log(m+n)),空间复杂度 O(1) + * 4. 中位数的统计学意义,将两个数组拆分,时间复杂度 O(log(min(m+n))),空间复杂度 O(1) + */ impl Solution { pub fn find_median_sorted_arrays(nums1: Vec, nums2: Vec) -> f64 { - 1.0 + let length_1 = nums1.len(); + let length_2 = nums2.len(); + let total_length = length_1 + length_2; + if (total_length % 2 == 1) { + let medium = total_length / 2; + Solution::find_median_sorted_arrays_by_binary_search(&nums1, &nums2, medium + 1) as f64 + } else { + let medium = total_length / 2; + let left = medium - 1; + let right = medium; + ((Solution::find_median_sorted_arrays_by_binary_search(&nums1, &nums2, left + 1) + + Solution::find_median_sorted_arrays_by_binary_search(&nums1, &nums2, right + 1)) + as f64) + / 2.0 + } } -} -// submission codes end + fn find_median_sorted_arrays_by_binary_search(nums1: &[i32], nums2: &[i32], k: usize) -> i32 { + let length1 = nums1.len(); + let length2 = nums2.len(); + let mut index1 = 0; + let mut index2 = 0; + let mut k = k; + let mut new_index1 = 0; + let mut new_index2 = 0; + loop { + if (index1 == nums1.len()) { + return nums2[index2 + k - 1]; + } + if (index2 == nums2.len()) { + return nums1[index1 + k - 1]; + } + if (k == 1) { + return cmp::min(nums1[index1], nums2[index2]); + } + let half = k / 2; + new_index1 = cmp::min(index1 + half, length1) - 1; + new_index2 = cmp::min(index2 + half, length2) - 1; + if (nums1[new_index1] <= nums2[new_index2]) { + k -= new_index1 - index1 + 1; + index1 = new_index1 + 1; + } else { + k -= new_index2 - index2 + 1; + index2 = new_index2 + 1; + } + } + } +} #[cfg(test)] mod tests { use super::*; - // TODO: implementation #[test] - #[ignore] - fn test_4() { + fn test_004() { assert_eq!( Solution::find_median_sorted_arrays(vec![1, 3], vec![2]), 2.0 ); + assert_eq!( Solution::find_median_sorted_arrays(vec![1, 2], vec![3, 4]), 2.5 - ); + ) } } diff --git a/src/solution/s0005_longest_palindromic_substring.rs b/src/solution/s0005_longest_palindromic_substring.rs deleted file mode 100644 index 675e1951..00000000 --- a/src/solution/s0005_longest_palindromic_substring.rs +++ /dev/null @@ -1,82 +0,0 @@ -/** - * [5] Longest Palindromic Substring - * - * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. - * - * Example 1: - * - * - * Input: "babad" - * Output: "bab" - * Note: "aba" is also a valid answer. - * - * - * Example 2: - * - * - * Input: "cbbd" - * Output: "bb" - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-palindromic-substring/ -// discuss: https://leetcode.com/problems/longest-palindromic-substring/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn longest_palindrome(s: String) -> String { - let seq: Vec = s.chars().collect(); - let len = seq.len(); - if len < 1 { - return s; - } - let (mut idx, mut curr_len, mut curr_start, mut curr_end) = (0, 0, 0, 0); - while idx < len { - let (mut i, mut j) = (idx, idx); - let ch = seq[idx]; - // handle same char - while i > 0 && seq[i - 1] == ch { - i -= 1 - } - while j < len - 1 && seq[j + 1] == ch { - j += 1 - } - idx = j + 1; - while i > 0 && j < len - 1 && seq[i - 1] == seq[j + 1] { - i -= 1; - j += 1; - } - let max_len = j - i + 1; - if max_len > curr_len { - curr_len = max_len; - curr_start = i; - curr_end = j; - } - if max_len >= len - 1 { - break; - } - } - - s[curr_start..curr_end + 1].to_owned() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_5() { - assert_eq!(Solution::longest_palindrome("aaaaa".to_owned()), "aaaaa"); - assert_eq!(Solution::longest_palindrome("babab".to_owned()), "babab"); - assert_eq!(Solution::longest_palindrome("babcd".to_owned()), "bab"); - assert_eq!(Solution::longest_palindrome("cbbd".to_owned()), "bb"); - assert_eq!(Solution::longest_palindrome("bb".to_owned()), "bb"); - assert_eq!(Solution::longest_palindrome("".to_owned()), ""); - } -} diff --git a/src/solution/s0006_zigzag_conversion.rs b/src/solution/s0006_zigzag_conversion.rs index 51ed13a7..894a1e40 100644 --- a/src/solution/s0006_zigzag_conversion.rs +++ b/src/solution/s0006_zigzag_conversion.rs @@ -1,95 +1,88 @@ -/** - * [6] ZigZag Conversion - * - * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) - * - * - * P A H N - * A P L S I I G - * Y I R - * - * - * And then read line by line: "PAHNAPLSIIGYIR" - * - * Write the code that will take a string and make this conversion given a number of rows: - * - * - * string convert(string s, int numRows); - * - * Example 1: - * - * - * Input: s = "PAYPALISHIRING", numRows = 3 - * Output: "PAHNAPLSIIGYIR" - * - * - * Example 2: - * - * - * Input: s = "PAYPALISHIRING", numRows = 4 - * Output: "PINALSIGYAHRPI" - * Explanation: - * - * P I N - * A L S I G - * Y A H R - * P I - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/zigzag-conversion/ -// discuss: https://leetcode.com/problems/zigzag-conversion/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn convert(s: String, num_rows: i32) -> String { - if num_rows < 2 { - return s; - } - let seq: Vec = s.chars().collect(); - let len = seq.len(); - let unit: usize = (2 * num_rows - 2) as usize; - let mut sb = String::with_capacity(s.capacity()); - for row in 0..num_rows { - let mut i = row as usize; - let step1 = 2 * (num_rows - 1 - row) as usize; - let step2 = (unit - step1) as usize; - let mut trigger = false; - while i < len { - sb.push(seq[i]); - if step1 == 0 { - i += step2 - } else if step2 == 0 { - i += step1 - } else { - i += if trigger { step2 } else { step1 }; - trigger = !trigger; - } - } - } - sb - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_6() { - assert_eq!( - Solution::convert("PAYPALISHIRING".to_string(), 4), - "PINALSIGYAHRPI" - ); - assert_eq!( - Solution::convert("PAYPALISHIRING".to_string(), 3), - "PAHNAPLSIIGYIR" - ); - assert_eq!(Solution::convert("A".to_string(), 1), "A"); - assert_eq!(Solution::convert("AY".to_string(), 2), "AY"); - } -} +use std::num; + +/** +* [0006] zigzag_conversion +* https://leetcode.cn/problems/zigzag-conversion/ +* +* 将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。 + +比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下: + +P A H N +A P L S I I G +Y I R +之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。 + +请你实现这个将字符串进行指定行数变换的函数: + +string convert(string s, int numRows); + + +示例 1: + +输入:s = "PAYPALISHIRING", numRows = 3 +输出:"PAHNAPLSIIGYIR" +示例 2: +输入:s = "PAYPALISHIRING", numRows = 4 +输出:"PINALSIGYAHRPI" +解释: +P I N +A L S I G +Y A H R +P I +示例 3: + +输入:s = "A", numRows = 1 +输出:"A" + + +提示: + +1 <= s.length <= 1000 +s 由英文字母(小写和大写)、',' 和 '.' 组成 +1 <= numRows <= 1000 +*/ + +pub struct Solution {} + +impl Solution { + pub fn convert(s: String, num_rows: i32) -> String { + let num_rows = num_rows as usize; + let total_count = s.len(); + if num_rows == 1 || num_rows >= total_count { + return s; + } + let count_pre_t = num_rows * 2 - 2; // 每个周期的字母数量 + let num_cols = (total_count + count_pre_t - 1) / count_pre_t * (num_rows - 1); + let mut x = 0; + let mut y = 0; + let mut matrix = vec![Vec::new(); num_rows]; + for (i, b) in s.bytes().enumerate() { + matrix[x].push(b); + if i % count_pre_t < num_rows - 1 { + x += 1 + } else { + x = (x + num_rows - 1) % num_rows; + } + } + std::str::from_utf8(&matrix.concat()).unwrap().to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_0006() { + assert_eq!( + Solution::convert(String::from("PAYPALISHIRING"), 3), + String::from("PAHNAPLSIIGYIR") + ); + + assert_eq!( + Solution::convert(String::from("PAYPALISHIRING"), 4), + String::from("PINALSIGYAHRPI") + ); + } +} diff --git a/src/solution/s0007_reverse_integer.rs b/src/solution/s0007_reverse_integer.rs deleted file mode 100644 index ad89eebd..00000000 --- a/src/solution/s0007_reverse_integer.rs +++ /dev/null @@ -1,73 +0,0 @@ -/** - * [7] Reverse Integer - * - * Given a 32-bit signed integer, reverse digits of an integer. - * - * Example 1: - * - * - * Input: 123 - * Output: 321 - * - * - * Example 2: - * - * - * Input: -123 - * Output: -321 - * - * - * Example 3: - * - * - * Input: 120 - * Output: 21 - * - * - * Note:
- * Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31 - 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/reverse-integer/ -// discuss: https://leetcode.com/problems/reverse-integer/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -impl Solution { - pub fn reverse(x: i32) -> i32 { - let mut input: i64 = x as i64; - let mut result: i64 = 0; - let mut digit: i64 = 0; - let base: i64 = 2; - let upper_bound: i64 = base.pow(31) - 1; - let lower_bound: i64 = -base.pow(31); - while input != 0 { - digit = input % 10; - result = result * 10 + digit; - input = input / 10; - } - if result > upper_bound || result < lower_bound { - return 0; - } - result as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_7() { - assert_eq!(Solution::reverse(123), 321); - assert_eq!(Solution::reverse(-123), -321); - assert_eq!(Solution::reverse(0), 0); - assert_eq!(Solution::reverse(-123000), -321); - let base: i64 = 2; - assert_eq!(Solution::reverse((base.pow(31) - 1) as i32), 0); - assert_eq!(Solution::reverse((-base.pow(31)) as i32), 0); - } -} diff --git a/src/solution/s0008_string_to_integer_atoi.rs b/src/solution/s0008_string_to_integer_atoi.rs index 9c86e17b..0b779992 100644 --- a/src/solution/s0008_string_to_integer_atoi.rs +++ b/src/solution/s0008_string_to_integer_atoi.rs @@ -1,131 +1,89 @@ -/** - * [8] String to Integer (atoi) - * - * Implement atoi which converts a string to an integer. - * - * The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. - * - * The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. - * - * If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. - * - * If no valid conversion could be performed, a zero value is returned. - * - * Note: - * - *
    - *
  • Only the space character ' ' is considered as whitespace character.
  • - *
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31 - 1]. If the numerical value is out of the range of representable values, INT_MAX (2^31 - 1) or INT_MIN (-2^31) is returned.
  • - *
- * - * Example 1: - * - * - * Input: "42" - * Output: 42 - * - * - * Example 2: - * - * - * Input: " -42" - * Output: -42 - * Explanation: The first non-whitespace character is '-', which is the minus sign. - * Then take as many numerical digits as possible, which gets 42. - * - * - * Example 3: - * - * - * Input: "4193 with words" - * Output: 4193 - * Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. - * - * - * Example 4: - * - * - * Input: "words and 987" - * Output: 0 - * Explanation: The first non-whitespace character is 'w', which is not a numerical - * digit or a +/- sign. Therefore no valid conversion could be performed. - * - * Example 5: - * - * - * Input: "-91283472332" - * Output: -2147483648 - * Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. - * Thefore INT_MIN (-2^31) is returned. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/string-to-integer-atoi/ -// discuss: https://leetcode.com/problems/string-to-integer-atoi/discuss/?currentPage=1&orderBy=most_votes&query= +use std::collections::HashMap; -// submission codes start here - -impl Solution { - pub fn my_atoi(input: String) -> i32 { - let (i32_min, i32_max) = (-2_i64.pow(31), 2_i64.pow(31) - 1); - let mut result: i64 = 0; - let mut minus = false; - // simple state machine - let mut num_matched = false; - for ch in input.chars().into_iter() { - if !num_matched { - match ch { - ' ' => {} - '0'..='9' => { - num_matched = true; - result = result * 10 + ch.to_digit(10).unwrap() as i64; - } - '-' => { - num_matched = true; - minus = true; - } - '+' => { - num_matched = true; - } - _ => return 0, - } - } else { - match ch { - '0'..='9' => { - result = result * 10 + ch.to_digit(10).unwrap() as i64; - if result > i32_max { - break; - } - } - _ => break, - } - } - } - result = if minus { -result } else { result }; - if result > i32_max { - return i32_max as i32; - } - if result < i32_min { - return i32_min as i32; - } - return result as i32; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_8() { - assert_eq!(Solution::my_atoi("aa".to_string()), 0); - assert_eq!(Solution::my_atoi("-91283472332".to_string()), -2147483648); - assert_eq!(Solution::my_atoi("words and 987".to_string()), 0); - assert_eq!(Solution::my_atoi("4193 with words".to_string()), 4193); - assert_eq!(Solution::my_atoi("42".to_string()), 42); - assert_eq!(Solution::my_atoi("004193333".to_string()), 4193333); - } -} +/** + * [0008] string to &integer atoi + * https://leetcode.cn/problems/string-to-integer-atoi/ + */ + +pub struct Automaton { + state: String, + states: HashMap<&'static str, [&'static str; 4]>, + pub ans: i64, + pub sign: i8, +} + +impl Automaton { + pub fn new() -> Automaton { + let automaton_states = HashMap::from([ + ("start", ["start", "signed", "in_number", "end"]), + ("signed", ["end", "end", "in_number", "end"]), + ("in_number", ["end", "end", "in_number", "end"]), + ("end", ["end", "end", "end", "end"]), + ]); + Automaton { + state: String::from("start"), + states: automaton_states, + ans: 0, + sign: 1, + } + } + + pub fn get_state(&self, c: char) -> usize { + if c.is_whitespace() { + return 0; + } + if c.eq(&'-') || c.eq(&'+') { + return 1; + } + if c.is_digit(10) { + return 2; + } + 3 + } + + pub fn get(&mut self, c: char) { + let state = self.get_state(c); + let states = self.states.get(&self.state[..]).unwrap(); + self.state = states[state].to_string(); + if self.state.eq("in_number") { + self.ans = self.ans * 10 + c.to_digit(10).unwrap() as i64; + self.ans = if self.sign == 1 { + self.ans.min(i32::MAX as i64) + } else { + self.ans.min(-(i32::MIN as i64)) + } + } else if self.state.eq("signed") { + self.sign = if c.eq(&'+') { 1 } else { -1 } + } + } +} + +pub struct Solution {} + +impl Solution { + pub fn my_atoi(s: String) -> i32 { + let mut auto_man = Automaton::new(); + for c in s.chars() { + auto_man.get(c); + } + return (auto_man.ans * auto_man.sign as i64) as i32; + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn test_0008() { + assert_eq!(Solution::my_atoi("".to_string()), 0); + assert_eq!(Solution::my_atoi(" ".to_string()), 0); + assert_eq!(Solution::my_atoi(" -".to_string()), 0); + assert_eq!(Solution::my_atoi(" -a".to_string()), 0); + assert_eq!(Solution::my_atoi("21474836460".to_string()), 2147483647); + assert_eq!(Solution::my_atoi(" -2147483648".to_string()), -2147483648); + assert_eq!(Solution::my_atoi(" +2147483647".to_string()), 2147483647); + assert_eq!(Solution::my_atoi("42".to_string()), 42); + assert_eq!(Solution::my_atoi("-42".to_string()), -42); + assert_eq!(Solution::my_atoi("4193 with words".to_string()), 4193); + } +} diff --git a/src/solution/s0009_palindrome_number.rs b/src/solution/s0009_palindrome_number.rs deleted file mode 100644 index 255eeed1..00000000 --- a/src/solution/s0009_palindrome_number.rs +++ /dev/null @@ -1,89 +0,0 @@ -/** - * [9] Palindrome Number - * - * Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. - * - * Example 1: - * - * - * Input: 121 - * Output: true - * - * - * Example 2: - * - * - * Input: -121 - * Output: false - * Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. - * - * - * Example 3: - * - * - * Input: 10 - * Output: false - * Explanation: Reads 01 from right to left. Therefore it is not a palindrome. - * - * - * Follow up: - * - * Coud you solve it without converting the integer to a string? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/palindrome-number/ -// discuss: https://leetcode.com/problems/palindrome-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: not optimal, we only have to revert half of the string -impl Solution { - pub fn is_palindrome(x: i32) -> bool { - if x < 0 { - return false; - } - let mut digits: Vec = Vec::new(); - let mut input = x; - while input != 0 { - digits.push(input % 10); - input = input / 10; - } - let len = digits.len(); - // handle one digit - if len < 2 { - return true; - } - // handle end with 0 - if digits[0] == 0 { - return false; - } - let mut i = 0; - while i < len / 2 { - if digits[i] != digits[len - 1 - i] { - return false; - } - i += 1; - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_9() { - assert_eq!(Solution::is_palindrome(-32), false); - assert_eq!(Solution::is_palindrome(10), false); - assert_eq!(Solution::is_palindrome(0), true); - assert_eq!(Solution::is_palindrome(9), true); - assert_eq!(Solution::is_palindrome(121), true); - assert_eq!(Solution::is_palindrome(2222), true); - assert_eq!(Solution::is_palindrome(11222211), true); - } -} diff --git a/src/solution/s0010_regular_expression_matching.rs b/src/solution/s0010_regular_expression_matching.rs deleted file mode 100644 index 13e15cb7..00000000 --- a/src/solution/s0010_regular_expression_matching.rs +++ /dev/null @@ -1,92 +0,0 @@ -/** - * [10] Regular Expression Matching - * - * Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. - * - * - * '.' Matches any single character. - * '*' Matches zero or more of the preceding element. - * - * - * The matching should cover the entire input string (not partial). - * - * Note: - * - * - * s could be empty and contains only lowercase letters a-z. - * p could be empty and contains only lowercase letters a-z, and characters like . or *. - * - * - * Example 1: - * - * - * Input: - * s = "aa" - * p = "a" - * Output: false - * Explanation: "a" does not match the entire string "aa". - * - * - * Example 2: - * - * - * Input: - * s = "aa" - * p = "a*" - * Output: true - * Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". - * - * - * Example 3: - * - * - * Input: - * s = "ab" - * p = ".*" - * Output: true - * Explanation: ".*" means "zero or more (*) of any character (.)". - * - * - * Example 4: - * - * - * Input: - * s = "aab" - * p = "c*a*b" - * Output: true - * Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab". - * - * - * Example 5: - * - * - * Input: - * s = "mississippi" - * p = "mis*is*p*." - * Output: false - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/regular-expression-matching/ -// discuss: https://leetcode.com/problems/regular-expression-matching/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: NFA -impl Solution { - pub fn is_match(s: String, p: String) -> bool { - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_10() {} -} diff --git a/src/solution/s0011_container_with_most_water.rs b/src/solution/s0011_container_with_most_water.rs index ae818bac..f0f0c2bc 100644 --- a/src/solution/s0011_container_with_most_water.rs +++ b/src/solution/s0011_container_with_most_water.rs @@ -1,81 +1,65 @@ /** - * [11] Container With Most Water + * [0011] container with most water + * https://leetcode.cn/problems/container-with-most-water/ * - * Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. + * 给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。 * - * Note: You may not slant the container and n is at least 2. + * 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 * - * + * 返回容器可以储存的最大水量。 * - * + * 说明:你不能倾斜容器。 * - * The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. + * 示例 1: * - * + * 输入:[1,8,6,2,5,4,8,3,7] + * 输出:49 + * 解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。 + * 示例 2: * - * Example: + * 输入:height = [1,1] + * 输出:1 * * - * Input: [1,8,6,2,5,4,8,3,7] - * Output: 49 + * 提示: * + * n == height.length + * 2 <= n <= 105 + * 0 <= height[i] <= 104 */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/container-with-most-water/ -// discuss: https://leetcode.com/problems/container-with-most-water/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -// Brute force: O(N^2) +pub struct Solution {} -// Two Pointer: a[0] -> <- a[n-1] impl Solution { pub fn max_area(height: Vec) -> i32 { - let (mut start, mut end) = (0_usize, (height.len() - 1)); - let mut max: i32 = (end - start) as i32 * Solution::min(height[start], height[end]); - let mut curr_area: i32 = 0; - while end - start > 1 { - // move the lower one - if height[start] < height[end] { - start += 1; - if height[start] < height[start - 1] { - continue; - } - } else { - end -= 1; - if height[end] < height[end + 1] { - continue; - } + let mut i = 0; + let mut j = height.len() - 1; + let mut max_area = 0; + while (i != j) { + let left = height[i]; + let right = height[j]; + let area = (j - i) as i32 * (left.min(right)); + if (area > max_area) { + max_area = area; } - curr_area = (end - start) as i32 * Solution::min(height[start], height[end]); - if curr_area > max { - max = curr_area + if (left < right) { + i += 1; + } else { + j -= 1; } } - max - } - - #[inline(always)] - fn min(i: i32, j: i32) -> i32 { - if i > j { - j - } else { - i - } + max_area } } -// submission codes end - #[cfg(test)] mod tests { use super::*; #[test] - fn test_11() { + fn test0011() { assert_eq!(Solution::max_area(vec![1, 8, 6, 2, 5, 4, 8, 3, 7]), 49); - assert_eq!(Solution::max_area(vec![6, 9]), 6); - assert_eq!(Solution::max_area(vec![1, 1, 2, 1, 1, 1]), 5); + + assert_eq!(Solution::max_area(vec![1, 1]), 1); } } diff --git a/src/solution/s0012_integer_to_roman.rs b/src/solution/s0012_integer_to_roman.rs index b32592c7..286d4f13 100644 --- a/src/solution/s0012_integer_to_roman.rs +++ b/src/solution/s0012_integer_to_roman.rs @@ -1,114 +1,75 @@ -/** - * [12] Integer to Roman - * - * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. - * - * - * Symbol Value - * I 1 - * V 5 - * X 10 - * L 50 - * C 100 - * D 500 - * M 1000 - * - * For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. - * - * Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: - * - * - * I can be placed before V (5) and X (10) to make 4 and 9. - * X can be placed before L (50) and C (100) to make 40 and 90. - * C can be placed before D (500) and M (1000) to make 400 and 900. - * - * - * Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. - * - * Example 1: - * - * - * Input: 3 - * Output: "III" - * - * Example 2: - * - * - * Input: 4 - * Output: "IV" - * - * Example 3: - * - * - * Input: 9 - * Output: "IX" - * - * Example 4: - * - * - * Input: 58 - * Output: "LVIII" - * Explanation: L = 50, V = 5, III = 3. - * - * - * Example 5: - * - * - * Input: 1994 - * Output: "MCMXCIV" - * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/integer-to-roman/ -// discuss: https://leetcode.com/problems/integer-to-roman/discuss/?currentPage=1&orderBy=most_votes&query= +/** + * [0012] integer to roman + * https://leetcode.cn/problems/integer-to-roman/ + */ -// submission codes start here - -impl Solution { - pub fn int_to_roman(num: i32) -> String { - let table: Vec<(i32, &'static str)> = vec![ - (1000, "M"), - (900, "CM"), - (500, "D"), - (400, "CD"), - (100, "C"), - (90, "XC"), - (50, "L"), - (40, "XL"), - (10, "X"), - (9, "IX"), - (5, "V"), - (4, "IV"), - (1, "I"), - ]; - - let mut num = num; - let mut sb = String::new(); - for p in table.iter() { - if num >= p.0 { - for _ in 0..(num / p.0) { - sb.push_str(p.1); - } - num = num % p.0 - } - } - sb - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_12() { - assert_eq!(Solution::int_to_roman(3), "III"); - assert_eq!(Solution::int_to_roman(4), "IV"); - assert_eq!(Solution::int_to_roman(9), "IX"); - assert_eq!(Solution::int_to_roman(1994), "MCMXCIV"); - } -} +pub struct Solution {} + +impl Solution { + pub fn int_to_roman_my(num: i32) -> String { + let symbols: Vec> = vec![ + vec![(1000, "M")], + vec![(900, "CM"), (500, "D"), (400, "CD"), (100, "C")], + vec![(90, "XC"), (50, "L"), (40, "XL"), (10, "X")], + vec![(9, "IX"), (5, "V"), (4, "IV"), (1, "I")], + ]; + let mut roman = Vec::new(); + let mut number = num; + // integer log10 是 nightly api,无法通过 leetcode 编译 + // let count = num.log10() + 1; + let count = num.to_string().len(); + for i in (4 - count)..4 { + let s = symbols.get(i).unwrap(); + for (radix, symbol) in s { + let count = number / radix; + number %= radix; + roman.push(symbol.repeat(count as usize)); + } + } + roman.join("") + } + + pub fn int_to_roman(num: i32) -> String { + let symbols: Vec<(i32, &str)> = vec![ + (1000, "M"), + (900, "CM"), + (500, "D"), + (400, "CD"), + (100, "C"), + (90, "XC"), + (50, "L"), + (40, "XL"), + (10, "X"), + (9, "IX"), + (5, "V"), + (4, "IV"), + (1, "I"), + ]; + let mut number = num; + let mut roman = String::new(); + for (radix, symbol) in symbols { + while number >= radix { + number -= radix; + roman += symbol; + } + if number == 0 { + break; + } + } + roman + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_0012() { + assert_eq!(Solution::int_to_roman(3), "III".to_string()); + assert_eq!(Solution::int_to_roman(4), "IV".to_string()); + assert_eq!(Solution::int_to_roman(9), "IX".to_string()); + assert_eq!(Solution::int_to_roman(58), "LVIII".to_string()); + assert_eq!(Solution::int_to_roman(3), "III".to_string()); + } +} diff --git a/src/solution/s0013_roman_to_integer.rs b/src/solution/s0013_roman_to_integer.rs deleted file mode 100644 index 4f3f0ae4..00000000 --- a/src/solution/s0013_roman_to_integer.rs +++ /dev/null @@ -1,115 +0,0 @@ -/** - * [13] Roman to Integer - * - * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. - * - * - * Symbol Value - * I 1 - * V 5 - * X 10 - * L 50 - * C 100 - * D 500 - * M 1000 - * - * For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. - * - * Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: - * - * - * I can be placed before V (5) and X (10) to make 4 and 9. - * X can be placed before L (50) and C (100) to make 40 and 90. - * C can be placed before D (500) and M (1000) to make 400 and 900. - * - * - * Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. - * - * Example 1: - * - * - * Input: "III" - * Output: 3 - * - * Example 2: - * - * - * Input: "IV" - * Output: 4 - * - * Example 3: - * - * - * Input: "IX" - * Output: 9 - * - * Example 4: - * - * - * Input: "LVIII" - * Output: 58 - * Explanation: L = 50, V= 5, III = 3. - * - * - * Example 5: - * - * - * Input: "MCMXCIV" - * Output: 1994 - * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/roman-to-integer/ -// discuss: https://leetcode.com/problems/roman-to-integer/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn roman_to_int(s: String) -> i32 { - let table: Vec<(i32, &'static str)> = vec![ - (1000, "M"), - (900, "CM"), - (500, "D"), - (400, "CD"), - (100, "C"), - (90, "XC"), - (50, "L"), - (40, "XL"), - (10, "X"), - (9, "IX"), - (5, "V"), - (4, "IV"), - (1, "I"), - ]; - let mut sum = 0; - let mut idx = 0; - for p in table.iter() { - while idx + p.1.len() <= s.len() && p.1 == &s[idx..idx + p.1.len()] { - idx += p.1.len(); - sum += p.0; - if idx >= s.len() { - return sum; - } - } - } - sum - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_13() { - assert_eq!(Solution::roman_to_int("III".to_string()), 3); - assert_eq!(Solution::roman_to_int("IV".to_string()), 4); - assert_eq!(Solution::roman_to_int("IX".to_string()), 9); - assert_eq!(Solution::roman_to_int("MCMXCIV".to_string()), 1994); - assert_eq!(Solution::roman_to_int("DCXXI".to_string()), 621); - } -} diff --git a/src/solution/s0014_longest_common_prefix.rs b/src/solution/s0014_longest_common_prefix.rs deleted file mode 100644 index 1c5fd985..00000000 --- a/src/solution/s0014_longest_common_prefix.rs +++ /dev/null @@ -1,90 +0,0 @@ -/** - * [14] Longest Common Prefix - * - * Write a function to find the longest common prefix string amongst an array of strings. - * - * If there is no common prefix, return an empty string "". - * - * Example 1: - * - * - * Input: ["flower","flow","flight"] - * Output: "fl" - * - * - * Example 2: - * - * - * Input: ["dog","racecar","car"] - * Output: "" - * Explanation: There is no common prefix among the input strings. - * - * - * Note: - * - * All given inputs are in lowercase letters a-z. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-common-prefix/ -// discuss: https://leetcode.com/problems/longest-common-prefix/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::str::Chars; -impl Solution { - pub fn longest_common_prefix(strs: Vec) -> String { - let mut prefix = String::new(); - let mut iters: Vec = strs.iter().map(|s| s.chars()).collect(); - let mut curr_char: Option = None; - if strs.len() < 1 { - return prefix; - } - loop { - curr_char.take().map(|ch| prefix.push(ch)); - for iter in iters.iter_mut() { - let mut ch = iter.next(); - if ch.is_none() { - return prefix; - } - match curr_char { - None => curr_char = ch.take(), - Some(curr) => { - if curr != ch.unwrap() { - return prefix; - } - } - } - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_14() { - assert_eq!( - Solution::longest_common_prefix(vec![ - "".to_string(), - "racecar".to_string(), - "car".to_string() - ]), - "" - ); - assert_eq!( - Solution::longest_common_prefix(vec![ - "flower".to_string(), - "flow".to_string(), - "flight".to_string() - ]), - "fl" - ); - assert_eq!(Solution::longest_common_prefix(vec![]), ""); - } -} diff --git a/src/solution/s0015_3sum.rs b/src/solution/s0015_3sum.rs deleted file mode 100644 index 9feb3cd0..00000000 --- a/src/solution/s0015_3sum.rs +++ /dev/null @@ -1,143 +0,0 @@ -/** - * [15] 3Sum - * - * Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. - * - * Note: - * - * The solution set must not contain duplicate triplets. - * - * Example: - * - * - * Given array nums = [-1, 0, 1, 2, -1, -4], - * - * A solution set is: - * [ - * [-1, 0, 1], - * [-1, -1, 2] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/3sum/ -// discuss: https://leetcode.com/problems/3sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn three_sum(nums: Vec) -> Vec> { - let len = nums.len(); - if len < 3 { - return vec![]; - } - let mut nums = nums; - nums.sort(); - let mut i = 0; - let mut result: Vec> = Vec::new(); - let mut previous = nums[0] - 1; - while i < len - 2 { - // skip same number - if nums[i] == previous { - i += 1; - continue; - } - previous = nums[i]; - let mut vec = Solution::two_sum(&nums[(i + 1)..len], 0 - nums[i]); - for t in vec.iter() { - result.push(vec![nums[i], t.0, t.1]); - } - i += 1; - } - result - } - - // 2 sum using 2 pointers: nums[0] -> <- nums[len-1] - #[inline(always)] - fn two_sum(nums: &[i32], sum: i32) -> Vec<(i32, i32)> { - let (mut i, mut j) = (0_usize, nums.len() - 1); - let mut result = Vec::new(); - while i < j { - if nums[i] + nums[j] < sum { - i += 1 - } else if nums[i] + nums[j] > sum { - j -= 1 - } else { - result.push((nums[i], nums[j])); - i = Solution::next_unique(nums, i, true); - j = Solution::next_unique(nums, j, false); - } - } - result - } - - // seek next un-repeat number - #[inline(always)] - fn next_unique(nums: &[i32], idx: usize, forward: bool) -> usize { - let curr = nums[idx]; - let mut i = idx; - while i > 0 && i < nums.len() && nums[i] == curr { - i = if forward { i + 1 } else { i - 1 } - } - i - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_15() { - assert_eq!( - Solution::three_sum(vec![-1, 0, 1, 2, -1, -4]), - vec![vec![-1, -1, 2], vec![-1, 0, 1]] - ); - assert_eq!( - Solution::three_sum(vec![ - -7, -4, -6, 6, 4, -6, -9, -10, -7, 5, 3, -1, -5, 8, -1, -2, -8, -1, 5, -3, -5, 4, - 2, -5, -4, 4, 7 - ]), - vec![ - vec![-10, 2, 8], - vec![-10, 3, 7], - vec![-10, 4, 6], - vec![-10, 5, 5], - vec![-9, 2, 7], - vec![-9, 3, 6], - vec![-9, 4, 5], - vec![-8, 2, 6], - vec![-8, 3, 5], - vec![-8, 4, 4], - vec![-7, -1, 8], - vec![-7, 2, 5], - vec![-7, 3, 4], - vec![-6, -2, 8], - vec![-6, -1, 7], - vec![-6, 2, 4], - vec![-5, -3, 8], - vec![-5, -2, 7], - vec![-5, -1, 6], - vec![-5, 2, 3], - vec![-4, -4, 8], - vec![-4, -3, 7], - vec![-4, -2, 6], - vec![-4, -1, 5], - vec![-3, -2, 5], - vec![-3, -1, 4], - vec![-2, -1, 3], - vec![-1, -1, 2] - ] - ); - assert_eq!( - Solution::three_sum(vec![2, 0, -2, -5, -5, -3, 2, -4]), - vec![vec![-4, 2, 2], vec![-2, 0, 2]] - ); - let empty_vec: Vec> = vec![]; - assert_eq!(Solution::three_sum(vec![]), empty_vec); - } -} diff --git a/src/solution/s0016_3sum_closest.rs b/src/solution/s0016_3sum_closest.rs deleted file mode 100644 index 01cf442d..00000000 --- a/src/solution/s0016_3sum_closest.rs +++ /dev/null @@ -1,76 +0,0 @@ -/** - * [16] 3Sum Closest - * - * Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. - * - * Example: - * - * - * Given array nums = [-1, 2, 1, -4], and target = 1. - * - * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/3sum-closest/ -// discuss: https://leetcode.com/problems/3sum-closest/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn three_sum_closest(nums: Vec, target: i32) -> i32 { - let mut nums = nums; - let mut min_distance: i32 = i32::max_value(); - nums.sort(); - let mut i = 0; - while i < nums.len() - 2 { - let sub_min = Solution::two_sum_closest(&nums[(i + 1)..nums.len()], target - nums[i]); - if sub_min.abs() < min_distance.abs() { - min_distance = sub_min; - if min_distance == 0 { - break; - } - } - i += 1; - } - target + min_distance - } - - pub fn two_sum_closest(nums: &[i32], target: i32) -> i32 { - let (mut i, mut j) = (0_usize, nums.len() - 1); - let mut local_min = i32::max_value(); - while i < j { - let sum = nums[i] + nums[j]; - if sum > target { - j -= 1; - } else if sum < target { - i += 1; - } else { - return 0; - } - if (sum - target).abs() < local_min.abs() { - local_min = sum - target - } - } - local_min - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_16() { - assert_eq!(Solution::three_sum_closest(vec![-1, 2, 1, -4], 1), 2); - assert_eq!(Solution::three_sum_closest(vec![1, 2, 3], 1), 6); - assert_eq!( - Solution::three_sum_closest(vec![1, 2, 4, 8, 16, 32, 64, 128], 82), - 82 - ); - } -} diff --git a/src/solution/s0017_letter_combinations_of_a_phone_number.rs b/src/solution/s0017_letter_combinations_of_a_phone_number.rs deleted file mode 100644 index 7d3245f4..00000000 --- a/src/solution/s0017_letter_combinations_of_a_phone_number.rs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * [17] Letter Combinations of a Phone Number - * - * Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. - * - * A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. - * - * - * - * Example: - * - * - * Input: "23" - * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. - * - * - * Note: - * - * Although the above answer is in lexicographical order, your answer could be in any order you want. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/letter-combinations-of-a-phone-number/ -// discuss: https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn letter_combinations(digits: String) -> Vec { - // '0' and '1' as placeholder to avoid index shifting - let table: Vec<(char, Vec)> = vec![ - ('0', vec![]), - ('1', vec![]), - ('2', vec!['a', 'b', 'c']), - ('3', vec!['d', 'e', 'f']), - ('4', vec!['g', 'h', 'i']), - ('5', vec!['j', 'k', 'l']), - ('6', vec!['m', 'n', 'o']), - ('7', vec!['p', 'q', 'r', 's']), - ('8', vec!['t', 'u', 'v']), - ('9', vec!['w', 'x', 'y', 'z']), - ]; - if digits.len() < 1 { - return vec![]; - } - let mut combs: Vec = vec![String::with_capacity(digits.len())]; - for ch in digits.chars().into_iter() { - let chs = &table[ch.to_digit(10).unwrap() as usize].1; - let mut added: Vec = Vec::with_capacity((chs.len() - 1) * combs.len()); - for comb in combs.iter_mut() { - for (i, &alphabetic) in chs.iter().enumerate() { - if i == chs.len() - 1 { - comb.push(alphabetic); - } else { - let mut new_comb = (*comb).clone(); - new_comb.push(alphabetic); - added.push(new_comb); - } - } - } - combs.append(&mut added); - } - combs - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_17() { - assert_eq!( - Solution::letter_combinations("23".to_string()), - ["cf", "af", "bf", "cd", "ce", "ad", "ae", "bd", "be"] - ); - } -} diff --git a/src/solution/s0018_4sum.rs b/src/solution/s0018_4sum.rs deleted file mode 100644 index d832aef1..00000000 --- a/src/solution/s0018_4sum.rs +++ /dev/null @@ -1,99 +0,0 @@ -/** - * [18] 4Sum - * - * Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. - * - * Note: - * - * The solution set must not contain duplicate quadruplets. - * - * Example: - * - * - * Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. - * - * A solution set is: - * [ - * [-1, 0, 0, 1], - * [-2, -1, 1, 2], - * [-2, 0, 0, 2] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/4sum/ -// discuss: https://leetcode.com/problems/4sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: change to faster N^3 solution... maybe -// this is a N^2 * logN solution, but slower than N^3 solution -// iterate all combinations and the sum of 2 elements, then use one-round hash -use std::collections::BTreeMap; -use std::collections::HashSet; -impl Solution { - pub fn four_sum(nums: Vec, target: i32) -> Vec> { - if nums.len() < 4 { - return vec![]; - } - let mut set: HashSet> = HashSet::new(); - let mut map: BTreeMap> = BTreeMap::new(); - // collect two-sums in asc order, store the index to avoid single number reusing - for i in 0..(nums.len() - 1) { - for j in (i + 1)..nums.len() { - map.entry(nums[i] + nums[j]) - .or_insert(Vec::new()) - .push((i, j)); - } - } - // find results - for (&sum, pairs) in map.iter() { - // avoid duplicates - if sum > target / 2 { - break; - } - match map.get(&(target - sum)) { - None => continue, - // 2-sum + 2-sum == target, then all the possible combination - // (without index conflicts) is our answer - Some(subs) => { - for pair in pairs.iter() { - for sub in subs.iter() { - if sub.0 == pair.0 - || sub.0 == pair.1 - || sub.1 == pair.0 - || sub.1 == pair.1 - { - continue; - } - let mut vec = - vec![nums[pair.0], nums[pair.1], nums[sub.0], nums[sub.1]]; - vec.sort(); - set.insert(vec); - } - } - } - } - } - set.into_iter().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - // TODO: build a macro for arbitrary match - #[test] - #[ignore] - fn test_18() { - assert_eq!( - Solution::four_sum(vec![1, 0, -1, 0, -2, 2], 0), - vec![vec![-1, 0, 0, 1], vec![-2, 0, 0, 2], vec![-2, -1, 1, 2]] - ); - } -} diff --git a/src/solution/s0019_remove_nth_node_from_end_of_list.rs b/src/solution/s0019_remove_nth_node_from_end_of_list.rs deleted file mode 100644 index c3f53a32..00000000 --- a/src/solution/s0019_remove_nth_node_from_end_of_list.rs +++ /dev/null @@ -1,71 +0,0 @@ -/** - * [19] Remove Nth Node From End of List - * - * Given a linked list, remove the n-th node from the end of list and return its head. - * - * Example: - * - * - * Given linked list: 1->2->3->4->5, and n = 2. - * - * After removing the second node from the end, the linked list becomes 1->2->3->5. - * - * - * Note: - * - * Given n will always be valid. - * - * Follow up: - * - * Could you do this in one pass? - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/remove-nth-node-from-end-of-list/ -// discuss: https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// one pass (two pointer runner pattern) cannot make borrow checker happy -// but two pass don't takes longer time -impl Solution { - pub fn remove_nth_from_end(head: Option>, n: i32) -> Option> { - let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head })); - let mut len = 0; - { - let mut p = dummy_head.as_ref(); - while p.unwrap().next.is_some() { - len += 1; - p = p.unwrap().next.as_ref(); - } - } - let idx = len - n; - { - let mut p = dummy_head.as_mut(); - for _ in 0..(idx) { - p = p.unwrap().next.as_mut(); - } - let next = p.as_mut().unwrap().next.as_mut().unwrap().next.take(); - p.as_mut().unwrap().next = next; - } - dummy_head.unwrap().next - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_19() { - assert_eq!( - Solution::remove_nth_from_end(to_list(vec![1, 2, 3, 4, 5]), 2), - to_list(vec![1, 2, 3, 5]) - ); - assert_eq!(Solution::remove_nth_from_end(to_list(vec![1]), 1), None); - } -} diff --git a/src/solution/s0020_valid_parentheses.rs b/src/solution/s0020_valid_parentheses.rs deleted file mode 100644 index 3c0940b9..00000000 --- a/src/solution/s0020_valid_parentheses.rs +++ /dev/null @@ -1,94 +0,0 @@ -/** - * [20] Valid Parentheses - * - * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. - * - * An input string is valid if: - * - *
    - * Open brackets must be closed by the same type of brackets. - * Open brackets must be closed in the correct order. - *
- * - * Note that an empty string is also considered valid. - * - * Example 1: - * - * - * Input: "()" - * Output: true - * - * - * Example 2: - * - * - * Input: "()[]{}" - * Output: true - * - * - * Example 3: - * - * - * Input: "(]" - * Output: false - * - * - * Example 4: - * - * - * Input: "([)]" - * Output: false - * - * - * Example 5: - * - * - * Input: "{[]}" - * Output: true - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/valid-parentheses/ -// discuss: https://leetcode.com/problems/valid-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_valid(s: String) -> bool { - let mut stack: Vec = Vec::new(); - for ch in s.chars().into_iter() { - match stack.last() { - None => {} - Some(&last) => { - if Solution::pair(last, ch) { - stack.pop(); - continue; - } - } - } - stack.push(ch); - } - stack.is_empty() - } - - #[inline(always)] - fn pair(open: char, close: char) -> bool { - (open == '{' && close == '}') - || (open == '(' && close == ')') - || (open == '[' && close == ']') - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_20() { - assert_eq!(Solution::is_valid("()[]{}".to_string()), true); - } -} diff --git a/src/solution/s0021_merge_two_sorted_lists.rs b/src/solution/s0021_merge_two_sorted_lists.rs deleted file mode 100644 index 54d7f256..00000000 --- a/src/solution/s0021_merge_two_sorted_lists.rs +++ /dev/null @@ -1,75 +0,0 @@ -/** - * [21] Merge Two Sorted Lists - * - * Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. - * - * Example: - * - * Input: 1->2->4, 1->3->4 - * Output: 1->1->2->3->4->4 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/merge-two-sorted-lists/ -// discuss: https://leetcode.com/problems/merge-two-sorted-lists/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// recursive will be much easier to understand -impl Solution { - pub fn merge_two_lists( - l1: Option>, - l2: Option>, - ) -> Option> { - let mut dummy_head = Some(Box::new(ListNode { val: 0, next: None })); - let mut head = &mut dummy_head; - let (mut l1, mut l2) = (l1, l2); - while l1.is_some() || l2.is_some() { - if l1.is_none() { - head.as_mut().unwrap().next = l2; - break; - } else if l2.is_none() { - head.as_mut().unwrap().next = l1; - break; - } - let next = if l1.as_ref().unwrap().val < l2.as_ref().unwrap().val { - let (origin, next) = Solution::take_head(l1); - l1 = origin; - next - } else { - let (origin, next) = Solution::take_head(l2); - l2 = origin; - next - }; - head.as_mut().unwrap().next = next; - head = &mut head.as_mut().unwrap().next; - } - dummy_head.unwrap().next - } - - #[inline(always)] - fn take_head(mut l: Option>) -> (Option>, Option>) { - let l_next = l.as_mut().unwrap().next.take(); - let next = l.take(); - l = l_next; - (l, next) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_21() { - assert_eq!( - Solution::merge_two_lists(to_list(vec![1, 2, 4]), to_list(vec![1, 3, 4])), - to_list(vec![1, 1, 2, 3, 4, 4]) - ); - } -} diff --git a/src/solution/s0022_generate_parentheses.rs b/src/solution/s0022_generate_parentheses.rs deleted file mode 100644 index 9e0e33df..00000000 --- a/src/solution/s0022_generate_parentheses.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [22] Generate Parentheses - * - * - * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. - * - * - * - * For example, given n = 3, a solution set is: - * - * - * [ - * "((()))", - * "(()())", - * "(())()", - * "()(())", - * "()()()" - * ] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/generate-parentheses/ -// discuss: https://leetcode.com/problems/generate-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// DFS -impl Solution { - pub fn generate_parenthesis(n: i32) -> Vec { - if n < 1 { - return vec![]; - } - let mut result = Vec::new(); - Solution::dfs(n, 0, 0, &mut result, String::new()); - result - } - - fn dfs(n: i32, left: i32, right: i32, result: &mut Vec, mut path: String) { - if left == n && right == n { - result.push(path); - return; - } - if left < n { - let mut new_path = path.clone(); - new_path.push('('); - Solution::dfs(n, left + 1, right, result, new_path); - } - if right < left { - // reuse path to avoid clone overhead - path.push(')'); - Solution::dfs(n, left, right + 1, result, path); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_22() { - assert_eq!(Solution::generate_parenthesis(1), vec!["()"]); - assert_eq!(Solution::generate_parenthesis(2), vec!["(())", "()()"]); - assert_eq!( - Solution::generate_parenthesis(3), - vec!["((()))", "(()())", "(())()", "()(())", "()()()"] - ); - } -} diff --git a/src/solution/s0023_merge_k_sorted_lists.rs b/src/solution/s0023_merge_k_sorted_lists.rs deleted file mode 100644 index eeaf3695..00000000 --- a/src/solution/s0023_merge_k_sorted_lists.rs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * [23] Merge k Sorted Lists - * - * Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. - * - * Example: - * - * - * Input: - * [ - * 1->4->5, - * 1->3->4, - * 2->6 - * ] - * Output: 1->1->2->3->4->4->5->6 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/merge-k-sorted-lists/ -// discuss: https://leetcode.com/problems/merge-k-sorted-lists/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -use std::cmp::Ordering; -use std::collections::BinaryHeap; - -// head value and the index -struct Node(i32, usize); - -// sort in reverse order of head value -impl Ord for Node { - fn cmp(&self, other: &Self) -> Ordering { - self.0.cmp(&other.0).reverse() - } -} -impl PartialEq for Node { - fn eq(&self, other: &Self) -> bool { - self.0.eq(&other.0) - } -} -impl Eq for Node {} -impl PartialOrd for Node { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.0.cmp(&other.0).reverse()) - } -} - -impl Solution { - pub fn merge_k_lists(lists: Vec>>) -> Option> { - let mut heap: BinaryHeap = BinaryHeap::new(); - for (idx, node) in lists.iter().enumerate() { - node.as_ref() - .and_then(|n| Some(heap.push(Node(n.val, idx)))); - } - Solution::next(lists, &mut heap) - } - - fn next( - mut lists: Vec>>, - heap: &mut BinaryHeap, - ) -> Option> { - heap.pop().map(|node| { - let next = lists[node.1].take().unwrap().next; - next.as_ref() - .and_then(|n| Some(heap.push(Node(n.val, node.1)))); - lists[node.1] = next; - Box::new(ListNode { - val: node.0, - next: Solution::next(lists, heap), - }) - }) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_23() { - assert_eq!( - Solution::merge_k_lists(vec![ - to_list(vec![1, 4, 5]), - to_list(vec![1, 3, 4]), - to_list(vec![2, 6]), - ]), - to_list(vec![1, 1, 2, 3, 4, 4, 5, 6]) - ); - assert_eq!(Solution::merge_k_lists(vec![]), None); - } -} diff --git a/src/solution/s0024_swap_nodes_in_pairs.rs b/src/solution/s0024_swap_nodes_in_pairs.rs deleted file mode 100644 index 4a6deb3e..00000000 --- a/src/solution/s0024_swap_nodes_in_pairs.rs +++ /dev/null @@ -1,73 +0,0 @@ -/** - * [24] Swap Nodes in Pairs - * - * Given a linked list, swap every two adjacent nodes and return its head. - * - * Example: - * - * - * Given 1->2->3->4, you should return the list as 2->1->4->3. - * - * Note: - * - * - * Your algorithm should use only constant extra space. - * You may not modify the values in the list's nodes, only nodes itself may be changed. - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/swap-nodes-in-pairs/ -// discuss: https://leetcode.com/problems/swap-nodes-in-pairs/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn swap_pairs(head: Option>) -> Option> { - let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head })); - let mut head = dummy_head.as_mut(); - loop { - let mut left = head.as_mut().unwrap().next.take(); - if left.is_none() { - break; - } - let mut right = left.as_mut().unwrap().next.take(); - // handle the un-paired one, e.g. [1, 2, 3] -> [2, 1, 3], 3 is un-paired - if right.is_none() { - head.as_mut().unwrap().next = left; - break; - } - let mut next = right.as_mut().unwrap().next.take(); - // BEFORE: head -> left -> right -> next - // AFTER: head -> right -> left -> next - left.as_mut().unwrap().next = next; - right.as_mut().unwrap().next = left; - head.as_mut().unwrap().next = right; - head = head.unwrap().next.as_mut().unwrap().next.as_mut(); - } - dummy_head.unwrap().next - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_24() { - assert_eq!( - Solution::swap_pairs(to_list(vec![1, 2, 3, 4])), - to_list(vec![2, 1, 4, 3]) - ); - assert_eq!(Solution::swap_pairs(to_list(vec![])), to_list(vec![])); - assert_eq!( - Solution::swap_pairs(to_list(vec![1, 2, 3])), - to_list(vec![2, 1, 3]) - ); - assert_eq!(Solution::swap_pairs(to_list(vec![1])), to_list(vec![1])); - } -} diff --git a/src/solution/s0025_reverse_nodes_in_k_group.rs b/src/solution/s0025_reverse_nodes_in_k_group.rs deleted file mode 100644 index 5d39cd1e..00000000 --- a/src/solution/s0025_reverse_nodes_in_k_group.rs +++ /dev/null @@ -1,106 +0,0 @@ -/** - * [25] Reverse Nodes in k-Group - * - * Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. - * - * k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. - * - * - * - * - * Example: - * - * Given this linked list: 1->2->3->4->5 - * - * For k = 2, you should return: 2->1->4->3->5 - * - * For k = 3, you should return: 3->2->1->4->5 - * - * Note: - * - * - * Only constant extra memory is allowed. - * You may not alter the values in the list's nodes, only nodes itself may be changed. - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/reverse-nodes-in-k-group/ -// discuss: https://leetcode.com/problems/reverse-nodes-in-k-group/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn reverse_k_group(head: Option>, k: i32) -> Option> { - let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head })); - let mut head = dummy_head.as_mut(); - 'outer: loop { - let mut start = head.as_mut().unwrap().next.take(); - if start.is_none() { - break 'outer; - } - let mut end = start.as_mut(); - for _ in 0..(k - 1) { - end = end.unwrap().next.as_mut(); - if end.is_none() { - head.as_mut().unwrap().next = start; - break 'outer; - } - } - let mut tail = end.as_mut().unwrap().next.take(); - // BEFORE: head -> start -> 123456... -> end -> tail - // AFTER: head -> end -> ...654321 -> start -> tail - let end = Solution::reverse(start, tail); - head.as_mut().unwrap().next = end; - for _ in 0..k { - head = head.unwrap().next.as_mut() - } - } - dummy_head.unwrap().next - } - - #[inline(always)] - fn reverse( - mut head: Option>, - tail: Option>, - ) -> Option> { - let mut prev = tail; - let mut current = head; - while let Some(mut current_node_inner) = current { - let mut next = current_node_inner.next.take(); - current_node_inner.next = prev.take(); - prev = Some(current_node_inner); - current = next; - } - prev - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_25() { - assert_eq!( - Solution::reverse_k_group(to_list(vec![1, 2, 3, 4, 5]), 2), - to_list(vec![2, 1, 4, 3, 5]) - ); - assert_eq!( - Solution::reverse_k_group(to_list(vec![1, 2, 3, 4, 5]), 3), - to_list(vec![3, 2, 1, 4, 5]) - ); - assert_eq!( - Solution::reverse_k_group(to_list(vec![1, 2, 3, 4, 5]), 5), - to_list(vec![5, 4, 3, 2, 1]) - ); - assert_eq!( - Solution::reverse_k_group(to_list(vec![1]), 1), - to_list(vec![1]) - ); - } -} diff --git a/src/solution/s0026_remove_duplicates_from_sorted_array.rs b/src/solution/s0026_remove_duplicates_from_sorted_array.rs deleted file mode 100644 index 286b7c54..00000000 --- a/src/solution/s0026_remove_duplicates_from_sorted_array.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [26] Remove Duplicates from Sorted Array - * - * Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. - * - * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. - * - * Example 1: - * - * - * Given nums = [1,1,2], - * - * Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. - * - * It doesn't matter what you leave beyond the returned length. - * - * Example 2: - * - * - * Given nums = [0,0,1,1,1,2,2,3,3,4], - * - * Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. - * - * It doesn't matter what values are set beyond the returned length. - * - * - * Clarification: - * - * Confused why the returned value is an integer but your answer is an array? - * - * Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. - * - * Internally you can think of this: - * - * - * // nums is passed in by reference. (i.e., without making a copy) - * int len = removeDuplicates(nums); - * - * // any modification to nums in your function would be known by the caller. - * // using the length returned by your function, it prints the first len elements. - * for (int i = 0; i < len; i++) { - * print(nums[i]); - * } - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/remove-duplicates-from-sorted-array/ -// discuss: https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn remove_duplicates(nums: &mut Vec) -> i32 { - let len = nums.len(); - if len <= 1 { - return len as i32; - } - let mut slow = 0usize; - for fast in 1..len { - if nums[slow] != nums[fast] { - slow += 1; - nums[slow] = nums[fast]; - } - } - nums.truncate(slow + 1); - (slow + 1) as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_26() { - assert_eq!(Solution::remove_duplicates(&mut vec![]), 0); - let mut vec1 = vec![1, 1, 1, 1, 3]; - assert_eq!(Solution::remove_duplicates(&mut vec1), 2); - assert_eq!(vec1, vec![1, 3]); - let mut vec2 = vec![1, 1, 2]; - assert_eq!(Solution::remove_duplicates(&mut vec2), 2); - assert_eq!(vec2, vec![1, 2]); - } -} diff --git a/src/solution/s0027_remove_element.rs b/src/solution/s0027_remove_element.rs deleted file mode 100644 index 7144d3e9..00000000 --- a/src/solution/s0027_remove_element.rs +++ /dev/null @@ -1,97 +0,0 @@ -/** - * [27] Remove Element - * - * Given an array nums and a value val, remove all instances of that value in-place and return the new length. - * - * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. - * - * The order of elements can be changed. It doesn't matter what you leave beyond the new length. - * - * Example 1: - * - * - * Given nums = [3,2,2,3], val = 3, - * - * Your function should return length = 2, with the first two elements of nums being 2. - * - * It doesn't matter what you leave beyond the returned length. - * - * - * Example 2: - * - * - * Given nums = [0,1,2,2,3,0,4,2], val = 2, - * - * Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. - * - * Note that the order of those five elements can be arbitrary. - * - * It doesn't matter what values are set beyond the returned length. - * - * Clarification: - * - * Confused why the returned value is an integer but your answer is an array? - * - * Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. - * - * Internally you can think of this: - * - * - * // nums is passed in by reference. (i.e., without making a copy) - * int len = removeElement(nums, val); - * - * // any modification to nums in your function would be known by the caller. - * // using the length returned by your function, it prints the first len elements. - * for (int i = 0; i < len; i++) { - * print(nums[i]); - * } - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/remove-element/ -// discuss: https://leetcode.com/problems/remove-element/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn remove_element(nums: &mut Vec, val: i32) -> i32 { - if nums.len() < 1 { - return 0; - } - let (mut start, mut end) = (0_usize, nums.len() - 1); - while start < end { - if nums[start] == val { - nums[start] = nums[end - 1]; - end -= 1; - } else { - start += 1; - } - } - end as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_27() { - let mut vec1 = vec![0, 1, 2, 2, 3, 0, 4, 2]; - assert_eq!(Solution::remove_element(&mut vec1, 2), 5); - assert_eq!(vec1[0..5], [0, 1, 4, 0, 3]); - assert_eq!(Solution::remove_element(&mut vec![], 2), 0); - assert_eq!( - Solution::remove_element(&mut vec![1, 2, 2, 2, 2, 2, 2], 2), - 1 - ); - assert_eq!( - Solution::remove_element(&mut vec![2, 2, 2, 2, 2, 2, 2], 2), - 0 - ); - assert_eq!(Solution::remove_element(&mut vec![1], 1), 0); - } -} diff --git a/src/solution/s0028_implement_strstr.rs b/src/solution/s0028_implement_strstr.rs deleted file mode 100644 index e0d944ee..00000000 --- a/src/solution/s0028_implement_strstr.rs +++ /dev/null @@ -1,55 +0,0 @@ -/** - * [28] Implement strStr() - * - * Implement strStr(). - * - * Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. - * - * Example 1: - * - * - * Input: haystack = "hello", needle = "ll" - * Output: 2 - * - * - * Example 2: - * - * - * Input: haystack = "aaaaa", needle = "bba" - * Output: -1 - * - * - * Clarification: - * - * What should we return when needle is an empty string? This is a great question to ask during an interview. - * - * For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/implement-strstr/ -// discuss: https://leetcode.com/problems/implement-strstr/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn str_str(haystack: String, needle: String) -> i32 { - if needle.is_empty() { - return 0; - } - haystack.find(&needle).map_or(-1_i32, |v| v as i32) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_28() { - assert_eq!(Solution::str_str("hello".to_string(), "ll".to_string()), 2) - } -} diff --git a/src/solution/s0029_divide_two_integers.rs b/src/solution/s0029_divide_two_integers.rs deleted file mode 100644 index e8f13435..00000000 --- a/src/solution/s0029_divide_two_integers.rs +++ /dev/null @@ -1,52 +0,0 @@ -/** - * [29] Divide Two Integers - * - * Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. - * - * Return the quotient after dividing dividend by divisor. - * - * The integer division should truncate toward zero. - * - * Example 1: - * - * - * Input: dividend = 10, divisor = 3 - * Output: 3 - * - * Example 2: - * - * - * Input: dividend = 7, divisor = -3 - * Output: -2 - * - * Note: - * - * - * Both dividend and divisor will be 32-bit signed integers. - * The divisor will never be 0. - * Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31 - 1]. For the purpose of this problem, assume that your function returns 2^31 - 1 when the division result overflows. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/divide-two-integers/ -// discuss: https://leetcode.com/problems/divide-two-integers/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn divide(dividend: i32, divisor: i32) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_29() {} -} diff --git a/src/solution/s0030_substring_with_concatenation_of_all_words.rs b/src/solution/s0030_substring_with_concatenation_of_all_words.rs deleted file mode 100644 index 002ae9a3..00000000 --- a/src/solution/s0030_substring_with_concatenation_of_all_words.rs +++ /dev/null @@ -1,175 +0,0 @@ -/** - * [30] Substring with Concatenation of All Words - * - * You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. - * - * Example 1: - * - * - * Input: - * s = "barfoothefoobarman", - * words = ["foo","bar"] - * Output: [0,9] - * Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively. - * The output order does not matter, returning [9,0] is fine too. - * - * - * Example 2: - * - * - * Input: - * s = "wordgoodgoodgoodbestword", - * words = ["word","good","best","word"] - * Output: [] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/substring-with-concatenation-of-all-words/ -// discuss: https://leetcode.com/problems/substring-with-concatenation-of-all-words/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -struct Term { - expect: i32, - count: i32, -} -impl Term { - fn new(expect: i32, count: i32) -> Self { - Term { expect, count } - } - fn inc_expect(&mut self) { - self.expect += 1; - } - fn inc(&mut self) { - self.count += 1; - } - fn dec(&mut self) { - self.count -= 1; - } - fn exhausted(&self) -> bool { - self.count > self.expect - } - fn reset(&mut self) { - self.count = 0; - } -} - -use std::collections::hash_map::Entry; -use std::collections::HashMap; - -impl Solution { - pub fn find_substring(s: String, words: Vec) -> Vec { - if words.len() < 1 { - return vec![]; - } - let word_len = words[0].len(); - if word_len < 1 { - return vec![]; - } - let substr_len = word_len * words.len(); - let mut map: HashMap<&str, Term> = HashMap::with_capacity(words.len()); - for word in words.iter() { - map.entry(word).or_insert(Term::new(0, 0)).inc_expect(); - } - let mut result: Vec = Vec::new(); - // we can split terms in N ways, where N = word_len - for shift in 0..word_len { - let mut i = shift; - let mut j = shift; - // we do a sliding window for each round - while j + word_len - 1 < s.len() { - match map.entry(&s[j..j + word_len]) { - Entry::Occupied(mut entry) => { - entry.get_mut().inc(); - // term exhausted, shrink the window to release - if entry.get().exhausted() { - while i < j { - let term = &s[i..i + word_len]; - map.entry(term).and_modify(|t| t.dec()); - i += word_len; - if term == &s[j..j + word_len] { - break; - } - } - j += word_len; - } else { - if j - i < (words.len() - 1) * word_len { - j += word_len; - } else { - // matched! - result.push(i as i32); - // move the whole window, release the dropped term - map.entry(&s[i..i + word_len]).and_modify(|t| t.dec()); - j += word_len; - i += word_len; - } - } - } - // bad term, move over and do a reset - Entry::Vacant(entry) => { - map.iter_mut().for_each(|(_, v)| v.reset()); - j += word_len; - i = j; - } - } - } - map.iter_mut().for_each(|(_, v)| v.reset()) - } - result - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_30() { - assert_eq!( - Solution::find_substring( - "barfoothefoobarman".to_string(), - vec!["foo".to_string(), "bar".to_string()] - ), - vec![0, 9] - ); - assert_eq!( - Solution::find_substring( - "wordgoodgoodgoodbestword".to_string(), - vec![ - "word".to_string(), - "good".to_string(), - "best".to_string(), - "word".to_string() - ] - ), - vec![] - ); - assert_eq!( - Solution::find_substring( - "wordgoodgoodgoodbestword".to_string(), - vec![ - "word".to_string(), - "good".to_string(), - "best".to_string(), - "good".to_string() - ] - ), - vec![8] - ); - assert_eq!( - Solution::find_substring( - "xxwordgoodgoodgoodbestword".to_string(), - vec![ - "word".to_string(), - "good".to_string(), - "best".to_string(), - "good".to_string() - ] - ), - vec![10] - ); - } -} diff --git a/src/solution/s0031_next_permutation.rs b/src/solution/s0031_next_permutation.rs deleted file mode 100644 index b448dfa1..00000000 --- a/src/solution/s0031_next_permutation.rs +++ /dev/null @@ -1,89 +0,0 @@ -/** - * [31] Next Permutation - * - * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. - * - * If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). - * - * The replacement must be in-place and use only constant extra memory. - * - * Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. - * - * 1,2,3 → 1,3,2
- * 3,2,1 → 1,2,3
- * 1,1,5 → 1,5,1 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/next-permutation/ -// discuss: https://leetcode.com/problems/next-permutation/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn next_permutation(nums: &mut Vec) { - let len = nums.len(); - let mut i = (len - 1) as i32; - let mut prev = -1; - // find the decrement digit from end - while i >= 0 { - if nums[i as usize] < prev { - break; - } - prev = nums[i as usize]; - i -= 1; - } - let mut j = len - 1; - // find the first digit larger than nums[i] - // we can do binary search here to make a slightly improvement - if i >= 0 { - while j > (i as usize) { - if nums[j] > nums[i as usize] { - nums.swap(i as usize, j); - break; - } - j -= 1; - } - } - let slice = &mut nums[((i + 1) as usize)..len]; - slice.reverse(); - } -} - -// submission codes end - -/* -// a clean solution (from leetcode submissions) -impl Solution { - pub fn next_permutation(a: &mut Vec) { - let n = a.len(); - - if let Some(i) = (1..n).rev().find(|&i| a[i - 1] < a[i]) { - let j = (i..n).rev().find(|&j| a[i - 1] < a[j]) - .unwrap(); - - a.swap(i - 1, j); - a[i..].reverse(); - } else { - a.reverse(); - } - } -} - */ - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_31() { - let mut vec1 = vec![1, 2, 3, 4, 5]; - Solution::next_permutation(&mut vec1); - assert_eq!(vec1, vec![1, 2, 3, 5, 4]); - - let mut vec2 = vec![5, 4, 3, 2, 1]; - Solution::next_permutation(&mut vec2); - assert_eq!(vec2, vec![1, 2, 3, 4, 5]); - } -} diff --git a/src/solution/s0032_longest_valid_parentheses.rs b/src/solution/s0032_longest_valid_parentheses.rs deleted file mode 100644 index d970de2b..00000000 --- a/src/solution/s0032_longest_valid_parentheses.rs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * [32] Longest Valid Parentheses - * - * Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. - * - * Example 1: - * - * - * Input: "(()" - * Output: 2 - * Explanation: The longest valid parentheses substring is "()" - * - * - * Example 2: - * - * - * Input: ")()())" - * Output: 4 - * Explanation: The longest valid parentheses substring is "()()" - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-valid-parentheses/ -// discuss: https://leetcode.com/problems/longest-valid-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// time: O(N) space: O(1) -impl Solution { - pub fn longest_valid_parentheses(s: String) -> i32 { - let mut seq: Vec = s.chars().collect(); - let forward_max = Solution::longest(&seq, '('); - seq.reverse(); - let backward_max = Solution::longest(&seq, ')'); - i32::max(forward_max, backward_max) - } - - fn longest(seq: &Vec, plus_char: char) -> i32 { - let mut stack = 0; - let mut max_len = 0; - let (mut i, mut j) = (0_usize, 0_usize); - while j < seq.len() { - if seq[j] == plus_char { - stack += 1; - } else { - // stack exhausted, shift over - if stack < 1 { - i = j + 1; - } else { - stack -= 1; - if stack == 0 { - max_len = i32::max(max_len, (j - i + 1) as i32); - } - } - } - j += 1; - } - max_len - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_32() { - assert_eq!(Solution::longest_valid_parentheses(")()())".to_string()), 4); - assert_eq!(Solution::longest_valid_parentheses(")(".to_string()), 0); - assert_eq!(Solution::longest_valid_parentheses("(()".to_string()), 2); - assert_eq!( - Solution::longest_valid_parentheses("(((((()()".to_string()), - 4 - ); - assert_eq!( - Solution::longest_valid_parentheses("((((((((()))".to_string()), - 6 - ); - assert_eq!(Solution::longest_valid_parentheses("()".to_string()), 2); - assert_eq!(Solution::longest_valid_parentheses("()(()".to_string()), 2); - assert_eq!( - Solution::longest_valid_parentheses(")()(((())))(".to_string()), - 10 - ); - assert_eq!( - Solution::longest_valid_parentheses("(()(((()".to_string()), - 2 - ); - assert_eq!(Solution::longest_valid_parentheses("".to_string()), 0); - } -} diff --git a/src/solution/s0033_search_in_rotated_sorted_array.rs b/src/solution/s0033_search_in_rotated_sorted_array.rs deleted file mode 100644 index ab5c13d3..00000000 --- a/src/solution/s0033_search_in_rotated_sorted_array.rs +++ /dev/null @@ -1,105 +0,0 @@ -/** - * [33] Search in Rotated Sorted Array - * - * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. - * - * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). - * - * You are given a target value to search. If found in the array return its index, otherwise return -1. - * - * You may assume no duplicate exists in the array. - * - * Your algorithm's runtime complexity must be in the order of O(log n). - * - * Example 1: - * - * - * Input: nums = [4,5,6,7,0,1,2], target = 0 - * Output: 4 - * - * - * Example 2: - * - * - * Input: nums = [4,5,6,7,0,1,2], target = 3 - * Output: -1 - * - */ -pub struct Solution {} - -/* - \ - 8 - 7 9 - 6 1 - 5 2 - 3 \ -Consider the given array as ring, each time we split the ring and judge which part is the target belong to, then it's ordinary binary search. -*/ - -// problem: https://leetcode.com/problems/search-in-rotated-sorted-array/ -// discuss: https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn search(nums: Vec, target: i32) -> i32 { - let mut size = nums.len(); - if size == 0 { - return -1; - } - let mut base = 0_usize; - while size > 1 { - let half = size / 2; - let mid = base + half; - if nums[mid] == target { - return mid as i32; - } - // we split the ring to [base..half] & [half+1..base-1] - // if target not in [base..half] ring, move base to select another ring - if !(((nums[base] < nums[mid]) && (target >= nums[base] && target <= nums[mid])) - || ((nums[base] > nums[mid]) && (target >= nums[base] || target <= nums[mid]))) - { - base = mid; - } - size -= half; - } - if nums[base] == target { - base as i32 - } else { - -1 - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_33() { - assert_eq!(Solution::search(vec![7, 8, 1, 2, 3, 4, 5, 6], 2), 3); - assert_eq!( - Solution::search( - vec![ - 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 0, 1, 2, 3, 4, 5, 6, 7, 8 - ], - 0 - ), - 9 - ); - assert_eq!( - Solution::search( - vec![ - 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 0, 1, 2, 3, 4, 5, 6, 7, 8 - ], - 1006 - ), - 2 - ); - assert_eq!(Solution::search(vec![4, 5, 6, 7, 0, 1, 2], 3), -1); - assert_eq!(Solution::search(vec![], 3), -1); - } -} diff --git a/src/solution/s0034_find_first_and_last_position_of_element_in_sorted_array.rs b/src/solution/s0034_find_first_and_last_position_of_element_in_sorted_array.rs deleted file mode 100644 index eba1c01c..00000000 --- a/src/solution/s0034_find_first_and_last_position_of_element_in_sorted_array.rs +++ /dev/null @@ -1,45 +0,0 @@ -/** - * [34] Find First and Last Position of Element in Sorted Array - * - * Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. - * - * Your algorithm's runtime complexity must be in the order of O(log n). - * - * If the target is not found in the array, return [-1, -1]. - * - * Example 1: - * - * - * Input: nums = [5,7,7,8,8,10], target = 8 - * Output: [3,4] - * - * Example 2: - * - * - * Input: nums = [5,7,7,8,8,10], target = 6 - * Output: [-1,-1] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ -// discuss: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO -impl Solution { - pub fn search_range(nums: Vec, target: i32) -> Vec { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_34() {} -} diff --git a/src/solution/s0035_search_insert_position.rs b/src/solution/s0035_search_insert_position.rs deleted file mode 100644 index 31c1c38b..00000000 --- a/src/solution/s0035_search_insert_position.rs +++ /dev/null @@ -1,59 +0,0 @@ -/** - * [35] Search Insert Position - * - * Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. - * - * You may assume no duplicates in the array. - * - * Example 1: - * - * - * Input: [1,3,5,6], 5 - * Output: 2 - * - * - * Example 2: - * - * - * Input: [1,3,5,6], 2 - * Output: 1 - * - * - * Example 3: - * - * - * Input: [1,3,5,6], 7 - * Output: 4 - * - * - * Example 4: - * - * - * Input: [1,3,5,6], 0 - * Output: 0 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/search-insert-position/ -// discuss: https://leetcode.com/problems/search-insert-position/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO -impl Solution { - pub fn search_insert(nums: Vec, target: i32) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_35() {} -} diff --git a/src/solution/s0036_valid_sudoku.rs b/src/solution/s0036_valid_sudoku.rs deleted file mode 100644 index 5a595774..00000000 --- a/src/solution/s0036_valid_sudoku.rs +++ /dev/null @@ -1,172 +0,0 @@ -/** - * [36] Valid Sudoku - * - * Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: - * - *
    - * Each row must contain the digits 1-9 without repetition. - * Each column must contain the digits 1-9 without repetition. - * Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition. - *
- * - *
- * A partially filled sudoku which is valid. - * - * The Sudoku board could be partially filled, where empty cells are filled with the character '.'. - * - * Example 1: - * - * - * Input: - * [ - * ["5","3",".",".","7",".",".",".","."], - * ["6",".",".","1","9","5",".",".","."], - * [".","9","8",".",".",".",".","6","."], - * ["8",".",".",".","6",".",".",".","3"], - * ["4",".",".","8",".","3",".",".","1"], - * ["7",".",".",".","2",".",".",".","6"], - * [".","6",".",".",".",".","2","8","."], - * [".",".",".","4","1","9",".",".","5"], - * [".",".",".",".","8",".",".","7","9"] - * ] - * Output: true - * - * - * Example 2: - * - * - * Input: - * [ - * ["8","3",".",".","7",".",".",".","."], - * ["6",".",".","1","9","5",".",".","."], - * [".","9","8",".",".",".",".","6","."], - * ["8",".",".",".","6",".",".",".","3"], - * ["4",".",".","8",".","3",".",".","1"], - * ["7",".",".",".","2",".",".",".","6"], - * [".","6",".",".",".",".","2","8","."], - * [".",".",".","4","1","9",".",".","5"], - * [".",".",".",".","8",".",".","7","9"] - * ] - * Output: false - * Explanation: Same as Example 1, except with the 5 in the top left corner being - * modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. - * - * - * Note: - * - * - * A Sudoku board (partially filled) could be valid but is not necessarily solvable. - * Only the filled cells need to be validated according to the mentioned rules. - * The given board contain only digits 1-9 and the character '.'. - * The given board size is always 9x9. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/valid-sudoku/ -// discuss: https://leetcode.com/problems/valid-sudoku/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// just brute force -impl Solution { - pub fn is_valid_sudoku(board: Vec>) -> bool { - let mut table = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - for row in board.iter() { - for z in 1..10 { - table[z] = 0; - } - for ch in row { - match ch.to_digit(10) { - None => continue, - Some(idx) => { - if table[idx as usize] > 0 { - return false; - } else { - table[idx as usize] = 1 - } - } - } - } - } - for i in 0..9 { - for z in 1..10 { - table[z] = 0; - } - for row in board.iter() { - match row[i].to_digit(10) { - None => continue, - Some(idx) => { - if table[idx as usize] > 0 { - return false; - } else { - table[idx as usize] = 1 - } - } - } - } - } - for i in 0..3 { - for j in 0..3 { - for z in 1..10 { - table[z] = 0; - } - for row in 3 * i..3 * (i + 1) { - for column in 3 * j..3 * (j + 1) { - match board[row][column].to_digit(10) { - None => continue, - Some(idx) => { - if table[idx as usize] > 0 { - return false; - } else { - table[idx as usize] = 1 - } - } - } - } - } - } - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_36() { - assert_eq!( - Solution::is_valid_sudoku(vec![ - vec!['8', '3', '.', '.', '7', '.', '.', '.', '.'], - vec!['6', '.', '.', '1', '9', '5', '.', '.', '.'], - vec!['.', '9', '8', '.', '.', '.', '.', '6', '.'], - vec!['8', '.', '.', '.', '6', '.', '.', '.', '3'], - vec!['4', '.', '.', '8', '.', '3', '.', '.', '1'], - vec!['7', '.', '.', '.', '2', '.', '.', '.', '6'], - vec!['.', '6', '.', '.', '.', '.', '2', '8', '.'], - vec!['.', '.', '.', '4', '1', '9', '.', '.', '5'], - vec!['.', '.', '.', '.', '8', '.', '.', '7', '9'], - ]), - false - ); - assert_eq!( - Solution::is_valid_sudoku(vec![ - vec!['5', '3', '.', '.', '7', '.', '.', '.', '.'], - vec!['6', '.', '.', '1', '9', '5', '.', '.', '.'], - vec!['.', '9', '8', '.', '.', '.', '.', '6', '.'], - vec!['8', '.', '.', '.', '6', '.', '.', '.', '3'], - vec!['4', '.', '.', '8', '.', '3', '.', '.', '1'], - vec!['7', '.', '.', '.', '2', '.', '.', '.', '6'], - vec!['.', '6', '.', '.', '.', '.', '2', '8', '.'], - vec!['.', '.', '.', '4', '1', '9', '.', '.', '5'], - vec!['.', '.', '.', '.', '8', '.', '.', '7', '9'] - ]), - true - ); - } -} diff --git a/src/solution/s0037_sudoku_solver.rs b/src/solution/s0037_sudoku_solver.rs deleted file mode 100644 index d0187582..00000000 --- a/src/solution/s0037_sudoku_solver.rs +++ /dev/null @@ -1,51 +0,0 @@ -/** - * [37] Sudoku Solver - * - * Write a program to solve a Sudoku puzzle by filling the empty cells. - * - * A sudoku solution must satisfy all of the following rules: - * - *
    - * Each of the digits 1-9 must occur exactly once in each row. - * Each of the digits 1-9 must occur exactly once in each column. - * Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. - *
- * - * Empty cells are indicated by the character '.'. - * - *
- * A sudoku puzzle... - * - *
- * ...and its solution numbers marked in red. - * - * Note: - * - * - * The given board contain only digits 1-9 and the character '.'. - * You may assume that the given Sudoku puzzle will have a single unique solution. - * The given board size is always 9x9. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/sudoku-solver/ -// discuss: https://leetcode.com/problems/sudoku-solver/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO -impl Solution { - pub fn solve_sudoku(board: &mut Vec>) {} -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_37() {} -} diff --git a/src/solution/s0038_count_and_say.rs b/src/solution/s0038_count_and_say.rs deleted file mode 100644 index 6305b2a5..00000000 --- a/src/solution/s0038_count_and_say.rs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * [38] Count and Say - * - * The count-and-say sequence is the sequence of integers with the first five terms as following: - * - * - * 1. 1 - * 2. 11 - * 3. 21 - * 4. 1211 - * 5. 111221 - * - * - * 1 is read off as "one 1" or 11.
- * 11 is read off as "two 1s" or 21.
- * 21 is read off as "one 2, then one 1" or 1211. - * - * Given an integer n where 1 <= n <= 30, generate the n^th term of the count-and-say sequence. - * - * Note: Each term of the sequence of integers will be represented as a string. - * - * - * - * Example 1: - * - * - * Input: 1 - * Output: "1" - * - * - * Example 2: - * - * - * Input: 4 - * Output: "1211" - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/count-and-say/ -// discuss: https://leetcode.com/problems/count-and-say/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::char::from_digit; -impl Solution { - pub fn count_and_say(n: i32) -> String { - let mut res = vec!['1']; - for _ in 0..n - 1 { - let mut temp = Vec::new(); - let mut i = 0_usize; - while i < res.len() { - let mut j = i + 1; - while j < res.len() && res[j] == res[i] { - j += 1; - } - temp.push(from_digit((j - i) as u32, 10).unwrap()); - temp.push(res[i]); - i = j; - } - res = temp; - } - res.iter().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_38() { - assert_eq!(Solution::count_and_say(1), "1"); - assert_eq!(Solution::count_and_say(2), "11"); - assert_eq!(Solution::count_and_say(3), "21"); - assert_eq!(Solution::count_and_say(4), "1211"); - assert_eq!(Solution::count_and_say(5), "111221"); - } -} diff --git a/src/solution/s0039_combination_sum.rs b/src/solution/s0039_combination_sum.rs deleted file mode 100644 index b31e397e..00000000 --- a/src/solution/s0039_combination_sum.rs +++ /dev/null @@ -1,100 +0,0 @@ -/** - * [39] Combination Sum - * - * Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. - * - * The same repeated number may be chosen from candidates unlimited number of times. - * - * Note: - * - * - * All numbers (including target) will be positive integers. - * The solution set must not contain duplicate combinations. - * - * - * Example 1: - * - * - * Input: candidates = [2,3,6,7], target = 7, - * A solution set is: - * [ - * [7], - * [2,2,3] - * ] - * - * - * Example 2: - * - * - * Input: candidates = [2,3,5], target = 8, - * A solution set is: - * [ - * [2,2,2,2], - * [2,3,3], - * [3,5] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/combination-sum/ -// discuss: https://leetcode.com/problems/combination-sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn combination_sum(candidates: Vec, target: i32) -> Vec> { - let mut seq = candidates; - let mut res = Vec::new(); - seq.sort_unstable_by(|a, b| b.cmp(a)); - let mut vec = Vec::new(); - Solution::backtrack(&seq, target, vec, &mut res, 0); - res - } - - fn backtrack( - seq: &Vec, - target: i32, - mut curr: Vec, - result: &mut Vec>, - start_idx: usize, - ) { - for i in start_idx..seq.len() { - let item = seq[i]; - if target - item < 0 { - continue; - } - let mut new_vec = curr.clone(); - new_vec.push(item); - if target == item { - result.push(new_vec); - } else { - Solution::backtrack(seq, target - item, new_vec, result, i); - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_39() { - assert_eq!( - Solution::combination_sum(vec![1], 7), - vec![vec![1, 1, 1, 1, 1, 1, 1]] - ); - assert_eq!( - Solution::combination_sum(vec![2, 3, 6, 7], 7), - vec![vec![7], vec![3, 2, 2],] - ); - assert_eq!( - Solution::combination_sum(vec![2, 3, 5], 8), - vec![vec![5, 3], vec![3, 3, 2], vec![2, 2, 2, 2],] - ); - } -} diff --git a/src/solution/s0040_combination_sum_ii.rs b/src/solution/s0040_combination_sum_ii.rs deleted file mode 100644 index 0445bfb9..00000000 --- a/src/solution/s0040_combination_sum_ii.rs +++ /dev/null @@ -1,107 +0,0 @@ -/** - * [40] Combination Sum II - * - * Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. - * - * Each number in candidates may only be used once in the combination. - * - * Note: - * - * - * All numbers (including target) will be positive integers. - * The solution set must not contain duplicate combinations. - * - * - * Example 1: - * - * - * Input: candidates = [10,1,2,7,6,1,5], target = 8, - * A solution set is: - * [ - * [1, 7], - * [1, 2, 5], - * [2, 6], - * [1, 1, 6] - * ] - * - * - * Example 2: - * - * - * Input: candidates = [2,5,2,1,2], target = 5, - * A solution set is: - * [ - * [1,2,2], - * [5] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/combination-sum-ii/ -// discuss: https://leetcode.com/problems/combination-sum-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn combination_sum2(candidates: Vec, target: i32) -> Vec> { - let mut seq = candidates; - let mut res = Vec::new(); - seq.sort_unstable_by(|a, b| b.cmp(a)); - let mut vec = Vec::new(); - Solution::backtrack(&seq, target, vec, &mut res, 0); - res - } - - fn backtrack( - seq: &Vec, - target: i32, - mut curr: Vec, - result: &mut Vec>, - start_idx: usize, - ) { - let mut i = start_idx; - while i < seq.len() { - let item = seq[i]; - if target - item < 0 { - i += 1; - continue; - } - let mut new_vec = curr.clone(); - new_vec.push(item); - if target == item { - result.push(new_vec); - } else { - Solution::backtrack(seq, target - item, new_vec, result, i + 1); - } - // skip duplicate result - while i < seq.len() && seq[i] == item { - i += 1; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_40() { - assert_eq!( - Solution::combination_sum2(vec![1, 1, 1, 1, 1, 1, 1], 7), - vec![vec![1, 1, 1, 1, 1, 1, 1]] - ); - assert_eq!( - Solution::combination_sum2(vec![10, 1, 2, 7, 6, 1, 5], 8), - vec![vec![7, 1], vec![6, 2], vec![6, 1, 1], vec![5, 2, 1],] - ); - assert_eq!( - Solution::combination_sum2(vec![2, 5, 2, 1, 2], 5), - vec![vec![5], vec![2, 2, 1],] - ); - } -} diff --git a/src/solution/s0041_first_missing_positive.rs b/src/solution/s0041_first_missing_positive.rs deleted file mode 100644 index 80cd8d8e..00000000 --- a/src/solution/s0041_first_missing_positive.rs +++ /dev/null @@ -1,91 +0,0 @@ -/** - * [41] First Missing Positive - * - * Given an unsorted integer array, find the smallest missing positive integer. - * - * Example 1: - * - * - * Input: [1,2,0] - * Output: 3 - * - * - * Example 2: - * - * - * Input: [3,4,-1,1] - * Output: 2 - * - * - * Example 3: - * - * - * Input: [7,8,9,11,12] - * Output: 1 - * - * - * Note: - * - * Your algorithm should run in O(n) time and uses constant extra space. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/first-missing-positive/ -// discuss: https://leetcode.com/problems/first-missing-positive/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn first_missing_positive(nums: Vec) -> i32 { - let mut nums = nums; - let len = nums.len(); - let mut i = 0; - let mut c = 0; - while i < len { - let num = nums[i]; - if num > 0 && num - 1 < (len as i32) { - c += 1; - nums.swap((num - 1) as usize, i); - if (num - 1) > (i as i32) && (num != nums[i]) { - continue; - } - } - i += 1; - } - println!("{}", c); - for (i, &num) in nums.iter().enumerate() { - if num != ((i + 1) as i32) { - return (i + 1) as i32; - } - } - return (len + 1) as i32; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_41() { - assert_eq!(Solution::first_missing_positive(vec![2, 2]), 1); - assert_eq!( - Solution::first_missing_positive(vec![12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]), - 1 - ); - assert_eq!( - Solution::first_missing_positive(vec![2, 2, 2, 2, 2, 2, 2]), - 1 - ); - assert_eq!(Solution::first_missing_positive(vec![3, 4, -1, 1]), 2); - assert_eq!(Solution::first_missing_positive(vec![2, 1, 0]), 3); - assert_eq!(Solution::first_missing_positive(vec![7, 8, 9, 11, 12]), 1); - assert_eq!( - Solution::first_missing_positive(vec![7, 8, 1, 2, 3, 3, 3, 3, 3, 3, 3, -5, -7, 1234]), - 4 - ); - } -} diff --git a/src/solution/s0042_trapping_rain_water.rs b/src/solution/s0042_trapping_rain_water.rs deleted file mode 100644 index 9d961994..00000000 --- a/src/solution/s0042_trapping_rain_water.rs +++ /dev/null @@ -1,38 +0,0 @@ -/** - * [42] Trapping Rain Water - * - * Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. - * - *
- * The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! - * - * Example: - * - * - * Input: [0,1,0,2,1,0,1,3,2,1,2,1] - * Output: 6 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/trapping-rain-water/ -// discuss: https://leetcode.com/problems/trapping-rain-water/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO -impl Solution { - pub fn trap(height: Vec) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_42() {} -} diff --git a/src/solution/s0043_multiply_strings.rs b/src/solution/s0043_multiply_strings.rs deleted file mode 100644 index 8c487b8e..00000000 --- a/src/solution/s0043_multiply_strings.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [43] Multiply Strings - * - * Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. - * - * Example 1: - * - * - * Input: num1 = "2", num2 = "3" - * Output: "6" - * - * Example 2: - * - * - * Input: num1 = "123", num2 = "456" - * Output: "56088" - * - * - * Note: - * - *
    - * The length of both num1 and num2 is < 110. - * Both num1 and num2 contain only digits 0-9. - * Both num1 and num2 do not contain any leading zero, except the number 0 itself. - * You must not use any built-in BigInteger library or convert the inputs to integer directly. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/multiply-strings/ -// discuss: https://leetcode.com/problems/multiply-strings/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO -use std::char::from_digit; -use std::collections::VecDeque; -impl Solution { - pub fn multiply(num1: String, num2: String) -> String { - let mut num1: Vec = num1.chars().map(|ch| ch.to_digit(10).unwrap()).collect(); - let mut num2: Vec = num2.chars().map(|ch| ch.to_digit(10).unwrap()).collect(); - let mut buffer = VecDeque::with_capacity(num2.len() + 1); - let mut res: Vec = Vec::new(); - let mut carry = 0_u32; - num1.reverse(); - num2.reverse(); - for (i, multiplier) in num1.into_iter().enumerate() { - buffer - .pop_back() - .and_then(|digit| Some(res.push(from_digit(digit, 10).unwrap()))); - for &multiplicand in num2.iter() {} - } - res.reverse(); - res.into_iter().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_43() {} -} diff --git a/src/solution/s0044_wildcard_matching.rs b/src/solution/s0044_wildcard_matching.rs deleted file mode 100644 index e875131a..00000000 --- a/src/solution/s0044_wildcard_matching.rs +++ /dev/null @@ -1,91 +0,0 @@ -/** - * [44] Wildcard Matching - * - * Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. - * - * - * '?' Matches any single character. - * '*' Matches any sequence of characters (including the empty sequence). - * - * - * The matching should cover the entire input string (not partial). - * - * Note: - * - * - * s could be empty and contains only lowercase letters a-z. - * p could be empty and contains only lowercase letters a-z, and characters like ? or *. - * - * - * Example 1: - * - * - * Input: - * s = "aa" - * p = "a" - * Output: false - * Explanation: "a" does not match the entire string "aa". - * - * - * Example 2: - * - * - * Input: - * s = "aa" - * p = "*" - * Output: true - * Explanation: '*' matches any sequence. - * - * - * Example 3: - * - * - * Input: - * s = "cb" - * p = "?a" - * Output: false - * Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. - * - * - * Example 4: - * - * - * Input: - * s = "adceb" - * p = "*a*b" - * Output: true - * Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". - * - * - * Example 5: - * - * - * Input: - * s = "acdcb" - * p = "a*c?b" - * Output: false - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/wildcard-matching/ -// discuss: https://leetcode.com/problems/wildcard-matching/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_match(s: String, p: String) -> bool { - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_44() {} -} diff --git a/src/solution/s0045_jump_game_ii.rs b/src/solution/s0045_jump_game_ii.rs deleted file mode 100644 index 3922e20b..00000000 --- a/src/solution/s0045_jump_game_ii.rs +++ /dev/null @@ -1,45 +0,0 @@ -/** - * [45] Jump Game II - * - * Given an array of non-negative integers, you are initially positioned at the first index of the array. - * - * Each element in the array represents your maximum jump length at that position. - * - * Your goal is to reach the last index in the minimum number of jumps. - * - * Example: - * - * - * Input: [2,3,1,1,4] - * Output: 2 - * Explanation: The minimum number of jumps to reach the last index is 2. - * Jump 1 step from index 0 to 1, then 3 steps to the last index. - * - * Note: - * - * You can assume that you can always reach the last index. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/jump-game-ii/ -// discuss: https://leetcode.com/problems/jump-game-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: shortest path from backward -impl Solution { - pub fn jump(nums: Vec) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_45() {} -} diff --git a/src/solution/s0046_permutations.rs b/src/solution/s0046_permutations.rs deleted file mode 100644 index ef9354c8..00000000 --- a/src/solution/s0046_permutations.rs +++ /dev/null @@ -1,70 +0,0 @@ -/** - * [46] Permutations - * - * Given a collection of distinct integers, return all possible permutations. - * - * Example: - * - * - * Input: [1,2,3] - * Output: - * [ - * [1,2,3], - * [1,3,2], - * [2,1,3], - * [2,3,1], - * [3,1,2], - * [3,2,1] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/permutations/ -// discuss: https://leetcode.com/problems/permutations/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn permute(nums: Vec) -> Vec> { - if nums.len() <= 1 { - return vec![nums]; - } - nums.iter() - .flat_map(|&num| { - let mut sub = nums.clone().into_iter().filter(|&x| x != num).collect(); - Solution::permute(sub) - .into_iter() - .map(|vec| { - let mut vec = vec; - vec.push(num); - vec - }) - .collect::>>() - }) - .collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_46() { - assert_eq!( - Solution::permute(vec![1, 2, 3]), - vec![ - vec![3, 2, 1], - vec![2, 3, 1], - vec![3, 1, 2], - vec![1, 3, 2], - vec![2, 1, 3], - vec![1, 2, 3], - ] - ) - } -} diff --git a/src/solution/s0047_permutations_ii.rs b/src/solution/s0047_permutations_ii.rs deleted file mode 100644 index 7dceb55b..00000000 --- a/src/solution/s0047_permutations_ii.rs +++ /dev/null @@ -1,179 +0,0 @@ -/** - * [47] Permutations II - * - * Given a collection of numbers that might contain duplicates, return all possible unique permutations. - * - * Example: - * - * - * Input: [1,1,2] - * Output: - * [ - * [1,1,2], - * [1,2,1], - * [2,1,1] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/permutations-ii/ -// discuss: https://leetcode.com/problems/permutations-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn permute_unique(nums: Vec) -> Vec> { - let mut nums = nums; - nums.sort_unstable(); - Solution::permute(nums) - } - - fn permute(mut nums: Vec) -> Vec> { - if nums.len() <= 1 { - return vec![nums]; - } - let mut prev: Option = None; - let mut res = Vec::new(); - for (i, &num) in nums.iter().enumerate() { - if prev.is_some() && prev.unwrap() == num { - continue; - } else { - prev = Some(num) - } - let mut sub = nums.clone(); - sub.remove(i); - let mut permutations: Vec> = Solution::permute(sub) - .into_iter() - .map(|x| { - let mut x = x; - x.push(num); - x - }) - .collect(); - res.append(&mut permutations); - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_47() { - assert_eq!( - Solution::permute(vec![1, 1, 2]), - vec![vec![2, 1, 1], vec![1, 2, 1], vec![1, 1, 2],] - ); - assert_eq!(Solution::permute(vec![1, 1, 1]), vec![vec![1, 1, 1],]); - assert_eq!( - Solution::permute(vec![1, 1, 1, 2]), - vec![ - vec![2, 1, 1, 1], - vec![1, 2, 1, 1], - vec![1, 1, 2, 1], - vec![1, 1, 1, 2], - ] - ); - assert_eq!( - Solution::permute(vec![1, 1, 2, 2, 3, 3]), - vec![ - vec![3, 3, 2, 2, 1, 1], - vec![3, 2, 3, 2, 1, 1], - vec![2, 3, 3, 2, 1, 1], - vec![3, 2, 2, 3, 1, 1], - vec![2, 3, 2, 3, 1, 1], - vec![2, 2, 3, 3, 1, 1], - vec![3, 3, 2, 1, 2, 1], - vec![3, 2, 3, 1, 2, 1], - vec![2, 3, 3, 1, 2, 1], - vec![3, 3, 1, 2, 2, 1], - vec![3, 1, 3, 2, 2, 1], - vec![1, 3, 3, 2, 2, 1], - vec![3, 2, 1, 3, 2, 1], - vec![2, 3, 1, 3, 2, 1], - vec![3, 1, 2, 3, 2, 1], - vec![1, 3, 2, 3, 2, 1], - vec![2, 1, 3, 3, 2, 1], - vec![1, 2, 3, 3, 2, 1], - vec![3, 2, 2, 1, 3, 1], - vec![2, 3, 2, 1, 3, 1], - vec![2, 2, 3, 1, 3, 1], - vec![3, 2, 1, 2, 3, 1], - vec![2, 3, 1, 2, 3, 1], - vec![3, 1, 2, 2, 3, 1], - vec![1, 3, 2, 2, 3, 1], - vec![2, 1, 3, 2, 3, 1], - vec![1, 2, 3, 2, 3, 1], - vec![2, 2, 1, 3, 3, 1], - vec![2, 1, 2, 3, 3, 1], - vec![1, 2, 2, 3, 3, 1], - vec![3, 3, 2, 1, 1, 2], - vec![3, 2, 3, 1, 1, 2], - vec![2, 3, 3, 1, 1, 2], - vec![3, 3, 1, 2, 1, 2], - vec![3, 1, 3, 2, 1, 2], - vec![1, 3, 3, 2, 1, 2], - vec![3, 2, 1, 3, 1, 2], - vec![2, 3, 1, 3, 1, 2], - vec![3, 1, 2, 3, 1, 2], - vec![1, 3, 2, 3, 1, 2], - vec![2, 1, 3, 3, 1, 2], - vec![1, 2, 3, 3, 1, 2], - vec![3, 3, 1, 1, 2, 2], - vec![3, 1, 3, 1, 2, 2], - vec![1, 3, 3, 1, 2, 2], - vec![3, 1, 1, 3, 2, 2], - vec![1, 3, 1, 3, 2, 2], - vec![1, 1, 3, 3, 2, 2], - vec![3, 2, 1, 1, 3, 2], - vec![2, 3, 1, 1, 3, 2], - vec![3, 1, 2, 1, 3, 2], - vec![1, 3, 2, 1, 3, 2], - vec![2, 1, 3, 1, 3, 2], - vec![1, 2, 3, 1, 3, 2], - vec![3, 1, 1, 2, 3, 2], - vec![1, 3, 1, 2, 3, 2], - vec![1, 1, 3, 2, 3, 2], - vec![2, 1, 1, 3, 3, 2], - vec![1, 2, 1, 3, 3, 2], - vec![1, 1, 2, 3, 3, 2], - vec![3, 2, 2, 1, 1, 3], - vec![2, 3, 2, 1, 1, 3], - vec![2, 2, 3, 1, 1, 3], - vec![3, 2, 1, 2, 1, 3], - vec![2, 3, 1, 2, 1, 3], - vec![3, 1, 2, 2, 1, 3], - vec![1, 3, 2, 2, 1, 3], - vec![2, 1, 3, 2, 1, 3], - vec![1, 2, 3, 2, 1, 3], - vec![2, 2, 1, 3, 1, 3], - vec![2, 1, 2, 3, 1, 3], - vec![1, 2, 2, 3, 1, 3], - vec![3, 2, 1, 1, 2, 3], - vec![2, 3, 1, 1, 2, 3], - vec![3, 1, 2, 1, 2, 3], - vec![1, 3, 2, 1, 2, 3], - vec![2, 1, 3, 1, 2, 3], - vec![1, 2, 3, 1, 2, 3], - vec![3, 1, 1, 2, 2, 3], - vec![1, 3, 1, 2, 2, 3], - vec![1, 1, 3, 2, 2, 3], - vec![2, 1, 1, 3, 2, 3], - vec![1, 2, 1, 3, 2, 3], - vec![1, 1, 2, 3, 2, 3], - vec![2, 2, 1, 1, 3, 3], - vec![2, 1, 2, 1, 3, 3], - vec![1, 2, 2, 1, 3, 3], - vec![2, 1, 1, 2, 3, 3], - vec![1, 2, 1, 2, 3, 3], - vec![1, 1, 2, 2, 3, 3] - ] - ); - } -} diff --git a/src/solution/s0048_rotate_image.rs b/src/solution/s0048_rotate_image.rs deleted file mode 100644 index 6f6fdffa..00000000 --- a/src/solution/s0048_rotate_image.rs +++ /dev/null @@ -1,122 +0,0 @@ -/** - * [48] Rotate Image - * - * You are given an n x n 2D matrix representing an image. - * - * Rotate the image by 90 degrees (clockwise). - * - * Note: - * - * You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. - * - * Example 1: - * - * - * Given input matrix = - * [ - * [1,2,3], - * [4,5,6], - * [7,8,9] - * ], - * - * rotate the input matrix in-place such that it becomes: - * [ - * [7,4,1], - * [8,5,2], - * [9,6,3] - * ] - * - * - * Example 2: - * - * - * Given input matrix = - * [ - * [ 5, 1, 9,11], - * [ 2, 4, 8,10], - * [13, 3, 6, 7], - * [15,14,12,16] - * ], - * - * rotate the input matrix in-place such that it becomes: - * [ - * [15,13, 2, 5], - * [14, 3, 4, 1], - * [12, 6, 8, 9], - * [16, 7,10,11] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/rotate-image/ -// discuss: https://leetcode.com/problems/rotate-image/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// x,y -> y,n-x 2-dimension vector rotate -90 degree: -// ^ x 0 1 y -// | | * = -// v y -1 0 -x -// n-y,x <- n-x,n-y if we consider axis transform, then: rotate(x, y) = (y, -x + n) - -// we only need to iterate a 1/4 corner matrix, for odd matrix, we take an extra part in x direction -// -// even: -// -// x x o o -// x x o o -// o o o o -// o o o o -// -// odd: -// -// x x o o o -// x x o o o -// x x o o o -// o o o o o -// o o o o o - -impl Solution { - pub fn rotate(matrix: &mut Vec>) { - let mut matrix = matrix; - let (len, n) = (matrix.len(), matrix.len() - 1); - for x in 0..len / 2 { - for y in 0..(len + 1) / 2 { - let temp = matrix[x][y]; - matrix[x][y] = matrix[n - y][x]; - matrix[n - y][x] = matrix[n - x][n - y]; - matrix[n - x][n - y] = matrix[y][n - x]; - matrix[y][n - x] = temp; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_48() { - let mut matrix = vec![ - vec![5, 1, 9, 11], - vec![2, 4, 8, 10], - vec![13, 3, 6, 7], - vec![15, 14, 12, 16], - ]; - Solution::rotate(&mut matrix); - assert_eq!( - matrix, - vec![ - vec![15, 13, 2, 5], - vec![14, 3, 4, 1], - vec![12, 6, 8, 9], - vec![16, 7, 10, 11] - ] - ); - } -} diff --git a/src/solution/s0049_group_anagrams.rs b/src/solution/s0049_group_anagrams.rs deleted file mode 100644 index 64200ea3..00000000 --- a/src/solution/s0049_group_anagrams.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [49] Group Anagrams - * - * Given an array of strings, group anagrams together. - * - * Example: - * - * - * Input: ["eat", "tea", "tan", "ate", "nat", "bat"], - * Output: - * [ - * ["ate","eat","tea"], - * ["nat","tan"], - * ["bat"] - * ] - * - * Note: - * - * - * All inputs will be in lowercase. - * The order of your output does not matter. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/group-anagrams/ -// discuss: https://leetcode.com/problems/group-anagrams/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashMap; -impl Solution { - pub fn group_anagrams(strs: Vec) -> Vec> { - let mut map = HashMap::new(); - for s in strs.into_iter() { - let mut key = [0; 26]; - for ch in s.chars() { - key[(ch as u32 - 'a' as u32) as usize] += 1; - } - map.entry(key).or_insert(Vec::new()).push(s); - } - map.into_iter().map(|(_, v)| v).collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - use std::collections::HashSet; - // TODO: implement arbitrary match macro - #[test] - #[ignore] - fn test_49() { - assert_eq!( - Solution::group_anagrams(vec_string!["eat", "tea", "tan", "ate", "nat", "bat"]), - vec![ - vec_string!["tan", "nat"], - vec_string!["bat"], - vec_string!["eat", "ate", "tea"], - ] - ); - } -} diff --git a/src/solution/s0050_powx_n.rs b/src/solution/s0050_powx_n.rs deleted file mode 100644 index 3e2e9b3e..00000000 --- a/src/solution/s0050_powx_n.rs +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [50] Pow(x, n) - * - * Implement pow(x, n), which calculates x raised to the power n (x^n). - * - * Example 1: - * - * - * Input: 2.00000, 10 - * Output: 1024.00000 - * - * - * Example 2: - * - * - * Input: 2.10000, 3 - * Output: 9.26100 - * - * - * Example 3: - * - * - * Input: 2.00000, -2 - * Output: 0.25000 - * Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25 - * - * - * Note: - * - * - * -100.0 < x < 100.0 - * n is a 32-bit signed integer, within the range [-2^31, 2^31 - 1] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/powx-n/ -// discuss: https://leetcode.com/problems/powx-n/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn my_pow(x: f64, n: i32) -> f64 { - x.powi(n) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_50() { - assert_eq!(Solution::my_pow(2.0, -2), 0.25); - assert_eq!(Solution::my_pow(2.0, 4), 16.0); - assert_eq!(Solution::my_pow(2.0, 5), 32.0); - assert_eq!(Solution::my_pow(2.0, 1), 2.0); - assert_eq!(Solution::my_pow(2.0, -1), 0.5); - assert_eq!(Solution::my_pow(2.0, 10), 1024.0); - } -} diff --git a/src/solution/s0051_n_queens.rs b/src/solution/s0051_n_queens.rs deleted file mode 100644 index d78435a9..00000000 --- a/src/solution/s0051_n_queens.rs +++ /dev/null @@ -1,109 +0,0 @@ -/** - * [51] N-Queens - * - * The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other. - * - * - * - * Given an integer n, return all distinct solutions to the n-queens puzzle. - * - * Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. - * - * Example: - * - * - * Input: 4 - * Output: [ - * [".Q..", // Solution 1 - * "...Q", - * "Q...", - * "..Q."], - * - * ["..Q.", // Solution 2 - * "Q...", - * "...Q", - * ".Q.."] - * ] - * Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/n-queens/ -// discuss: https://leetcode.com/problems/n-queens/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn solve_n_queens(n: i32) -> Vec> { - let mut board = vec![vec!['.'; n as usize]; n as usize]; - let mut solution = Vec::new(); - Solution::schedule_queens(&mut board, &mut solution, n as usize, 0); - solution - } - - fn schedule_queens( - board: &mut Vec>, - solution: &mut Vec>, - len: usize, - row: usize, - ) { - for col in 0..len { - if !Solution::collision(&board, len, row, col) { - board[row][col] = 'Q'; - if row == len - 1 { - solution.push(board.iter().map(|vec| vec.iter().collect()).collect()); - } else { - Solution::schedule_queens(board, solution, len, row + 1); - } - board[row][col] = '.'; - } - } - } - - #[inline(always)] - fn collision(board: &Vec>, len: usize, x: usize, y: usize) -> bool { - for i in 0..x { - if board[i][y] == 'Q' { - return true; - } - } - let (mut i, mut j) = (x as i32 - 1, y as i32 - 1); - while i >= 0 && j >= 0 { - if board[i as usize][j as usize] == 'Q' { - return true; - } - i -= 1; - j -= 1; - } - let (mut i, mut j) = (x as i32 - 1, y as i32 + 1); - while i >= 0 && j < len as i32 { - if board[i as usize][j as usize] == 'Q' { - return true; - } - i -= 1; - j += 1; - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_51() { - assert_eq!( - Solution::solve_n_queens(4), - vec![ - vec![".Q..", "...Q", "Q...", "..Q."], - vec!["..Q.", "Q...", "...Q", ".Q.."] - ] - ); - assert_eq!(Solution::solve_n_queens(8).len(), 92); - } -} diff --git a/src/solution/s0052_n_queens_ii.rs b/src/solution/s0052_n_queens_ii.rs deleted file mode 100644 index 7c9b1987..00000000 --- a/src/solution/s0052_n_queens_ii.rs +++ /dev/null @@ -1,99 +0,0 @@ -/** - * [52] N-Queens II - * - * The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. - * - * - * - * Given an integer n, return the number of distinct solutions to the n-queens puzzle. - * - * Example: - * - * - * Input: 4 - * Output: 2 - * Explanation: There are two distinct solutions to the 4-queens puzzle as shown below. - * [ - * [".Q..", // Solution 1 - * "...Q", - * "Q...", - * "..Q."], - * - * ["..Q.", // Solution 2 - * "Q...", - * "...Q", - * ".Q.."] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/n-queens-ii/ -// discuss: https://leetcode.com/problems/n-queens-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn total_n_queens(n: i32) -> i32 { - let mut board = vec![vec!['.'; n as usize]; n as usize]; - let mut num = 0; - Solution::schedule_queens(&mut board, &mut num, n as usize, 0); - num - } - - fn schedule_queens(board: &mut Vec>, num: &mut i32, len: usize, row: usize) { - for col in 0..len { - if !Solution::collision(&board, len, row, col) { - board[row][col] = 'Q'; - if row == len - 1 { - *num += 1; - } else { - Solution::schedule_queens(board, num, len, row + 1); - } - board[row][col] = '.'; - } - } - } - - #[inline(always)] - fn collision(board: &Vec>, len: usize, x: usize, y: usize) -> bool { - for i in 0..x { - if board[i][y] == 'Q' { - return true; - } - } - let (mut i, mut j) = (x as i32 - 1, y as i32 - 1); - while i >= 0 && j >= 0 { - if board[i as usize][j as usize] == 'Q' { - return true; - } - i -= 1; - j -= 1; - } - let (mut i, mut j) = (x as i32 - 1, y as i32 + 1); - while i >= 0 && j < len as i32 { - if board[i as usize][j as usize] == 'Q' { - return true; - } - i -= 1; - j += 1; - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_52() { - assert_eq!(Solution::total_n_queens(4), 2); - assert_eq!(Solution::total_n_queens(8), 92); - assert_eq!(Solution::total_n_queens(13), 73712); - // assert_eq!(Solution::total_n_queens(14), 365596); - } -} diff --git a/src/solution/s0053_maximum_subarray.rs b/src/solution/s0053_maximum_subarray.rs deleted file mode 100644 index 7967fb00..00000000 --- a/src/solution/s0053_maximum_subarray.rs +++ /dev/null @@ -1,57 +0,0 @@ -/** - * [53] Maximum Subarray - * - * Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. - * - * Example: - * - * - * Input: [-2,1,-3,4,-1,2,1,-5,4], - * Output: 6 - * Explanation: [4,-1,2,1] has the largest sum = 6. - * - * - * Follow up: - * - * If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/maximum-subarray/ -// discuss: https://leetcode.com/problems/maximum-subarray/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn max_sub_array(nums: Vec) -> i32 { - let mut j = 0_usize; - let mut max = i32::min_value(); - let mut curr = 0; - for j in 0..nums.len() { - curr += nums[j]; - max = i32::max(max, curr); - if curr <= 0 { - curr = 0; - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_53() { - assert_eq!( - Solution::max_sub_array(vec![-2, 1, -3, 4, -1, 2, 1, -5, 4]), - 6 - ); - assert_eq!(Solution::max_sub_array(vec![-8]), -8); - assert_eq!(Solution::max_sub_array(vec![-8, -2]), -2); - } -} diff --git a/src/solution/s0054_spiral_matrix.rs b/src/solution/s0054_spiral_matrix.rs deleted file mode 100644 index ac90b769..00000000 --- a/src/solution/s0054_spiral_matrix.rs +++ /dev/null @@ -1,101 +0,0 @@ -/** - * [54] Spiral Matrix - * - * Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. - * - * Example 1: - * - * - * Input: - * [ - * [ 1, 2, 3 ], - * [ 4, 5, 6 ], - * [ 7, 8, 9 ] - * ] - * Output: [1,2,3,6,9,8,7,4,5] - * - * - * Example 2: - * - * Input: - * [ - * [1, 2, 3, 4], - * [5, 6, 7, 8], - * [9,10,11,12] - * ] - * Output: [1,2,3,4,8,12,11,10,9,5,6,7] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/spiral-matrix/ -// discuss: https://leetcode.com/problems/spiral-matrix/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn spiral_order(matrix: Vec>) -> Vec { - let mut res = Vec::new(); - if matrix.len() < 1 { - return res; - } - let (height, width) = (matrix.len(), matrix[0].len()); - let (mut x_min, mut x_max, mut y_min, mut y_max) = (0, height, 0, width); - loop { - for y in y_min..y_max { - res.push(matrix[x_min][y]) - } - x_min += 1; - if x_min == x_max { - break; - } - for x in x_min..x_max { - res.push(matrix[x][y_max - 1]) - } - y_max -= 1; - if y_min == y_max { - break; - } - for y in (y_min..y_max).rev() { - res.push(matrix[x_max - 1][y]) - } - x_max -= 1; - if x_min == x_max { - break; - } - for x in (x_min..x_max).rev() { - res.push(matrix[x][y_min]) - } - y_min += 1; - if y_min == y_max { - break; - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_54() { - assert_eq!( - Solution::spiral_order(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]), - vec![1, 2, 3, 6, 9, 8, 7, 4, 5] - ); - assert_eq!(Solution::spiral_order(vec![vec![1, 2, 3]]), vec![1, 2, 3]); - assert_eq!( - Solution::spiral_order(vec![vec![1], vec![2], vec![3],]), - vec![1, 2, 3] - ); - assert_eq!(Solution::spiral_order(vec![vec![1],]), vec![1]); - assert_eq!( - Solution::spiral_order(vec![vec![1, 2], vec![4, 5],]), - vec![1, 2, 5, 4] - ); - } -} diff --git a/src/solution/s0055_jump_game.rs b/src/solution/s0055_jump_game.rs deleted file mode 100644 index 8dc35842..00000000 --- a/src/solution/s0055_jump_game.rs +++ /dev/null @@ -1,66 +0,0 @@ -/** - * [55] Jump Game - * - * Given an array of non-negative integers, you are initially positioned at the first index of the array. - * - * Each element in the array represents your maximum jump length at that position. - * - * Determine if you are able to reach the last index. - * - * Example 1: - * - * - * Input: [2,3,1,1,4] - * Output: true - * Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. - * - * - * Example 2: - * - * - * Input: [3,2,1,0,4] - * Output: false - * Explanation: You will always arrive at index 3 no matter what. Its maximum - * jump length is 0, which makes it impossible to reach the last index. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/jump-game/ -// discuss: https://leetcode.com/problems/jump-game/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn can_jump(nums: Vec) -> bool { - let mut max_idx = 0_usize; - let mut start = 0_usize; - while start < nums.len() && start <= max_idx { - max_idx = usize::max(start + nums[start] as usize, max_idx); - start += 1; - } - return max_idx >= (nums.len() - 1); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_55() { - assert_eq!(Solution::can_jump(vec![2, 3, 1, 1, 4]), true); - assert_eq!(Solution::can_jump(vec![3, 2, 1, 0, 4]), false); - assert_eq!(Solution::can_jump(vec![2, 3, 1, 1, 0, 0, 0, 4]), false); - assert_eq!(Solution::can_jump(vec![8, 3, 1, 1, 0, 0, 0, 4]), true); - assert_eq!(Solution::can_jump(vec![0]), true); - assert_eq!(Solution::can_jump(vec![1, 1, 2, 2, 0, 1, 1]), true); - assert_eq!( - Solution::can_jump(vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]), - true - ); - } -} diff --git a/src/solution/s0056_merge_intervals.rs b/src/solution/s0056_merge_intervals.rs deleted file mode 100644 index 108c043b..00000000 --- a/src/solution/s0056_merge_intervals.rs +++ /dev/null @@ -1,85 +0,0 @@ -/** - * [56] Merge Intervals - * - * Given a collection of intervals, merge all overlapping intervals. - * - * Example 1: - * - * - * Input: [[1,3],[2,6],[8,10],[15,18]] - * Output: [[1,6],[8,10],[15,18]] - * Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. - * - * - * Example 2: - * - * - * Input: [[1,4],[4,5]] - * Output: [[1,5]] - * Explanation: Intervals [1,4] and [4,5] are considered overlapping. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/merge-intervals/ -// discuss: https://leetcode.com/problems/merge-intervals/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for an interval. -#[derive(Debug, PartialEq, Eq)] -pub struct Interval { - pub start: i32, - pub end: i32, -} - -impl Interval { - #[inline] - pub fn new(start: i32, end: i32) -> Self { - Interval { start, end } - } -} -impl Solution { - pub fn merge(intervals: Vec) -> Vec { - let mut intervals = intervals; - intervals.sort_unstable_by_key(|interval| interval.start); - let mut result: Vec = Vec::new(); - for interval in intervals.into_iter() { - match result.last_mut() { - Some(mut last_inter) => { - if last_inter.end >= interval.start { - last_inter.end = i32::max(last_inter.end, interval.end); - continue; - } - } - None => {} - } - result.push(interval); - } - result - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_56() { - assert_eq!( - Solution::merge(vec![ - Interval::new(1, 3), - Interval::new(2, 6), - Interval::new(8, 10), - Interval::new(15, 18) - ]), - vec![ - Interval::new(1, 6), - Interval::new(8, 10), - Interval::new(15, 18) - ] - ); - } -} diff --git a/src/solution/s0057_insert_interval.rs b/src/solution/s0057_insert_interval.rs deleted file mode 100644 index 0afe62b4..00000000 --- a/src/solution/s0057_insert_interval.rs +++ /dev/null @@ -1,126 +0,0 @@ -/** - * [57] Insert Interval - * - * Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). - * - * You may assume that the intervals were initially sorted according to their start times. - * - * Example 1: - * - * - * Input: intervals = [[1,3],Interval::new(6,9)], newInterval = [2,5] - * Output: [[1,5],[6,9]] - * - * - * Example 2: - * - * - * Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] - * Output: [[1,2],[3,10],[12,16]] - * Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/insert-interval/ -// discuss: https://leetcode.com/problems/insert-interval/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for an interval. -#[derive(Debug, PartialEq, Eq)] -pub struct Interval { - pub start: i32, - pub end: i32, -} - -impl Interval { - #[inline] - pub fn new(start: i32, end: i32) -> Self { - Interval { start, end } - } -} -impl Solution { - pub fn insert(intervals: Vec, new_interval: Interval) -> Vec { - let mut result = Vec::new(); - let mut new_interval = new_interval; - let mut inserting = false; - let mut inserted = false; - for interval in intervals.into_iter() { - if new_interval.start <= interval.end && !inserted { - inserting = true; - } - if inserting { - if new_interval.end >= interval.start { - new_interval.start = i32::min(new_interval.start, interval.start); - new_interval.end = i32::max(new_interval.end, interval.end); - } else { - result.push(Interval::new(new_interval.start, new_interval.end)); - inserting = false; - inserted = true; - } - } - if !inserting { - result.push(interval); - } - } - if !inserted { - result.push(new_interval); - } - result - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_57() { - assert_eq!( - Solution::insert( - vec![Interval::new(1, 3), Interval::new(6, 9)], - Interval::new(2, 5) - ), - vec![Interval::new(1, 5), Interval::new(6, 9)] - ); - assert_eq!( - Solution::insert( - vec![ - Interval::new(1, 2), - Interval::new(3, 5), - Interval::new(6, 7), - Interval::new(8, 10), - Interval::new(12, 16) - ], - Interval::new(4, 8) - ), - vec![ - Interval::new(1, 2), - Interval::new(3, 10), - Interval::new(12, 16) - ] - ); - assert_eq!( - Solution::insert(vec![Interval::new(3, 4)], Interval::new(1, 2)), - vec![Interval::new(1, 2), Interval::new(3, 4)] - ); - assert_eq!( - Solution::insert(vec![Interval::new(1, 2)], Interval::new(3, 4)), - vec![Interval::new(1, 2), Interval::new(3, 4)] - ); - assert_eq!( - Solution::insert(vec![Interval::new(1, 2)], Interval::new(2, 3)), - vec![Interval::new(1, 3)] - ); - assert_eq!( - Solution::insert( - vec![Interval::new(1, 2), Interval::new(3, 4)], - Interval::new(0, 6) - ), - vec![Interval::new(0, 6)] - ); - } -} diff --git a/src/solution/s0058_length_of_last_word.rs b/src/solution/s0058_length_of_last_word.rs deleted file mode 100644 index 4889c739..00000000 --- a/src/solution/s0058_length_of_last_word.rs +++ /dev/null @@ -1,55 +0,0 @@ -/** - * [58] Length of Last Word - * - * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. - * - * If the last word does not exist, return 0. - * - * Note: A word is defined as a character sequence consists of non-space characters only. - * - * Example: - * - * Input: "Hello World" - * Output: 5 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/length-of-last-word/ -// discuss: https://leetcode.com/problems/length-of-last-word/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn length_of_last_word(s: String) -> i32 { - let seq: Vec = s.chars().rev().collect(); - let mut result = 0; - let mut find = false; - for ch in seq { - if ch == ' ' && find { - break; - } - if ch != ' ' { - find = true; - result += 1; - } - } - result - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_58() { - assert_eq!(Solution::length_of_last_word("Hello World".to_owned()), 5); - assert_eq!(Solution::length_of_last_word(" ".to_owned()), 0); - assert_eq!(Solution::length_of_last_word("".to_owned()), 0); - assert_eq!(Solution::length_of_last_word(" rrrrr ".to_owned()), 5); - } -} diff --git a/src/solution/s0059_spiral_matrix_ii.rs b/src/solution/s0059_spiral_matrix_ii.rs deleted file mode 100644 index d54f57b4..00000000 --- a/src/solution/s0059_spiral_matrix_ii.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [59] Spiral Matrix II - * - * Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. - * - * Example: - * - * - * Input: 3 - * Output: - * [ - * [ 1, 2, 3 ], - * [ 8, 9, 4 ], - * [ 7, 6, 5 ] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/spiral-matrix-ii/ -// discuss: https://leetcode.com/problems/spiral-matrix-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn generate_matrix(n: i32) -> Vec> { - let mut res = vec![vec![0; n as usize]; n as usize]; - if n < 1 { - return res; - } - let (mut x_min, mut x_max, mut y_min, mut y_max) = (0, n as usize, 0, n as usize); - let mut i = 1; - loop { - for y in y_min..y_max { - res[x_min][y] = i; - i += 1; - } - x_min += 1; - if x_min == x_max { - break; - } - for x in x_min..x_max { - res[x][y_max - 1] = i; - i += 1; - } - y_max -= 1; - if y_min == y_max { - break; - } - for y in (y_min..y_max).rev() { - res[x_max - 1][y] = i; - i += 1; - } - x_max -= 1; - if x_min == x_max { - break; - } - for x in (x_min..x_max).rev() { - res[x][y_min] = i; - i += 1; - } - y_min += 1; - if y_min == y_max { - break; - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_59() { - assert_eq!(Solution::generate_matrix(1), vec![vec![1]]); - assert_eq!(Solution::generate_matrix(2), vec![vec![1, 2], vec![4, 3]]); - assert_eq!( - Solution::generate_matrix(3), - vec![vec![1, 2, 3], vec![8, 9, 4], vec![7, 6, 5],] - ); - } -} diff --git a/src/solution/s0060_permutation_sequence.rs b/src/solution/s0060_permutation_sequence.rs deleted file mode 100644 index 0136a0b4..00000000 --- a/src/solution/s0060_permutation_sequence.rs +++ /dev/null @@ -1,76 +0,0 @@ -/** - * [60] Permutation Sequence - * - * The set [1,2,3,...,n] contains a total of n! unique permutations. - * - * By listing and labeling all of the permutations in order, we get the following sequence for n = 3: - * - *
    - * "123" - * "132" - * "213" - * "231" - * "312" - * "321" - *
- * - * Given n and k, return the k^th permutation sequence. - * - * Note: - * - * - * Given n will be between 1 and 9 inclusive. - * Given k will be between 1 and n! inclusive. - * - * - * Example 1: - * - * - * Input: n = 3, k = 3 - * Output: "213" - * - * - * Example 2: - * - * - * Input: n = 4, k = 9 - * Output: "2314" - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/permutation-sequence/ -// discuss: https://leetcode.com/problems/permutation-sequence/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// target: split k = i! + j! + ... -use std::char::from_digit; -impl Solution { - pub fn get_permutation(n: i32, k: i32) -> String { - let factorials = [0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]; - let mut k = k; - let mut i = n; - let mut res = String::new(); - while i > 0 { - if k > factorials[i as usize] { - let round = k / factorials[i as usize]; - if round >= n {} - } else { - i -= 1; - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_60() {} -} diff --git a/src/solution/s0061_rotate_list.rs b/src/solution/s0061_rotate_list.rs deleted file mode 100644 index bbfb059f..00000000 --- a/src/solution/s0061_rotate_list.rs +++ /dev/null @@ -1,50 +0,0 @@ -/** - * [61] Rotate List - * - * Given a linked list, rotate the list to the right by k places, where k is non-negative. - * - * Example 1: - * - * - * Input: 1->2->3->4->5->NULL, k = 2 - * Output: 4->5->1->2->3->NULL - * Explanation: - * rotate 1 steps to the right: 5->1->2->3->4->NULL - * rotate 2 steps to the right: 4->5->1->2->3->NULL - * - * - * Example 2: - * - * - * Input: 0->1->2->NULL, k = 4 - * Output: 2->0->1->NULL - * Explanation: - * rotate 1 steps to the right: 2->0->1->NULL - * rotate 2 steps to the right: 1->2->0->NULL - * rotate 3 steps to the right: 0->1->2->NULL - * rotate 4 steps to the right: 2->0->1->NULL - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/rotate-list/ -// discuss: https://leetcode.com/problems/rotate-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn rotate_right(head: Option>, k: i32) -> Option> { - None - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_61() {} -} diff --git a/src/solution/s0062_unique_paths.rs b/src/solution/s0062_unique_paths.rs deleted file mode 100644 index 3a158326..00000000 --- a/src/solution/s0062_unique_paths.rs +++ /dev/null @@ -1,80 +0,0 @@ -/** - * [62] Unique Paths - * - * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). - * - * The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). - * - * How many possible unique paths are there? - * - *
- * Above is a 7 x 3 grid. How many possible unique paths are there? - * - * Note: m and n will be at most 100. - * - * Example 1: - * - * - * Input: m = 3, n = 2 - * Output: 3 - * Explanation: - * From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: - * 1. Right -> Right -> Down - * 2. Right -> Down -> Right - * 3. Down -> Right -> Right - * - * - * Example 2: - * - * - * Input: m = 7, n = 3 - * Output: 28 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/unique-paths/ -// discuss: https://leetcode.com/problems/unique-paths/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// its high school math: C(r,n) = n! / r!(n-r)! ...are you fxxking kidding me? -// ...high school math will attempt to i32 overflow, we have to do it clever -impl Solution { - pub fn unique_paths(m: i32, n: i32) -> i32 { - let (m, n) = ((m - 1) as u64, (n - 1) as u64); - let sum = m + n; - (Solution::partial_factorial(u64::max(m, n), sum) - / Solution::partial_factorial(0, u64::min(m, n))) as i32 - } - - #[inline(always)] - pub fn partial_factorial(start: u64, mut end: u64) -> u64 { - if start > end { - unreachable!() - } - let mut res = 1; - while end > start { - println!("{}", end); - res *= end; - end -= 1; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_62() { - assert_eq!(Solution::unique_paths(7, 3), 28); - assert_eq!(Solution::unique_paths(3, 7), 28); - assert_eq!(Solution::unique_paths(1, 1), 1); - assert_eq!(Solution::unique_paths(2, 2), 2); - assert_eq!(Solution::unique_paths(36, 7), 4496388); - } -} diff --git a/src/solution/s0063_unique_paths_ii.rs b/src/solution/s0063_unique_paths_ii.rs deleted file mode 100644 index 04d84911..00000000 --- a/src/solution/s0063_unique_paths_ii.rs +++ /dev/null @@ -1,111 +0,0 @@ -/** - * [63] Unique Paths II - * - * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). - * - * The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). - * - * Now consider if some obstacles are added to the grids. How many unique paths would there be? - * - * - * - * An obstacle and empty space is marked as 1 and 0 respectively in the grid. - * - * Note: m and n will be at most 100. - * - * Example 1: - * - * - * Input: - * [ - * [0,0,0], - * [0,1,0], - * [0,0,0] - * ] - * Output: 2 - * Explanation: - * There is one obstacle in the middle of the 3x3 grid above. - * There are two ways to reach the bottom-right corner: - * 1. Right -> Right -> Down -> Down - * 2. Down -> Down -> Right -> Right - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/unique-paths-ii/ -// discuss: https://leetcode.com/problems/unique-paths-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Bottom-Up DP -impl Solution { - pub fn unique_paths_with_obstacles(obstacle_grid: Vec>) -> i32 { - let (height, width) = (obstacle_grid.len(), obstacle_grid[0].len()); - let mut paths: Vec> = vec![vec![0; width]; height]; - if obstacle_grid[0][0] != 1 { - paths[0][0] = 1; - } - let mut step = 1; - while step <= height + width - 2 { - for x in 0..(step + 1) { - let y = step - x; - if x >= height || y >= width || obstacle_grid[x][y] == 1 { - continue; - } - if y >= 1 { - paths[x][y] = paths[x][y] + paths[x][y - 1]; - } - if x >= 1 { - paths[x][y] = paths[x][y] + paths[x - 1][y]; - } - } - step += 1; - } - paths[height - 1][width - 1] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_63() { - assert_eq!(Solution::unique_paths_with_obstacles(vec![vec![0]]), 1); - assert_eq!( - Solution::unique_paths_with_obstacles(vec![vec![0, 0], vec![0, 0],]), - 2 - ); - assert_eq!( - Solution::unique_paths_with_obstacles(vec![vec![0, 1], vec![1, 0],]), - 0 - ); - assert_eq!( - Solution::unique_paths_with_obstacles(vec![ - vec![0, 0, 0], - vec![0, 1, 0], - vec![0, 0, 0], - ]), - 2 - ); - assert_eq!( - Solution::unique_paths_with_obstacles(vec![ - vec![0, 0, 0, 0], - vec![0, 0, 0, 0], - vec![0, 0, 0, 0], - ]), - 10 - ); - assert_eq!( - Solution::unique_paths_with_obstacles(vec![ - vec![0, 0, 0, 0], - vec![0, 0, 0, 1], - vec![0, 0, 1, 0], - ]), - 0 - ); - } -} diff --git a/src/solution/s0064_minimum_path_sum.rs b/src/solution/s0064_minimum_path_sum.rs deleted file mode 100644 index d6340d50..00000000 --- a/src/solution/s0064_minimum_path_sum.rs +++ /dev/null @@ -1,69 +0,0 @@ -/** - * [64] Minimum Path Sum - * - * Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. - * - * Note: You can only move either down or right at any point in time. - * - * Example: - * - * - * Input: - * [ - * [1,3,1], - * [1,5,1], - * [4,2,1] - * ] - * Output: 7 - * Explanation: Because the path 1→3→1→1→1 minimizes the sum. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/minimum-path-sum/ -// discuss: https://leetcode.com/problems/minimum-path-sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn min_path_sum(grid: Vec>) -> i32 { - let (height, width) = (grid.len(), grid[0].len()); - let mut grid = grid; - let mut step = 1; - while step <= height + width - 2 { - for x in 0..(step + 1) { - let y = step - x; - if x >= height || y >= width { - continue; - } - if x < 1 { - grid[x][y] += grid[x][y - 1]; - } else if y < 1 { - grid[x][y] += grid[x - 1][y]; - } else { - grid[x][y] += i32::min(grid[x][y - 1], grid[x - 1][y]); - } - } - step += 1; - } - grid[height - 1][width - 1] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_64() { - assert_eq!(Solution::min_path_sum(vec![vec![2]]), 2); - assert_eq!( - Solution::min_path_sum(vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1],]), - 7 - ); - assert_eq!(Solution::min_path_sum(vec![vec![1, 3, 1],]), 5); - } -} diff --git a/src/solution/s0065_valid_number.rs b/src/solution/s0065_valid_number.rs deleted file mode 100644 index 11c5753d..00000000 --- a/src/solution/s0065_valid_number.rs +++ /dev/null @@ -1,60 +0,0 @@ -/** - * [65] Valid Number - * - * Validate if a given string can be interpreted as a decimal number. - * - * Some examples:
- * "0" => true
- * " 0.1 " => true
- * "abc" => false
- * "1 a" => false
- * "2e10" => true
- * " -90e3 " => true
- * " 1e" => false
- * "e3" => false
- * " 6e-1" => true
- * " 99e2.5 " => false
- * "53.5e93" => true
- * " --6 " => false
- * "-+3" => false
- * "95a54e53" => false - * - * Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number: - * - * - * Numbers 0-9 - * Exponent - "e" - * Positive/negative sign - "+"/"-" - * Decimal point - "." - * - * - * Of course, the context of these characters also matters in the input. - * - * Update (2015-02-10):
- * The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/valid-number/ -// discuss: https://leetcode.com/problems/valid-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// hope that regex was included in std library... -// TODO: NFA -impl Solution { - pub fn is_number(s: String) -> bool { - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_65() {} -} diff --git a/src/solution/s0066_plus_one.rs b/src/solution/s0066_plus_one.rs deleted file mode 100644 index fb1ea045..00000000 --- a/src/solution/s0066_plus_one.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [66] Plus One - * - * Given a non-empty array of digits representing a non-negative integer, plus one to the integer. - * - * The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. - * - * You may assume the integer does not contain any leading zero, except the number 0 itself. - * - * Example 1: - * - * - * Input: [1,2,3] - * Output: [1,2,4] - * Explanation: The array represents the integer 123. - * - * - * Example 2: - * - * - * Input: [4,3,2,1] - * Output: [4,3,2,2] - * Explanation: The array represents the integer 4321. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/plus-one/ -// discuss: https://leetcode.com/problems/plus-one/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn plus_one(digits: Vec) -> Vec { - let mut digits = digits; - let mut carry = 0; - for i in (0..digits.len()).rev() { - digits[i] = if digits[i] == 9 { - carry = 1; - 0 - } else { - carry = 0; - digits[i] + 1 - }; - if carry == 0 { - break; - } - } - if carry > 0 { - digits.insert(0, 1); - } - digits - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_66() { - assert_eq!(Solution::plus_one(vec![0]), vec![1]); - assert_eq!(Solution::plus_one(vec![9, 9, 9, 9]), vec![1, 0, 0, 0, 0]); - assert_eq!( - Solution::plus_one(vec![1, 0, 9, 9, 9, 9]), - vec![1, 1, 0, 0, 0, 0] - ); - } -} diff --git a/src/solution/s0067_add_binary.rs b/src/solution/s0067_add_binary.rs deleted file mode 100644 index 8c9951cc..00000000 --- a/src/solution/s0067_add_binary.rs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * [67] Add Binary - * - * Given two binary strings, return their sum (also a binary string). - * - * The input strings are both non-empty and contains only characters 1 or 0. - * - * Example 1: - * - * - * Input: a = "11", b = "1" - * Output: "100" - * - * Example 2: - * - * - * Input: a = "1010", b = "1011" - * Output: "10101" - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/add-binary/ -// discuss: https://leetcode.com/problems/add-binary/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::char::from_digit; -impl Solution { - pub fn add_binary(a: String, b: String) -> String { - let mut buf = Vec::with_capacity(usize::max(a.len(), b.len()) + 1); - let mut a: Vec = a.chars().collect(); - let mut b: Vec = b.chars().collect(); - let mut carry = 0; - while !(a.is_empty() && b.is_empty()) { - let mut sum = a.pop().map_or(0, |ch| ch.to_digit(10).unwrap()) - + b.pop().map_or(0, |ch| ch.to_digit(10).unwrap()) - + carry; - if sum > 1 { - sum -= 2; - carry = 1; - } else { - carry = 0; - } - buf.push(from_digit(sum, 10).unwrap()) - } - if carry > 0 { - buf.push('1') - } - buf.into_iter().rev().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_67() { - assert_eq!( - Solution::add_binary("0".to_owned(), "0".to_owned()), - "0".to_owned() - ); - assert_eq!( - Solution::add_binary("1010".to_owned(), "1011".to_owned()), - "10101".to_owned() - ); - assert_eq!( - Solution::add_binary("11".to_owned(), "1".to_owned()), - "100".to_owned() - ); - assert_eq!( - Solution::add_binary("1111".to_owned(), "1111".to_owned()), - "11110".to_owned() - ); - } -} diff --git a/src/solution/s0068_text_justification.rs b/src/solution/s0068_text_justification.rs deleted file mode 100644 index 827fa4f8..00000000 --- a/src/solution/s0068_text_justification.rs +++ /dev/null @@ -1,200 +0,0 @@ -/** - * [68] Text Justification - * - * Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. - * - * You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. - * - * Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. - * - * For the last line of text, it should be left justified and no extra space is inserted between words. - * - * Note: - * - * - * A word is defined as a character sequence consisting of non-space characters only. - * Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. - * The input array words contains at least one word. - * - * - * Example 1: - * - * - * Input: - * words = ["This", "is", "an", "example", "of", "text", "justification."] - * maxWidth = 16 - * Output: - * [ - * "This is an", - * "example of text", - * "justification. " - * ] - * - * - * Example 2: - * - * - * Input: - * words = ["What","must","be","acknowledgment","shall","be"] - * maxWidth = 16 - * Output: - * [ - * "What must be", - * "acknowledgment ", - * "shall be " - * ] - * Explanation: Note that the last line is "shall be " instead of "shall be", - * because the last line must be left-justified instead of fully-justified. - * Note that the second line is also left-justified becase it contains only one word. - * - * - * Example 3: - * - * - * Input: - * words = ["Science","is","what","we","understand","well","enough","to","explain", - * "to","a","computer.","Art","is","everything","else","we","do"] - * maxWidth = 20 - * Output: - * [ - * "Science is what we", - * "understand well", - * "enough to explain to", - * "a computer. Art is", - * "everything else we", - * "do " - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/text-justification/ -// discuss: https://leetcode.com/problems/text-justification/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn full_justify(words: Vec, max_width: i32) -> Vec { - let mut res = Vec::new(); - let max_width = max_width as usize; - let mut i = 0; - let mut row_len = 0; - let mut buf = Vec::new(); - while i < words.len() { - if words[i].len() > max_width { - unreachable!() - } - let old_len = row_len; - row_len += words[i].len() + if row_len > 0 { 1 } else { 0 }; - if row_len > max_width { - res.push(Solution::compact(buf, max_width, old_len)); - buf = Vec::new(); - row_len = 0; - } else { - buf.push(words[i].clone()); - i += 1; - } - } - res.push(Solution::compact_last(buf, max_width)); - res - } - - fn compact(words: Vec, max_width: usize, row_len: usize) -> String { - let spaces = max_width - (row_len - words.len() + 1); - let avg_spaces = spaces / usize::max(1, words.len() - 1); - let mut extra_spaces = spaces - avg_spaces * usize::max(1, words.len() - 1);; - let mut res = String::new(); - for (i, word) in words.iter().enumerate() { - res.push_str(word); - if words.len() < 2 || (i < words.len() - 1) { - res.push_str(&" ".repeat(avg_spaces)); - if extra_spaces > 0 { - res.push(' '); - extra_spaces -= 1; - } - } - } - res - } - - fn compact_last(words: Vec, max_width: usize) -> String { - let mut res = String::new(); - for (i, word) in words.iter().enumerate() { - res.push_str(word); - if i < words.len() - 1 { - res.push(' '); - } - } - res.push_str(&" ".repeat(max_width - res.len())); - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_68() { - assert_eq!( - Solution::full_justify( - vec_string![ - "This", - "is", - "an", - "example", - "of", - "text", - "justification." - ], - 16 - ), - vec_string!["This is an", "example of text", "justification. "] - ); - - assert_eq!( - Solution::full_justify( - vec_string!["What", "must", "be", "acknowledgment", "shall", "be"], - 16 - ), - vec_string!["What must be", "acknowledgment ", "shall be "] - ); - - assert_eq!( - Solution::full_justify( - vec_string![ - "Science", - "is", - "what", - "we", - "understand", - "well", - "enough", - "to", - "explain", - "to", - "a", - "computer.", - "Art", - "is", - "everything", - "else", - "we", - "do" - ], - 20 - ), - vec_string![ - "Science is what we", - "understand well", - "enough to explain to", - "a computer. Art is", - "everything else we", - "do ", - ] - ); - } -} diff --git a/src/solution/s0069_sqrtx.rs b/src/solution/s0069_sqrtx.rs deleted file mode 100644 index 256f88be..00000000 --- a/src/solution/s0069_sqrtx.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [69] Sqrt(x) - * - * Implement int sqrt(int x). - * - * Compute and return the square root of x, where x is guaranteed to be a non-negative integer. - * - * Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. - * - * Example 1: - * - * - * Input: 4 - * Output: 2 - * - * - * Example 2: - * - * - * Input: 8 - * Output: 2 - * Explanation: The square root of 8 is 2.82842..., and since - * the decimal part is truncated, 2 is returned. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/sqrtx/ -// discuss: https://leetcode.com/problems/sqrtx/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Newton-Raphson for: root^2 - n = 0 -// Tangent equation: y = 2 * root * x - (root^2 + n) -// Zero point: (root^2 + n) / (2 * root) -impl Solution { - pub fn my_sqrt(x: i32) -> i32 { - let mut size = x; - let mut base = 1; - while size > 1 { - let half = size / 2; - let mid = base + half; - if mid <= x / mid { - base = mid; - } - size -= half; - } - base - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_69() { - assert_eq!(Solution::my_sqrt(8), 2); - assert_eq!(Solution::my_sqrt(16), 4); - assert_eq!(Solution::my_sqrt(17), 4); - assert_eq!(Solution::my_sqrt(81), 9); - assert_eq!(Solution::my_sqrt(82), 9); - assert_eq!(Solution::my_sqrt(100480577), 10024); - assert_eq!(Solution::my_sqrt(100480575), 10023); - assert_eq!(Solution::my_sqrt(100480575), 10023); - assert_eq!(Solution::my_sqrt(80), 8); - assert_eq!(Solution::my_sqrt(2), 1); - } -} diff --git a/src/solution/s0070_climbing_stairs.rs b/src/solution/s0070_climbing_stairs.rs deleted file mode 100644 index 2ef4153b..00000000 --- a/src/solution/s0070_climbing_stairs.rs +++ /dev/null @@ -1,71 +0,0 @@ -/** - * [70] Climbing Stairs - * - * You are climbing a stair case. It takes n steps to reach to the top. - * - * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? - * - * Note: Given n will be a positive integer. - * - * Example 1: - * - * - * Input: 2 - * Output: 2 - * Explanation: There are two ways to climb to the top. - * 1. 1 step + 1 step - * 2. 2 steps - * - * - * Example 2: - * - * - * Input: 3 - * Output: 3 - * Explanation: There are three ways to climb to the top. - * 1. 1 step + 1 step + 1 step - * 2. 1 step + 2 steps - * 3. 2 steps + 1 step - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/climbing-stairs/ -// discuss: https://leetcode.com/problems/climbing-stairs/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Bottom-up DP -impl Solution { - pub fn climb_stairs(n: i32) -> i32 { - let n = n as usize; - if n == 1 { - return 1; - } - if n == 2 { - return 2; - } - let (mut prev, mut curr) = (1, 2); - for i in 2..n { - let next = prev + curr; - prev = curr; - curr = next; - } - curr - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_70() { - assert_eq!(Solution::climb_stairs(3), 3); - assert_eq!(Solution::climb_stairs(4), 5); - assert_eq!(Solution::climb_stairs(5), 8); - } -} diff --git a/src/solution/s0071_simplify_path.rs b/src/solution/s0071_simplify_path.rs deleted file mode 100644 index 4b61f7be..00000000 --- a/src/solution/s0071_simplify_path.rs +++ /dev/null @@ -1,112 +0,0 @@ -/** - * [71] Simplify Path - * - * Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path. - * - * In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix - * - * Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path. - * - * - * - * Example 1: - * - * - * Input: "/home/" - * Output: "/home" - * Explanation: Note that there is no trailing slash after the last directory name. - * - * - * Example 2: - * - * - * Input: "/../" - * Output: "/" - * Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go. - * - * - * Example 3: - * - * - * Input: "/home//foo/" - * Output: "/home/foo" - * Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one. - * - * - * Example 4: - * - * - * Input: "/a/./b/../../c/" - * Output: "/c" - * - * - * Example 5: - * - * - * Input: "/a/../../b/../c//.//" - * Output: "/c" - * - * - * Example 6: - * - * - * Input: "/a//b////c/d//././/.." - * Output: "/a/b/c" - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/simplify-path/ -// discuss: https://leetcode.com/problems/simplify-path/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn simplify_path(path: String) -> String { - let mut stack = Vec::new(); - for s in path.split('/') { - match s { - "." => {} - "/" => {} - "" => {} - ".." => { - stack.pop(); - } - _ => stack.push(s), - } - } - let mut res = String::new(); - for s in stack { - res.push('/'); - res.push_str(s); - } - if res.len() > 0 { - res - } else { - "/".to_owned() - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_71() { - assert_eq!(Solution::simplify_path("/home/".to_owned()), "/home"); - assert_eq!(Solution::simplify_path("/../".to_owned()), "/"); - assert_eq!(Solution::simplify_path("/a/./b/../../c/".to_owned()), "/c"); - assert_eq!( - Solution::simplify_path("/a/../../b/../c//.//".to_owned()), - "/c" - ); - assert_eq!( - Solution::simplify_path("/a//b////c/d//././/..".to_owned()), - "/a/b/c" - ); - } -} diff --git a/src/solution/s0072_edit_distance.rs b/src/solution/s0072_edit_distance.rs deleted file mode 100644 index d50d9fa3..00000000 --- a/src/solution/s0072_edit_distance.rs +++ /dev/null @@ -1,60 +0,0 @@ -/** - * [72] Edit Distance - * - * Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. - * - * You have the following 3 operations permitted on a word: - * - *
    - * Insert a character - * Delete a character - * Replace a character - *
- * - * Example 1: - * - * - * Input: word1 = "horse", word2 = "ros" - * Output: 3 - * Explanation: - * horse -> rorse (replace 'h' with 'r') - * rorse -> rose (remove 'r') - * rose -> ros (remove 'e') - * - * - * Example 2: - * - * - * Input: word1 = "intention", word2 = "execution" - * Output: 5 - * Explanation: - * intention -> inention (remove 't') - * inention -> enention (replace 'i' with 'e') - * enention -> exention (replace 'n' with 'x') - * exention -> exection (replace 'n' with 'c') - * exection -> execution (insert 'u') - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/edit-distance/ -// discuss: https://leetcode.com/problems/edit-distance/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn min_distance(word1: String, word2: String) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_72() {} -} diff --git a/src/solution/s0073_set_matrix_zeroes.rs b/src/solution/s0073_set_matrix_zeroes.rs deleted file mode 100644 index 8d8cdab8..00000000 --- a/src/solution/s0073_set_matrix_zeroes.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [73] Set Matrix Zeroes - * - * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. - * - * Example 1: - * - * - * Input: - * [ - * [1,1,1], - * [1,0,1], - * [1,1,1] - * ] - * Output: - * [ - * [1,0,1], - * [0,0,0], - * [1,0,1] - * ] - * - * - * Example 2: - * - * - * Input: - * [ - * [0,1,2,0], - * [3,4,5,2], - * [1,3,1,5] - * ] - * Output: - * [ - * [0,0,0,0], - * [0,4,5,0], - * [0,3,1,0] - * ] - * - * - * Follow up: - * - * - * A straight forward solution using O(mn) space is probably a bad idea. - * A simple improvement uses O(m + n) space, but still not the best solution. - * Could you devise a constant space solution? - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/set-matrix-zeroes/ -// discuss: https://leetcode.com/problems/set-matrix-zeroes/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn set_zeroes(matrix: &mut Vec>) {} -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_73() {} -} diff --git a/src/solution/s0074_search_a_2d_matrix.rs b/src/solution/s0074_search_a_2d_matrix.rs deleted file mode 100644 index 90975918..00000000 --- a/src/solution/s0074_search_a_2d_matrix.rs +++ /dev/null @@ -1,92 +0,0 @@ -/** - * [74] Search a 2D Matrix - * - * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: - * - * - * Integers in each row are sorted from left to right. - * The first integer of each row is greater than the last integer of the previous row. - * - * - * Example 1: - * - * - * Input: - * matrix = [ - * [1, 3, 5, 7], - * [10, 11, 16, 20], - * [23, 30, 34, 50] - * ] - * target = 3 - * Output: true - * - * - * Example 2: - * - * - * Input: - * matrix = [ - * [1, 3, 5, 7], - * [10, 11, 16, 20], - * [23, 30, 34, 50] - * ] - * target = 13 - * Output: false - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/search-a-2d-matrix/ -// discuss: https://leetcode.com/problems/search-a-2d-matrix/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn search_matrix(matrix: Vec>, target: i32) -> bool { - if matrix.is_empty() { - return false; - } - let (height, width) = (matrix.len(), matrix[0].len()); - if height < 1 || width < 1 { - return false; - } - let mut size = height * width; - let mut base = 0_usize; - while size > 1 { - let half = size / 2; - let mid = base + half; - if target == matrix[mid / width][mid % width] { - return true; - } else if (target > matrix[mid / width][mid % width]) { - base = mid; - } - size -= half; - } - target == matrix[base / width][base % width] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_74() { - assert_eq!( - Solution::search_matrix( - vec![vec![1, 3, 5, 7], vec![10, 11, 16, 20], vec![23, 30, 34, 50]], - 3 - ), - true - ); - assert_eq!( - Solution::search_matrix( - vec![vec![1, 3, 5, 7], vec![10, 11, 16, 20], vec![23, 30, 34, 50]], - 13 - ), - false - ); - } -} diff --git a/src/solution/s0075_sort_colors.rs b/src/solution/s0075_sort_colors.rs deleted file mode 100644 index 6b72ac88..00000000 --- a/src/solution/s0075_sort_colors.rs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * [75] Sort Colors - * - * Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. - * - * Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. - * - * Note: You are not suppose to use the library's sort function for this problem. - * - * Example: - * - * - * Input: [2,0,2,1,1,0] - * Output: [0,0,1,1,2,2] - * - * Follow up: - * - * - * A rather straight forward solution is a two-pass algorithm using counting sort.
- * First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. - * Could you come up with a one-pass algorithm using only constant space? - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/sort-colors/ -// discuss: https://leetcode.com/problems/sort-colors/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// three-way partition -impl Solution { - pub fn sort_colors(nums: &mut Vec) { - if nums.is_empty() { - return; - } - let (mut lower_idx, mut upper_idx) = (0_usize, nums.len() - 1); - let mut i = 0_usize; - while i <= upper_idx { - if nums[i] < 1 { - // lower_idx <= i, we've scanned it so we know nums[lower_idx] <= 1, i++ - nums.swap(lower_idx, i); - i += 1; - lower_idx += 1; - } else if nums[i] > 1 { - nums.swap(upper_idx, i); - if upper_idx < 1 { - break; - } - upper_idx -= 1; - } else { - i += 1; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_75() { - let mut vec = vec![ - 1, 2, 0, 1, 2, 2, 2, 0, 0, 0, 2, 1, 1, 2, 0, 1, 2, 2, 1, 1, 0, - ]; - Solution::sort_colors(&mut vec); - assert_eq!( - vec, - vec![0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2] - ); - - let mut vec = vec![]; - Solution::sort_colors(&mut vec); - assert_eq!(vec, vec![]); - - let mut vec = vec![2, 2, 2]; - Solution::sort_colors(&mut vec); - assert_eq!(vec, vec![2, 2, 2]); - } -} diff --git a/src/solution/s0076_minimum_window_substring.rs b/src/solution/s0076_minimum_window_substring.rs deleted file mode 100644 index 9d190533..00000000 --- a/src/solution/s0076_minimum_window_substring.rs +++ /dev/null @@ -1,56 +0,0 @@ -/** - * [76] Minimum Window Substring - * - * Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). - * - * Example: - * - * - * Input: S = "ADOBECODEBANC", T = "ABC" - * Output: "BANC" - * - * - * Note: - * - * - * If there is no such window in S that covers all characters in T, return the empty string "". - * If there is such window, you are guaranteed that there will always be only one unique minimum window in S. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/minimum-window-substring/ -// discuss: https://leetcode.com/problems/minimum-window-substring/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -use std::collections::HashMap; -impl Solution { - pub fn min_window(s: String, t: String) -> String { - if t.is_empty() || t.len() > s.len() { - return "".to_owned(); - } - let (mut start, mut end) = (0_usize, 0_usize); - let mut result = (0_usize, 0_usize); - loop {} - s[result.0..result.1].to_owned() - } - - fn count_char(s: String) -> HashMap { - let mut res = HashMap::new(); - for ch in s.chars().into_iter() { - *res.entry(ch).or_insert(0) += 1; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_76() {} -} diff --git a/src/solution/s0077_combinations.rs b/src/solution/s0077_combinations.rs deleted file mode 100644 index 6bb10d6b..00000000 --- a/src/solution/s0077_combinations.rs +++ /dev/null @@ -1,77 +0,0 @@ -/** - * [77] Combinations - * - * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. - * - * Example: - * - * - * Input: n = 4, k = 2 - * Output: - * [ - * [2,4], - * [3,4], - * [2,3], - * [1,2], - * [1,3], - * [1,4], - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/combinations/ -// discuss: https://leetcode.com/problems/combinations/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn combine(n: i32, k: i32) -> Vec> { - let mut res: Vec> = Vec::new(); - Solution::backtrack(1, n, k, vec![], &mut res); - res - } - - fn backtrack(start: i32, end: i32, k: i32, curr: Vec, result: &mut Vec>) { - if k < 1 { - result.push(curr); - return; - } - if end - start + 1 < k { - // elements is not enough, return quickly - return; - } - for i in start..end + 1 { - let mut vec = curr.clone(); - vec.push(i); - Solution::backtrack(i + 1, end, k - 1, vec, result); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_77() { - assert_eq!( - Solution::combine(4, 2), - vec![ - vec![1, 2], - vec![1, 3], - vec![1, 4], - vec![2, 3], - vec![2, 4], - vec![3, 4] - ] - ); - assert_eq!(Solution::combine(1, 1), vec![vec![1]]); - let empty: Vec> = vec![]; - assert_eq!(Solution::combine(0, 1), empty); - assert_eq!(Solution::combine(2, 1), vec![vec![1], vec![2]]); - } -} diff --git a/src/solution/s0078_subsets.rs b/src/solution/s0078_subsets.rs deleted file mode 100644 index 2db34925..00000000 --- a/src/solution/s0078_subsets.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [78] Subsets - * - * Given a set of distinct integers, nums, return all possible subsets (the power set). - * - * Note: The solution set must not contain duplicate subsets. - * - * Example: - * - * - * Input: nums = [1,2,3] - * Output: - * [ - * [3], - * [1], - * [2], - * [1,2,3], - * [1,3], - * [2,3], - * [1,2], - * [] - * ] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/subsets/ -// discuss: https://leetcode.com/problems/subsets/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn subsets(nums: Vec) -> Vec> { - let mut res = Vec::new(); - Solution::backtrack(0, vec![], &nums, &mut res); - res - } - - fn backtrack(start: usize, mut curr: Vec, nums: &Vec, result: &mut Vec>) { - if start >= nums.len() { - result.push(curr); - return; - } - // current element dropped - Solution::backtrack(start + 1, curr.clone(), nums, result); - // current element picked - curr.push(nums[start]); - Solution::backtrack(start + 1, curr, nums, result); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_78() { - assert_eq!(Solution::subsets(vec![]), vec![vec![]]); - assert_eq!(Solution::subsets(vec![1]), vec![vec![], vec![1]]); - assert_eq!( - Solution::subsets(vec![1, 2]), - vec![vec![], vec![2], vec![1], vec![1, 2]] - ); - } -} diff --git a/src/solution/s0079_word_search.rs b/src/solution/s0079_word_search.rs deleted file mode 100644 index 07c4a705..00000000 --- a/src/solution/s0079_word_search.rs +++ /dev/null @@ -1,133 +0,0 @@ -/** - * [79] Word Search - * - * Given a 2D board and a word, find if the word exists in the grid. - * - * The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. - * - * Example: - * - * - * board = - * [ - * ['A','B','C','E'], - * ['S','F','C','S'], - * ['A','D','E','E'] - * ] - * - * Given word = "ABCCED", return true. - * Given word = "SEE", return true. - * Given word = "ABCB", return false. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-search/ -// discuss: https://leetcode.com/problems/word-search/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: use HashSet to record visited pos -impl Solution { - pub fn exist(board: Vec>, word: String) -> bool { - if board.is_empty() || word.len() < 1 { - return false; - } - let (height, width) = (board.len(), board[0].len()); - if height < 1 || width < 1 { - return false; - } - let seq: Vec = word.chars().collect(); - - for i in 0..height * width { - if Solution::dfs( - i / width, - i % width, - &seq[..], - &board, - vec![], - height, - width, - ) { - return true; - } - } - false - } - - fn dfs( - x: usize, - y: usize, - seq: &[char], - board: &Vec>, - mut visited: Vec<(usize, usize)>, - height: usize, - width: usize, - ) -> bool { - if seq[0] != board[x][y] { - return false; - } - if seq.len() < 2 { - return true; - } - visited.push((x, y)); - return (x > 0 - && !visited.contains(&(x - 1, y)) - && Solution::dfs(x - 1, y, &seq[1..], board, visited.clone(), height, width)) - || (x + 1 < height - && !visited.contains(&(x + 1, y)) - && Solution::dfs(x + 1, y, &seq[1..], board, visited.clone(), height, width)) - || (y > 0 - && !visited.contains(&(x, y - 1)) - && Solution::dfs(x, y - 1, &seq[1..], board, visited.clone(), height, width)) - || (y + 1 < width - && !visited.contains(&(x, y + 1)) - && Solution::dfs(x, y + 1, &seq[1..], board, visited.clone(), height, width)); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_79() { - assert_eq!(Solution::exist(vec![vec!['a']], "a".to_owned()), true); - assert_eq!( - Solution::exist( - vec![ - vec!['A', 'B', 'C', 'E'], - vec!['S', 'F', 'C', 'S'], - vec!['A', 'D', 'E', 'E'], - ], - "ABCCED".to_owned() - ), - true - ); - assert_eq!( - Solution::exist( - vec![ - vec!['A', 'B', 'C', 'E'], - vec!['S', 'F', 'C', 'S'], - vec!['A', 'D', 'E', 'E'], - ], - "SEE".to_owned() - ), - true - ); - assert_eq!( - Solution::exist( - vec![ - vec!['A', 'B', 'C', 'E'], - vec!['S', 'F', 'C', 'S'], - vec!['A', 'D', 'E', 'E'], - ], - "ABCB".to_owned() - ), - false - ); - } -} diff --git a/src/solution/s0080_remove_duplicates_from_sorted_array_ii.rs b/src/solution/s0080_remove_duplicates_from_sorted_array_ii.rs deleted file mode 100644 index 70b3cf82..00000000 --- a/src/solution/s0080_remove_duplicates_from_sorted_array_ii.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [80] Remove Duplicates from Sorted Array II - * - * Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. - * - * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. - * - * Example 1: - * - * - * Given nums = [1,1,1,2,2,3], - * - * Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. - * - * It doesn't matter what you leave beyond the returned length. - * - * Example 2: - * - * - * Given nums = [0,0,1,1,1,1,2,3,3], - * - * Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively. - * - * It doesn't matter what values are set beyond the returned length. - * - * - * Clarification: - * - * Confused why the returned value is an integer but your answer is an array? - * - * Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. - * - * Internally you can think of this: - * - * - * // nums is passed in by reference. (i.e., without making a copy) - * int len = removeDuplicates(nums); - * - * // any modification to nums in your function would be known by the caller. - * // using the length returned by your function, it prints the first len elements. - * for (int i = 0; i < len; i++) { - * print(nums[i]); - * } - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ -// discuss: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn remove_duplicates(nums: &mut Vec) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_80() {} -} diff --git a/src/solution/s0081_search_in_rotated_sorted_array_ii.rs b/src/solution/s0081_search_in_rotated_sorted_array_ii.rs deleted file mode 100644 index 7972a16f..00000000 --- a/src/solution/s0081_search_in_rotated_sorted_array_ii.rs +++ /dev/null @@ -1,52 +0,0 @@ -/** - * [81] Search in Rotated Sorted Array II - * - * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. - * - * (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). - * - * You are given a target value to search. If found in the array return true, otherwise return false. - * - * Example 1: - * - * - * Input: nums = [2,5,6,0,0,1,2], target = 0 - * Output: true - * - * - * Example 2: - * - * - * Input: nums = [2,5,6,0,0,1,2], target = 3 - * Output: false - * - * Follow up: - * - * - * This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates. - * Would this affect the run-time complexity? How and why? - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ -// discuss: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn search(nums: Vec, target: i32) -> bool { - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_81() {} -} diff --git a/src/solution/s0082_remove_duplicates_from_sorted_list_ii.rs b/src/solution/s0082_remove_duplicates_from_sorted_list_ii.rs deleted file mode 100644 index 067d0c79..00000000 --- a/src/solution/s0082_remove_duplicates_from_sorted_list_ii.rs +++ /dev/null @@ -1,59 +0,0 @@ -/** - * [82] Remove Duplicates from Sorted List II - * - * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. - * - * Example 1: - * - * - * Input: 1->2->3->3->4->4->5 - * Output: 1->2->5 - * - * - * Example 2: - * - * - * Input: 1->1->1->2->3 - * Output: 2->3 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ -// discuss: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn delete_duplicates(head: Option>) -> Option> { - None - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_82() {} -} diff --git a/src/solution/s0083_remove_duplicates_from_sorted_list.rs b/src/solution/s0083_remove_duplicates_from_sorted_list.rs deleted file mode 100644 index 5c9552cc..00000000 --- a/src/solution/s0083_remove_duplicates_from_sorted_list.rs +++ /dev/null @@ -1,59 +0,0 @@ -/** - * [83] Remove Duplicates from Sorted List - * - * Given a sorted linked list, delete all duplicates such that each element appear only once. - * - * Example 1: - * - * - * Input: 1->1->2 - * Output: 1->2 - * - * - * Example 2: - * - * - * Input: 1->1->2->3->3 - * Output: 1->2->3 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/remove-duplicates-from-sorted-list/ -// discuss: https://leetcode.com/problems/remove-duplicates-from-sorted-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn delete_duplicates(head: Option>) -> Option> { - None - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_83() {} -} diff --git a/src/solution/s0084_largest_rectangle_in_histogram.rs b/src/solution/s0084_largest_rectangle_in_histogram.rs deleted file mode 100644 index d33b9bda..00000000 --- a/src/solution/s0084_largest_rectangle_in_histogram.rs +++ /dev/null @@ -1,91 +0,0 @@ -/** - * [84] Largest Rectangle in Histogram - * - * Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. - * - * - * - *
- * Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. - * - * - * - *
- * The largest rectangle is shown in the shaded area, which has area = 10 unit. - * - * - * - * Example: - * - * - * Input: [2,1,5,6,2,3] - * Output: 10 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/largest-rectangle-in-histogram/ -// discuss: https://leetcode.com/problems/largest-rectangle-in-histogram/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// record the height and start position using 2 stack, thus we reuse the previously scanned information -impl Solution { - pub fn largest_rectangle_area(heights: Vec) -> i32 { - let mut positions = Vec::new(); - let mut hs = Vec::new(); - let mut max_area = 0; - let len = heights.len(); - for (i, h) in heights.into_iter().enumerate() { - let mut last_pop = None; - while hs.last().is_some() && *hs.last().unwrap() >= h { - max_area = i32::max( - max_area, - hs.last().unwrap() * ((i - positions.last().unwrap()) as i32), - ); - hs.pop(); - last_pop = positions.pop(); - } - if last_pop.is_some() { - positions.push(last_pop.unwrap()); - } else { - positions.push(i); - } - hs.push(h); - } - // drain stack - while !hs.is_empty() { - max_area = i32::max( - max_area, - hs.last().unwrap() * ((len - positions.last().unwrap()) as i32), - ); - positions.pop(); - hs.pop(); - } - max_area - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_84() { - assert_eq!(Solution::largest_rectangle_area(vec![2, 1, 5, 6, 2, 3]), 10); - assert_eq!( - Solution::largest_rectangle_area(vec![1, 1, 1, 1, 1, 1, 1, 1]), - 8 - ); - assert_eq!(Solution::largest_rectangle_area(vec![2, 2]), 4); - assert_eq!( - Solution::largest_rectangle_area(vec![1, 2, 8, 8, 2, 2, 1]), - 16 - ); - assert_eq!(Solution::largest_rectangle_area(vec![2, 1, 2]), 3); - assert_eq!(Solution::largest_rectangle_area(vec![1, 3, 2, 1, 2]), 5); - } -} diff --git a/src/solution/s0085_maximal_rectangle.rs b/src/solution/s0085_maximal_rectangle.rs deleted file mode 100644 index 6dbf2951..00000000 --- a/src/solution/s0085_maximal_rectangle.rs +++ /dev/null @@ -1,43 +0,0 @@ -/** - * [85] Maximal Rectangle - * - * Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. - * - * Example: - * - * - * Input: - * [ - * ["1","0","1","0","0"], - * ["1","0","1","1","1"], - * ["1","1","1","1","1"], - * ["1","0","0","1","0"] - * ] - * Output: 6 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/maximal-rectangle/ -// discuss: https://leetcode.com/problems/maximal-rectangle/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn maximal_rectangle(matrix: Vec>) -> i32 { - let mut max_area = 0; - - max_area - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_85() {} -} diff --git a/src/solution/s0086_partition_list.rs b/src/solution/s0086_partition_list.rs deleted file mode 100644 index 1f4952dd..00000000 --- a/src/solution/s0086_partition_list.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [86] Partition List - * - * Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. - * - * You should preserve the original relative order of the nodes in each of the two partitions. - * - * Example: - * - * - * Input: head = 1->4->3->2->5->2, x = 3 - * Output: 1->2->2->4->3->5 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/partition-list/ -// discuss: https://leetcode.com/problems/partition-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn partition(head: Option>, x: i32) -> Option> { - let mut lower = Some(Box::new(ListNode::new(0))); - let mut higher = Some(Box::new(ListNode::new(0))); - let mut lower_tail = lower.as_mut(); - let mut higher_tail = higher.as_mut(); - let mut head = head; - while let Some(mut inner) = head { - let mut next = inner.next.take(); - if inner.val < x { - lower_tail.as_mut().unwrap().next = Some(inner); - lower_tail = lower_tail.unwrap().next.as_mut(); - } else { - higher_tail.as_mut().unwrap().next = Some(inner); - higher_tail = higher_tail.unwrap().next.as_mut(); - } - head = next - } - lower_tail.as_mut().unwrap().next = higher.unwrap().next.take(); - lower.unwrap().next.take() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_86() { - assert_eq!( - Solution::partition(linked![1, 4, 3, 2, 5, 2], 3), - linked![1, 2, 2, 4, 3, 5] - ); - assert_eq!( - Solution::partition(linked![1, 4, 3, 2, 5, 2], 8), - linked![1, 4, 3, 2, 5, 2] - ); - assert_eq!(Solution::partition(linked![], 0), linked![]); - } -} diff --git a/src/solution/s0087_scramble_string.rs b/src/solution/s0087_scramble_string.rs deleted file mode 100644 index 19b47dc0..00000000 --- a/src/solution/s0087_scramble_string.rs +++ /dev/null @@ -1,85 +0,0 @@ -/** - * [87] Scramble String - * - * Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. - * - * Below is one possible representation of s1 = "great": - * - * - * great - * / \ - * gr eat - * / \ / \ - * g r e at - * / \ - * a t - * - * - * To scramble the string, we may choose any non-leaf node and swap its two children. - * - * For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". - * - * - * rgeat - * / \ - * rg eat - * / \ / \ - * r g e at - * / \ - * a t - * - * - * We say that "rgeat" is a scrambled string of "great". - * - * Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae". - * - * - * rgtae - * / \ - * rg tae - * / \ / \ - * r g ta e - * / \ - * t a - * - * - * We say that "rgtae" is a scrambled string of "great". - * - * Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. - * - * Example 1: - * - * - * Input: s1 = "great", s2 = "rgeat" - * Output: true - * - * - * Example 2: - * - * - * Input: s1 = "abcde", s2 = "caebd" - * Output: false - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/scramble-string/ -// discuss: https://leetcode.com/problems/scramble-string/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_scramble(s1: String, s2: String) -> bool { - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_87() {} -} diff --git a/src/solution/s0088_merge_sorted_array.rs b/src/solution/s0088_merge_sorted_array.rs deleted file mode 100644 index bdcc2a1a..00000000 --- a/src/solution/s0088_merge_sorted_array.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [88] Merge Sorted Array - * - * Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. - * - * Note: - * - * - * The number of elements initialized in nums1 and nums2 are m and n respectively. - * You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. - * - * - * Example: - * - * - * Input: - * nums1 = [1,2,3,0,0,0], m = 3 - * nums2 = [2,5,6], n = 3 - * - * Output: [1,2,2,3,5,6] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/merge-sorted-array/ -// discuss: https://leetcode.com/problems/merge-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn merge(nums1: &mut Vec, m: i32, nums2: &mut Vec, n: i32) { - let mut i = m - 1; - let mut j = n - 1; - let mut z = m + n - 1; - while z >= 0 { - if i >= 0 && (j < 0 || nums1[i as usize] >= nums2[j as usize]) { - nums1[z as usize] = nums1[i as usize]; - i -= 1; - } else { - nums1[z as usize] = nums2[j as usize]; - j -= 1; - } - z -= 1; - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_88() { - let mut vec1 = vec![1, 2, 3, 0, 0, 0]; - let mut vec2 = vec![2, 5, 6]; - Solution::merge(&mut vec1, 3, &mut vec2, 3); - assert_eq!(vec1, vec![1, 2, 2, 3, 5, 6]); - - let mut vec1 = vec![1, 2, 3]; - let mut vec2 = vec![]; - Solution::merge(&mut vec1, 3, &mut vec2, 0); - assert_eq!(vec1, vec![1, 2, 3]); - - let mut vec1 = vec![0, 0, 0]; - let mut vec2 = vec![1, 2, 3]; - Solution::merge(&mut vec1, 0, &mut vec2, 3); - assert_eq!(vec1, vec![1, 2, 3]); - } -} diff --git a/src/solution/s0089_gray_code.rs b/src/solution/s0089_gray_code.rs deleted file mode 100644 index 039283eb..00000000 --- a/src/solution/s0089_gray_code.rs +++ /dev/null @@ -1,82 +0,0 @@ -/** - * [89] Gray Code - * - * The gray code is a binary numeral system where two successive values differ in only one bit. - * - * Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. - * - * Example 1: - * - * - * Input: 2 - * Output: [0,1,3,2] - * Explanation: - * 00 - 0 - * 01 - 1 - * 11 - 3 - * 10 - 2 - * - * For a given n, a gray code sequence may not be uniquely defined. - * For example, [0,2,3,1] is also a valid gray code sequence. - * - * 00 - 0 - * 10 - 2 - * 11 - 3 - * 01 - 1 - * - * - * Example 2: - * - * - * Input: 0 - * Output: [0] - * Explanation: We define the gray code sequence to begin with 0. - * A gray code sequence of n has size = 2^n, which for n = 0 the size is 2^0 = 1. - * Therefore, for n = 0 the gray code sequence is [0]. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/gray-code/ -// discuss: https://leetcode.com/problems/gray-code/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -0000 -0001 <- flip [0] to 1, traverse [] in reverse order -0011 <- flip [1] to 1, traverse [0] in reverse order -0010 -0110 <- flip [2] to 1, traverse [1,0] in reverse order -0111 -0101 -0100 -1100 <- flip [3] to 1, traverse [2,1,0] in reverse order - */ -impl Solution { - pub fn gray_code(n: i32) -> Vec { - let mut res = vec![0]; - for i in 0..n { - for j in (0..res.len()).rev() { - res.push(2_i32.pow(i as u32) + res[j]); - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_89() { - assert_eq!(Solution::gray_code(2), vec![0, 1, 3, 2]); - assert_eq!(Solution::gray_code(1), vec![0, 1]); - assert_eq!(Solution::gray_code(0), vec![0]); - assert_eq!(Solution::gray_code(3), vec![0, 1, 3, 2, 6, 7, 5, 4]); - } -} diff --git a/src/solution/s0090_subsets_ii.rs b/src/solution/s0090_subsets_ii.rs deleted file mode 100644 index e859e2d1..00000000 --- a/src/solution/s0090_subsets_ii.rs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * [90] Subsets II - * - * Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). - * - * Note: The solution set must not contain duplicate subsets. - * - * Example: - * - * - * Input: [1,2,2] - * Output: - * [ - * [2], - * [1], - * [1,2,2], - * [2,2], - * [1,2], - * [] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/subsets-ii/ -// discuss: https://leetcode.com/problems/subsets-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -count the repeats of each number, -then in backtracking, each number can be picked up for 0..repeat times - -using BTreeMap to preserve order (easy for test) -*/ -use std::collections::BTreeMap; -impl Solution { - pub fn subsets_with_dup(nums: Vec) -> Vec> { - let mut res = Vec::new(); - let nums = nums - .into_iter() - .fold(BTreeMap::new(), |mut map, v| { - *map.entry(v).or_insert(0) += 1; - map - }) - .into_iter() - .collect::>(); - Solution::backtrack(0, vec![], &nums, &mut res); - res - } - - fn backtrack( - start: usize, - mut curr: Vec, - nums: &Vec<(i32, i32)>, - result: &mut Vec>, - ) { - if start >= nums.len() { - result.push(curr); - return; - } - for repeat in 0..nums[start].1 + 1 { - let mut inner = curr.clone(); - for _ in 0..repeat { - inner.push(nums[start].0); - } - Solution::backtrack(start + 1, inner, nums, result); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_90() { - assert_eq!( - Solution::subsets_with_dup(vec![1, 2, 2]), - vec![ - vec![], - vec![2], - vec![2, 2], - vec![1], - vec![1, 2], - vec![1, 2, 2], - ] - ); - assert_eq!(Solution::subsets_with_dup(vec![1]), vec![vec![], vec![1],]); - assert_eq!(Solution::subsets_with_dup(vec![]), vec![vec![],]); - } -} diff --git a/src/solution/s0091_decode_ways.rs b/src/solution/s0091_decode_ways.rs deleted file mode 100644 index bbecc932..00000000 --- a/src/solution/s0091_decode_ways.rs +++ /dev/null @@ -1,52 +0,0 @@ -/** - * [91] Decode Ways - * - * A message containing letters from A-Z is being encoded to numbers using the following mapping: - * - * - * 'A' -> 1 - * 'B' -> 2 - * ... - * 'Z' -> 26 - * - * - * Given a non-empty string containing only digits, determine the total number of ways to decode it. - * - * Example 1: - * - * - * Input: "12" - * Output: 2 - * Explanation: It could be decoded as "AB" (1 2) or "L" (12). - * - * - * Example 2: - * - * - * Input: "226" - * Output: 3 - * Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/decode-ways/ -// discuss: https://leetcode.com/problems/decode-ways/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn num_decodings(s: String) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_91() {} -} diff --git a/src/solution/s0092_reverse_linked_list_ii.rs b/src/solution/s0092_reverse_linked_list_ii.rs deleted file mode 100644 index 318c0d15..00000000 --- a/src/solution/s0092_reverse_linked_list_ii.rs +++ /dev/null @@ -1,54 +0,0 @@ -/** - * [92] Reverse Linked List II - * - * Reverse a linked list from position m to n. Do it in one-pass. - * - * Note: 1 ≤ m ≤ n ≤ length of list. - * - * Example: - * - * - * Input: 1->2->3->4->5->NULL, m = 2, n = 4 - * Output: 1->4->3->2->5->NULL - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/reverse-linked-list-ii/ -// discuss: https://leetcode.com/problems/reverse-linked-list-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn reverse_between(head: Option>, m: i32, n: i32) -> Option> { - None - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_92() {} -} diff --git a/src/solution/s0093_restore_ip_addresses.rs b/src/solution/s0093_restore_ip_addresses.rs deleted file mode 100644 index 5c2706b4..00000000 --- a/src/solution/s0093_restore_ip_addresses.rs +++ /dev/null @@ -1,35 +0,0 @@ -/** - * [93] Restore IP Addresses - * - * Given a string containing only digits, restore it by returning all possible valid IP address combinations. - * - * Example: - * - * - * Input: "25525511135" - * Output: ["255.255.11.135", "255.255.111.35"] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/restore-ip-addresses/ -// discuss: https://leetcode.com/problems/restore-ip-addresses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn restore_ip_addresses(s: String) -> Vec { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_93() {} -} diff --git a/src/solution/s0094_binary_tree_inorder_traversal.rs b/src/solution/s0094_binary_tree_inorder_traversal.rs deleted file mode 100644 index 01afb57a..00000000 --- a/src/solution/s0094_binary_tree_inorder_traversal.rs +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [94] Binary Tree Inorder Traversal - * - * Given a binary tree, return the inorder traversal of its nodes' values. - * - * Example: - * - * - * Input: [1,null,2,3] - * 1 - * \ - * 2 - * / - * 3 - * - * Output: [1,3,2] - * - * Follow up: Recursive solution is trivial, could you do it iteratively? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/binary-tree-inorder-traversal/ -// discuss: https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use crate::util::tree::{to_tree, TreeNode}; -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn inorder_traversal(root: Option>>) -> Vec { - let mut res = Vec::new(); - Solution::inorder_traverse(root.as_ref(), &mut (|v| res.push(v))); - res - } - - fn inorder_traverse(root: Option<&Rc>>, consumer: &mut F) { - if let Some(node) = root { - Solution::inorder_traverse(node.borrow().left.as_ref(), consumer); - consumer(root.as_ref().unwrap().borrow().val); - Solution::inorder_traverse(node.borrow().right.as_ref(), consumer); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_94() { - assert_eq!( - Solution::inorder_traversal(tree![1, null, 2, 3]), - vec![1, 3, 2] - ); - assert_eq!( - Solution::inorder_traversal(tree![1, 2, 3, 4, 5, 6, 7]), - vec![4, 2, 5, 1, 6, 3, 7] - ); - } -} diff --git a/src/solution/s0095_unique_binary_search_trees_ii.rs b/src/solution/s0095_unique_binary_search_trees_ii.rs deleted file mode 100644 index 1f75639d..00000000 --- a/src/solution/s0095_unique_binary_search_trees_ii.rs +++ /dev/null @@ -1,89 +0,0 @@ -/** - * [95] Unique Binary Search Trees II - * - * Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. - * - * Example: - * - * - * Input: 3 - * Output: - * [ - * [1,null,3,2], - * [3,2,null,1], - * [3,1,null,null,2], - * [2,1,3], - * [1,null,2,null,3] - * ] - * Explanation: - * The above output corresponds to the 5 unique BST's shown below: - * - * 1 3 3 2 1 - * \ / / / \ \ - * 3 2 1 1 3 2 - * / / \ \ - * 2 1 2 3 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/unique-binary-search-trees-ii/ -// discuss: https://leetcode.com/problems/unique-binary-search-trees-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* - 1 - - 1 2 - \ / - 2 1 - - 1 3 3 2 1 - \ / / / \ \ - 3 2 1 1 3 2 - / / \ \ - 2 1 2 3 - - 4 1 - / \ -(5*) 3 - / \ - 2 4 - */ -use crate::util::tree::{to_tree, TreeNode}; -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn generate_trees(n: i32) -> Vec>>> { - if n < 1 { - return vec![]; - } - let mut res = vec![Some(Rc::new(RefCell::new(TreeNode::new(1))))]; - for val in 2..n + 1 { - let mut next = Vec::new(); - for root in res.into_iter() { - let mut dummy = Some(Rc::new(RefCell::new(TreeNode { - val: 0, - left: None, - right: None, - }))); - let mut parent = dummy.as_ref().unwrap().clone(); - let mut node = root; - // we know that val is larger than all the elements in the tree - } - res = next; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_95() {} -} diff --git a/src/solution/s0096_unique_binary_search_trees.rs b/src/solution/s0096_unique_binary_search_trees.rs deleted file mode 100644 index 4f64c26c..00000000 --- a/src/solution/s0096_unique_binary_search_trees.rs +++ /dev/null @@ -1,43 +0,0 @@ -/** - * [96] Unique Binary Search Trees - * - * Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? - * - * Example: - * - * - * Input: 3 - * Output: 5 - * Explanation: - * Given n = 3, there are a total of 5 unique BST's: - * - * 1 3 3 2 1 - * \ / / / \ \ - * 3 2 1 1 3 2 - * / / \ \ - * 2 1 2 3 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/unique-binary-search-trees/ -// discuss: https://leetcode.com/problems/unique-binary-search-trees/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn num_trees(n: i32) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_96() {} -} diff --git a/src/solution/s0097_interleaving_string.rs b/src/solution/s0097_interleaving_string.rs deleted file mode 100644 index 8d69d851..00000000 --- a/src/solution/s0097_interleaving_string.rs +++ /dev/null @@ -1,115 +0,0 @@ -/** - * [97] Interleaving String - * - * Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. - * - * Example 1: - * - * - * Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" - * Output: true - * - * - * Example 2: - * - * - * Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" - * Output: false - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/interleaving-string/ -// discuss: https://leetcode.com/problems/interleaving-string/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// DFS with memorization -/* -思路: DFS, 三个指针 i,j,k 分别指向 s1, s2, s3 已经消费到的 char 位置, 下一个可以走的路径是 s3 当前消费到的 char 值 - -如 aaaaaas aaaaaaaw aaaaaaaaaaaaaasw -那么第一步可以从 s1 或 s2 取一个 char, 用 DFS 的方式搜索整个解空间 - -优化: 直接 DFS 非常慢, 还是上面的例子, 最差情况是大量重复字符, 时间复杂度直接是 2^(M+N), 优化方式借鉴 DP 经常用到的 -memorize, 使用一个二维数组缓存每一对遍历过的 i,j 最后是否能产生合法的 interleaving. - -优化后通过缓存剪除的路径比较难分析, 但很显然能知道最差情况也只需要将所有 M*N 的组合进行标记, 因此最差时间复杂度 O(M*N) -空间复杂度 O(M*N) -*/ - -impl Solution { - pub fn is_interleave(s1: String, s2: String, s3: String) -> bool { - let mut cache = vec![vec![false; s2.len() + 1]; s1.len() + 1]; - Solution::dfs( - &s1.chars().collect(), - &s2.chars().collect(), - &s3.chars().collect(), - 0, - 0, - 0, - &mut cache, - ) - } - - fn dfs( - s1: &Vec, - s2: &Vec, - s3: &Vec, - i: usize, - j: usize, - k: usize, - invalid: &mut Vec>, - ) -> bool { - if invalid[i][j] { - return false; - } - if i == s1.len() && j == s2.len() && k == s3.len() { - return true; - } - let valid = (i < s1.len() - && k < s3.len() - && s1[i] == s3[k] - && Solution::dfs(s1, s2, s3, i + 1, j, k + 1, invalid)) - || (j < s2.len() - && k < s3.len() - && s2[j] == s3[k] - && Solution::dfs(s1, s2, s3, i, j + 1, k + 1, invalid)); - if !valid { - invalid[i][j] = true - } - valid - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_97() { - assert_eq!( - Solution::is_interleave( - "aabcc".to_owned(), - "dbbca".to_owned(), - "aadbbcbcac".to_owned() - ), - true - ); - assert_eq!( - Solution::is_interleave( - "aabcc".to_owned(), - "dbbca".to_owned(), - "aadbbbaccc".to_owned() - ), - false - ); - assert_eq!( - Solution::is_interleave("a".to_owned(), "b".to_owned(), "a".to_owned()), - false - ); - } -} diff --git a/src/solution/s0098_validate_binary_search_tree.rs b/src/solution/s0098_validate_binary_search_tree.rs deleted file mode 100644 index 09098c18..00000000 --- a/src/solution/s0098_validate_binary_search_tree.rs +++ /dev/null @@ -1,97 +0,0 @@ -/** - * [98] Validate Binary Search Tree - * - * Given a binary tree, determine if it is a valid binary search tree (BST). - * - * Assume a BST is defined as follows: - * - * - * The left subtree of a node contains only nodes with keys less than the node's key. - * The right subtree of a node contains only nodes with keys greater than the node's key. - * Both the left and right subtrees must also be binary search trees. - * - * - * Example 1: - * - * - * Input: - * 2 - * / \ - * 1 3 - * Output: true - * - * - * Example 2: - * - * - * 5 - * / \ - * 1 4 - * / \ - * 3 6 - * Output: false - * Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value - * is 5 but its right child's value is 4. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/validate-binary-search-tree/ -// discuss: https://leetcode.com/problems/validate-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for a binary tree node. -use crate::util::tree::{to_tree, TreeNode}; - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn is_valid_bst(root: Option>>) -> bool { - let mut vec = vec![]; - Solution::preorder_traverse(root.as_ref(), &mut vec) - } - - fn preorder_traverse( - root: Option<&Rc>>, - formers: &mut Vec<(i32, i32)>, - ) -> bool { - if let Some(node) = root { - let root_val = root.as_ref().unwrap().borrow().val; - for former in formers.iter() { - if (former.0 < 0 && root_val >= former.1) || (former.0 > 0 && root_val <= former.1) - { - return false; - } - } - let mut to_right = formers.clone(); - formers.push((-1, root_val)); - to_right.push((1, root_val)); - Solution::preorder_traverse(node.borrow().left.as_ref(), formers) - && Solution::preorder_traverse(node.borrow().right.as_ref(), &mut to_right) - } else { - true - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_98() { - assert_eq!( - Solution::is_valid_bst(tree![5, 1, 4, null, null, 3, 6]), - false - ); - assert_eq!(Solution::is_valid_bst(tree![2, 1, 3]), true); - assert_eq!( - Solution::is_valid_bst(tree![10, 5, 15, null, null, 6, 20]), - false - ); - } -} diff --git a/src/solution/s0099_recover_binary_search_tree.rs b/src/solution/s0099_recover_binary_search_tree.rs deleted file mode 100644 index 2401231a..00000000 --- a/src/solution/s0099_recover_binary_search_tree.rs +++ /dev/null @@ -1,162 +0,0 @@ -/** - * [99] Recover Binary Search Tree - * - * Two elements of a binary search tree (BST) are swapped by mistake. - * - * Recover the tree without changing its structure. - * - * Example 1: - * - * - * Input: [1,3,null,null,2] - * - * 1 - * / - * 3 - * \ - * 2 - * - * Output: [3,1,null,null,2] - * - * 3 - * / - * 1 - * \ - * 2 - * - * - * Example 2: - * - * - * Input: [3,1,4,null,null,2] - * - * 3 - * / \ - * 1 4 - * / - * 2 - * - * Output: [2,1,4,null,null,3] - * - * 2 - * / \ - * 1 4 - * / - * 3 - * - * - * Follow up: - * - * - * A solution using O(n) space is pretty straight forward. - * Could you devise a constant space solution? - * - * - */ -pub struct Solution {} - -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/recover-binary-search-tree/ -// discuss: https://leetcode.com/problems/recover-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -基本思路: 对 root, 收集左右两侧的节点值: - - - 右侧有值小于 root, 左侧有值大于 root: 交换这两个值 - - 一侧有值不合法, 另一侧合法: 交换不合法的值与 root - - 两侧都合法: 递归对左右子树进行上述操作 - -直接使用上述思路会重复迭代子树, 因此可以先用一次中序遍历, 将值的分布记录在数组中, 之后可以用 O(1) 的时间得到某个 node 两侧的值分布 - -这种办法的时间空间复杂度都是 O(N) - -原题中的 follow up 部分提出可以想一个常数空间复杂度的算法, 因此可以继续优化. - -最开始的办法会重复迭代子树是因为 Top-down, 可以尝试一下 Bottom-up 能不能解决问题: - -- 后序遍历递归校验每个 node 是否合法 -- 假如 node 合法, 那么只需要把这个子树中的最大值和最小值返回到上一个层级来帮助判断上一个层级的子树是否合法即可, 无需记录这个子树的所有值 -- 假如 node 不合法, 按最开始的办法进行处理, 除非... -- 只有一侧值不合法, 这时候由于是 Bottom-up, 不能直接交换不合法的值与 root, 而要判断交换后能否合法(Top-down 的办法中由于题目给定了有且仅有 swap 一次, 因此与 root 交换必然是合法的) - -这个办法时间复杂度 O(N), 空间 O(1). 题解就用 Bottom-up 来写. - */ -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn recover_tree(root: &mut Option>>) { - Solution::recover_helper(root.as_ref()); - } - - fn recover_helper( - root: Option<&Rc>>, - ) -> ( - Option>>, - Option>>, - bool, - ) { - if let Some(node) = root { - let (l_min, l_max, l_flag) = Solution::recover_helper(node.borrow().left.as_ref()); - let (r_min, r_max, r_flag) = Solution::recover_helper(node.borrow().right.as_ref()); - // we've already find a swap, return quickly - if l_flag || r_flag { - return (None, None, true); - } - let root_val = node.borrow().val; - let l_err = l_max.as_ref().map_or(false, |v| v.borrow().val > root_val); - let r_err = r_min.as_ref().map_or(false, |v| v.borrow().val < root_val); - // invalid sub-tree found, do swap - if l_err || r_err { - if l_err && r_err { - } else if l_err { - std::mem::swap( - &mut l_max.unwrap().borrow_mut().val, - &mut node.borrow_mut().val, - ); - } else if r_err { - std::mem::swap( - &mut r_min.unwrap().borrow_mut().val, - &mut node.borrow_mut().val, - ) - } - return (None, None, true); - } - ( - if l_min.is_some() { - l_min - } else { - Some(node.clone()) - }, - if r_max.is_some() { - r_max - } else { - Some(node.clone()) - }, - false, - ) - } else { - (None, None, false) - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_99() { - let mut tree = tree![3, 1, 4, null, null, 2]; - Solution::recover_tree(&mut tree); - assert_eq!(tree, tree![2, 1, 4, null, null, 3]); - - let mut tree = tree![2, 6, 5, null, null, 3, 1, null, 4]; - Solution::recover_tree(&mut tree); - assert_eq!(tree, tree![2, 1, 5, null, null, 3, 6, null, 4]); - } -} diff --git a/src/solution/s0100_same_tree.rs b/src/solution/s0100_same_tree.rs deleted file mode 100644 index c7dc1372..00000000 --- a/src/solution/s0100_same_tree.rs +++ /dev/null @@ -1,76 +0,0 @@ -/** - * [100] Same Tree - * - * Given two binary trees, write a function to check if they are the same or not. - * - * Two binary trees are considered the same if they are structurally identical and the nodes have the same value. - * - * Example 1: - * - * - * Input: 1 1 - * / \ / \ - * 2 3 2 3 - * - * [1,2,3], [1,2,3] - * - * Output: true - * - * - * Example 2: - * - * - * Input: 1 1 - * / \ - * 2 2 - * - * [1,2], [1,null,2] - * - * Output: false - * - * - * Example 3: - * - * - * Input: 1 1 - * / \ / \ - * 2 1 1 2 - * - * [1,2,1], [1,1,2] - * - * Output: false - * - * - */ -pub struct Solution {} - -use crate::util::tree::{to_tree, TreeNode}; -// problem: https://leetcode.com/problems/same-tree/ -// discuss: https://leetcode.com/problems/same-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn is_same_tree( - p: Option>>, - q: Option>>, - ) -> bool { - p == q - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_100() { - assert_eq!( - Solution::is_same_tree(tree![1, 2, 3, 4, null, 5], tree![1, 2, 3, 4, null, 5]), - true - ) - } -} diff --git a/src/solution/s0101_symmetric_tree.rs b/src/solution/s0101_symmetric_tree.rs deleted file mode 100644 index 41f44bc8..00000000 --- a/src/solution/s0101_symmetric_tree.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [101] Symmetric Tree - * - * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). - * - * - * For example, this binary tree [1,2,2,3,4,4,3] is symmetric: - * - * 1 - * / \ - * 2 2 - * / \ / \ - * 3 4 4 3 - * - * - * - * But the following [1,2,2,null,3,null,3] is not:
- * - * 1 - * / \ - * 2 2 - * \ \ - * 3 3 - * - * - * - * - * Note:
- * Bonus points if you could solve it both recursively and iteratively. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/symmetric-tree/ -// discuss: https://leetcode.com/problems/symmetric-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn is_symmetric(root: Option>>) -> bool { - Solution::symmetric_helper( - root.as_ref().and_then(|v| v.borrow().left.clone()), - root.as_ref().and_then(|v| v.borrow().right.clone()), - ) - } - - fn symmetric_helper( - left: Option>>, - right: Option>>, - ) -> bool { - match (left, right) { - (Some(left), Some(right)) => { - left.borrow().val == right.borrow().val - && Solution::symmetric_helper( - left.borrow().left.clone(), - right.borrow().right.clone(), - ) - && Solution::symmetric_helper( - left.borrow().right.clone(), - right.borrow().left.clone(), - ) - } - (None, None) => true, - _ => false, - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_101() { - assert_eq!(Solution::is_symmetric(tree![1, 2, 2, 3, 4, 4, 3]), true); - assert_eq!( - Solution::is_symmetric(tree![1, 2, 2, null, 3, null, 3]), - false - ); - assert_eq!(Solution::is_symmetric(tree![]), true); - } -} diff --git a/src/solution/s0102_binary_tree_level_order_traversal.rs b/src/solution/s0102_binary_tree_level_order_traversal.rs deleted file mode 100644 index a5a3fd13..00000000 --- a/src/solution/s0102_binary_tree_level_order_traversal.rs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * [102] Binary Tree Level Order Traversal - * - * Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). - * - * - * For example:
- * Given binary tree [3,9,20,null,null,15,7],
- * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * - * - * return its level order traversal as:
- * - * [ - * [3], - * [9,20], - * [15,7] - * ] - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-level-order-traversal/ -// discuss: https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn level_order(root: Option>>) -> Vec> { - let mut res = Vec::new(); - let mut current_level = 0; - if root.is_none() { - return res; - } - let mut deq = VecDeque::new(); - deq.push_back((0, root.clone())); - let mut vec = Vec::new(); - while !deq.is_empty() { - if let Some((level, Some(node))) = deq.pop_front() { - deq.push_back((level + 1, node.borrow().left.clone())); - deq.push_back((level + 1, node.borrow().right.clone())); - if level > current_level { - res.push(vec); - vec = Vec::new(); - current_level = level; - } - vec.push(node.borrow().val); - } - } - if !vec.is_empty() { - res.push(vec) - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_102() { - assert_eq!( - Solution::level_order(tree![3, 9, 20, null, null, 15, 7]), - vec![vec![3], vec![9, 20], vec![15, 7]] - ); - } -} diff --git a/src/solution/s0103_binary_tree_zigzag_level_order_traversal.rs b/src/solution/s0103_binary_tree_zigzag_level_order_traversal.rs deleted file mode 100644 index 78aa7b5e..00000000 --- a/src/solution/s0103_binary_tree_zigzag_level_order_traversal.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [103] Binary Tree Zigzag Level Order Traversal - * - * Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). - * - * - * For example:
- * Given binary tree [3,9,20,null,null,15,7],
- * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * - * - * return its zigzag level order traversal as:
- * - * [ - * [3], - * [20,9], - * [15,7] - * ] - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ -// discuss: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn zigzag_level_order(root: Option>>) -> Vec> { - let mut res = Vec::new(); - let mut current_level = 0; - if root.is_none() { - return res; - } - let mut deq = VecDeque::new(); - deq.push_back((0, root.clone())); - let mut vec = Vec::new(); - while !deq.is_empty() { - if let Some((level, Some(node))) = deq.pop_front() { - deq.push_back((level + 1, node.borrow().left.clone())); - deq.push_back((level + 1, node.borrow().right.clone())); - if level > current_level { - if current_level % 2 == 1 { - vec.reverse(); - } - res.push(vec); - vec = Vec::new(); - current_level = level; - } - vec.push(node.borrow().val); - } - } - if !vec.is_empty() { - if current_level % 2 == 1 { - vec.reverse(); - } - res.push(vec) - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_103() { - assert_eq!( - Solution::zigzag_level_order(tree![3, 9, 20, null, null, 15, 7]), - vec![vec![3], vec![20, 9], vec![15, 7]] - ); - } -} diff --git a/src/solution/s0104_maximum_depth_of_binary_tree.rs b/src/solution/s0104_maximum_depth_of_binary_tree.rs deleted file mode 100644 index 2b2a51d4..00000000 --- a/src/solution/s0104_maximum_depth_of_binary_tree.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [104] Maximum Depth of Binary Tree - * - * Given a binary tree, find its maximum depth. - * - * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * Given binary tree [3,9,20,null,null,15,7], - * - * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * return its depth = 3. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/maximum-depth-of-binary-tree/ -// discuss: https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn max_depth(root: Option>>) -> i32 { - let mut max = 0; - Solution::depth_helper(root.as_ref(), &mut max, 0); - max - } - - fn depth_helper(root: Option<&Rc>>, max: &mut i32, curr: i32) { - if let Some(node) = root { - *max = i32::max(*max, curr + 1); - Solution::depth_helper(node.borrow().left.as_ref(), max, curr + 1); - Solution::depth_helper(node.borrow().right.as_ref(), max, curr + 1); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_104() { - assert_eq!(Solution::max_depth(tree![]), 0); - assert_eq!(Solution::max_depth(tree![3, 9, 20, null, null, 15, 7]), 3); - } -} diff --git a/src/solution/s0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs b/src/solution/s0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs deleted file mode 100644 index 809ae654..00000000 --- a/src/solution/s0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs +++ /dev/null @@ -1,71 +0,0 @@ -/** - * [105] Construct Binary Tree from Preorder and Inorder Traversal - * - * Given preorder and inorder traversal of a tree, construct the binary tree. - * - * Note:
- * You may assume that duplicates do not exist in the tree. - * - * For example, given - * - * - * preorder = [3,9,20,15,7] - * inorder = [9,3,15,20,7] - * - * Return the following binary tree: - * - * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ -// discuss: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn build_tree(preorder: Vec, inorder: Vec) -> Option>> { - Solution::build_tree_helper(&preorder[..], &inorder[..]) - } - - fn build_tree_helper(preorder: &[i32], inorder: &[i32]) -> Option>> { - if preorder.is_empty() { - return None; - } - let root_idx = inorder.iter().position(|&v| v == preorder[0]).unwrap(); - Some(Rc::new(RefCell::new(TreeNode { - val: preorder[0], - left: Solution::build_tree_helper(&preorder[1..root_idx + 1], &inorder[0..root_idx]), - right: Solution::build_tree_helper(&preorder[root_idx + 1..], &inorder[root_idx + 1..]), - }))) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_105() { - assert_eq!( - Solution::build_tree(vec![3, 9, 20, 15, 7], vec![9, 3, 15, 20, 7]), - tree![3, 9, 20, null, null, 15, 7] - ); - assert_eq!( - Solution::build_tree(vec![3, 20, 7], vec![3, 20, 7]), - tree![3, null, 20, null, 7] - ); - assert_eq!(Solution::build_tree(vec![], vec![]), tree![]); - } -} diff --git a/src/solution/s0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs b/src/solution/s0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs deleted file mode 100644 index df215bbc..00000000 --- a/src/solution/s0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs +++ /dev/null @@ -1,78 +0,0 @@ -/** - * [106] Construct Binary Tree from Inorder and Postorder Traversal - * - * Given inorder and postorder traversal of a tree, construct the binary tree. - * - * Note:
- * You may assume that duplicates do not exist in the tree. - * - * For example, given - * - * - * inorder = [9,3,15,20,7] - * postorder = [9,15,7,20,3] - * - * Return the following binary tree: - * - * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ -// discuss: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn build_tree(inorder: Vec, postorder: Vec) -> Option>> { - Solution::build_tree_helper(&postorder[..], &inorder[..]) - } - - fn build_tree_helper(postorder: &[i32], inorder: &[i32]) -> Option>> { - if postorder.is_empty() { - return None; - } - let root_idx = inorder - .iter() - .position(|v| v == postorder.last().unwrap()) - .unwrap(); - Some(Rc::new(RefCell::new(TreeNode { - val: *postorder.last().unwrap(), - left: Solution::build_tree_helper(&postorder[0..root_idx], &inorder[0..root_idx]), - right: Solution::build_tree_helper( - &postorder[root_idx..postorder.len() - 1], - &inorder[root_idx + 1..], - ), - }))) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_106() { - assert_eq!( - Solution::build_tree(vec![9, 3, 15, 20, 7], vec![9, 15, 7, 20, 3]), - tree![3, 9, 20, null, null, 15, 7] - ); - assert_eq!( - Solution::build_tree(vec![3, 20, 7], vec![7, 20, 3]), - tree![3, null, 20, null, 7] - ); - assert_eq!(Solution::build_tree(vec![], vec![]), tree![]); - } -} diff --git a/src/solution/s0107_binary_tree_level_order_traversal_ii.rs b/src/solution/s0107_binary_tree_level_order_traversal_ii.rs deleted file mode 100644 index 4b74e0d7..00000000 --- a/src/solution/s0107_binary_tree_level_order_traversal_ii.rs +++ /dev/null @@ -1,82 +0,0 @@ -/** - * [107] Binary Tree Level Order Traversal II - * - * Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). - * - * - * For example:
- * Given binary tree [3,9,20,null,null,15,7],
- * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * - * - * return its bottom-up level order traversal as:
- * - * [ - * [15,7], - * [9,20], - * [3] - * ] - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ -// discuss: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn level_order_bottom(root: Option>>) -> Vec> { - let mut res = Vec::new(); - let mut current_level = 0; - if root.is_none() { - return res; - } - let mut deq = VecDeque::new(); - deq.push_back((0, root.clone())); - let mut vec = Vec::new(); - while !deq.is_empty() { - if let Some((level, Some(node))) = deq.pop_front() { - deq.push_back((level + 1, node.borrow().left.clone())); - deq.push_back((level + 1, node.borrow().right.clone())); - if level > current_level { - res.push(vec); - vec = Vec::new(); - current_level = level; - } - vec.push(node.borrow().val); - } - } - if !vec.is_empty() { - res.push(vec) - } - res.reverse(); - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_107() { - assert_eq!( - Solution::level_order_bottom(tree![3, 9, 20, null, null, 15, 7]), - vec![vec![15, 7], vec![9, 20], vec![3],] - ); - } -} diff --git a/src/solution/s0108_convert_sorted_array_to_binary_search_tree.rs b/src/solution/s0108_convert_sorted_array_to_binary_search_tree.rs index 2cefab5c..9fcd2367 100644 --- a/src/solution/s0108_convert_sorted_array_to_binary_search_tree.rs +++ b/src/solution/s0108_convert_sorted_array_to_binary_search_tree.rs @@ -1,23 +1,28 @@ /** * [108] Convert Sorted Array to Binary Search Tree * - * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. + * Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. + * A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. + * + * Example 1: + * + * Input: nums = [-10,-3,0,5,9] + * Output: [0,-3,9,-10,null,5] + * Explanation: [0,-10,5,null,-3,null,9] is also accepted: + * * - * For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. + * Example 2: + * + * Input: nums = [1,3] + * Output: [3,1] + * Explanation: [1,null,3] and [3,1] are both height-balanced BSTs. * - * Example: - * - * - * Given the sorted array: [-10,-3,0,5,9], - * - * One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: - * - * 0 - * / \ - * -3 9 - * / / - * -10 5 + * + * Constraints: * + * 1 <= nums.length <= 10^4 + * -10^4 <= nums[i] <= 10^4 + * nums is sorted in a strictly increasing order. * */ pub struct Solution {} @@ -26,24 +31,22 @@ use crate::util::tree::{to_tree, TreeNode}; // problem: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ // discuss: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= -// submission codes start here - use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn sorted_array_to_bst(nums: Vec) -> Option>> { - Solution::bst_helper(&nums[..]) + Self::sorted_array_to_bst_recursive(&nums) } - fn bst_helper(nums: &[i32]) -> Option>> { + pub fn sorted_array_to_bst_recursive(nums: &[i32]) -> Option>> { if nums.is_empty() { return None; } - Some(Rc::new(RefCell::new(TreeNode { - val: nums[nums.len() / 2], - left: Solution::bst_helper(&nums[0..(nums.len() / 2)]), - right: Solution::bst_helper(&nums[(nums.len() / 2 + 1)..]), - }))) + let mid = nums.len() / 2; + let mut node = TreeNode::new(nums[mid]); + node.left = Self::sorted_array_to_bst_recursive(&nums[..mid]); + node.right = Self::sorted_array_to_bst_recursive(&nums[mid + 1..]); + Some(Rc::new(RefCell::new(node))) } } @@ -59,6 +62,7 @@ mod tests { Solution::sorted_array_to_bst(vec![-10, -3, 0, 5, 9]), tree![0, -3, 9, -10, null, 5] ); + assert_eq!(Solution::sorted_array_to_bst(vec![]), tree![]); } } diff --git a/src/solution/s0109_convert_sorted_list_to_binary_search_tree.rs b/src/solution/s0109_convert_sorted_list_to_binary_search_tree.rs deleted file mode 100644 index e2070965..00000000 --- a/src/solution/s0109_convert_sorted_list_to_binary_search_tree.rs +++ /dev/null @@ -1,70 +0,0 @@ -/** - * [109] Convert Sorted List to Binary Search Tree - * - * Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. - * - * For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. - * - * Example: - * - * - * Given the sorted linked list: [-10,-3,0,5,9], - * - * One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: - * - * 0 - * / \ - * -3 9 - * / / - * -10 5 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ -// discuss: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn sorted_list_to_bst(head: Option>) -> Option>> { - let mut arr = Vec::new(); - let mut head = head; - while let Some(node) = head { - arr.push(node.val); - head = node.next; - } - Solution::bst_helper(&arr[..]) - } - - fn bst_helper(nums: &[i32]) -> Option>> { - if nums.is_empty() { - return None; - } - Some(Rc::new(RefCell::new(TreeNode { - val: nums[nums.len() / 2], - left: Solution::bst_helper(&nums[0..(nums.len() / 2)]), - right: Solution::bst_helper(&nums[(nums.len() / 2 + 1)..]), - }))) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_109() { - assert_eq!( - Solution::sorted_list_to_bst(linked![-10, -3, 0, 5, 9]), - tree![0, -3, 9, -10, null, 5] - ); - } -} diff --git a/src/solution/s0110_balanced_binary_tree.rs b/src/solution/s0110_balanced_binary_tree.rs deleted file mode 100644 index c3171126..00000000 --- a/src/solution/s0110_balanced_binary_tree.rs +++ /dev/null @@ -1,97 +0,0 @@ -/** - * [110] Balanced Binary Tree - * - * Given a binary tree, determine if it is height-balanced. - * - * For this problem, a height-balanced binary tree is defined as: - * - *
- * a binary tree in which the depth of the two subtrees of every node never differ by more than 1. - *
- * - * Example 1: - * - * Given the following tree [3,9,20,null,null,15,7]: - * - * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * Return true.
- *
- * Example 2: - * - * Given the following tree [1,2,2,3,3,null,null,4,4]: - * - * - * 1 - * / \ - * 2 2 - * / \ - * 3 3 - * / \ - * 4 4 - * - * - * Return false. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/balanced-binary-tree/ -// discuss: https://leetcode.com/problems/balanced-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn is_balanced(root: Option>>) -> bool { - Solution::balanced_helper(root.as_ref()).is_some() - } - - fn balanced_helper(root: Option<&Rc>>) -> Option { - if let Some(node) = root { - let pair = ( - Solution::balanced_helper(node.borrow().left.as_ref()), - Solution::balanced_helper(node.borrow().right.as_ref()), - ); - match pair { - (Some(left), Some(right)) => { - if i32::abs(left - right) < 2 { - return Some(i32::max(left, right) + 1); - } else { - return None; - } - } - _ => return None, - } - } else { - Some(0) - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_110() { - assert_eq!(Solution::is_balanced(tree![]), true); - assert_eq!( - Solution::is_balanced(tree![3, 9, 20, null, null, 15, 7]), - true - ); - assert_eq!( - Solution::is_balanced(tree![1, 2, 2, 3, 3, null, null, 4, 4]), - false - ); - } -} diff --git a/src/solution/s0111_minimum_depth_of_binary_tree.rs b/src/solution/s0111_minimum_depth_of_binary_tree.rs deleted file mode 100644 index a73e49f0..00000000 --- a/src/solution/s0111_minimum_depth_of_binary_tree.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [111] Minimum Depth of Binary Tree - * - * Given a binary tree, find its minimum depth. - * - * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * Given binary tree [3,9,20,null,null,15,7], - * - * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * return its minimum depth = 2. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/minimum-depth-of-binary-tree/ -// discuss: https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn min_depth(root: Option>>) -> i32 { - if root.is_none() { - return 0; - } - let mut deq = VecDeque::new(); - deq.push_back((1, root.clone())); - while !deq.is_empty() { - if let Some((level, Some(node))) = deq.pop_front() { - if node.borrow().left.is_none() && node.borrow().right.is_none() { - return level; - } - deq.push_back((level + 1, node.borrow().left.clone())); - deq.push_back((level + 1, node.borrow().right.clone())); - } - } - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_111() { - assert_eq!(Solution::min_depth(tree![3, 9, 20, null, null, 15, 7]), 2); - } -} diff --git a/src/solution/s0112_path_sum.rs b/src/solution/s0112_path_sum.rs deleted file mode 100644 index e2e0a235..00000000 --- a/src/solution/s0112_path_sum.rs +++ /dev/null @@ -1,80 +0,0 @@ -/** - * [112] Path Sum - * - * Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * Given the below binary tree and sum = 22, - * - * - * 5 - * / \ - * 4 8 - * / / \ - * 11 13 4 - * / \ \ - * 7 2 1 - * - * - * return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/path-sum/ -// discuss: https://leetcode.com/problems/path-sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn has_path_sum(root: Option>>, sum: i32) -> bool { - if root.is_none() { - return false; - } - let mut deq = VecDeque::new(); - deq.push_back((0, root.unwrap().clone())); - while !deq.is_empty() { - if let Some((acc, node)) = deq.pop_front() { - let acc = acc + node.borrow().val; - if node.borrow().left.is_none() && node.borrow().right.is_none() { - if acc == sum { - return true; - } - } else { - if node.borrow().left.is_some() { - deq.push_back((acc, node.borrow().left.as_ref().unwrap().clone())) - }; - if node.borrow().right.is_some() { - deq.push_back((acc, node.borrow().right.as_ref().unwrap().clone())) - }; - } - } - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_112() { - assert_eq!( - Solution::has_path_sum( - tree![5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], - 22 - ), - true - ); - } -} diff --git a/src/solution/s0113_path_sum_ii.rs b/src/solution/s0113_path_sum_ii.rs deleted file mode 100644 index 106d1921..00000000 --- a/src/solution/s0113_path_sum_ii.rs +++ /dev/null @@ -1,86 +0,0 @@ -/** - * [113] Path Sum II - * - * Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * Given the below binary tree and sum = 22, - * - * - * 5 - * / \ - * 4 8 - * / / \ - * 11 13 4 - * / \ / \ - * 7 2 5 1 - * - * - * Return: - * - * - * [ - * [5,4,11,2], - * [5,8,4,5] - * ] - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/path-sum-ii/ -// discuss: https://leetcode.com/problems/path-sum-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn path_sum(root: Option>>, sum: i32) -> Vec> { - let mut res = Vec::new(); - if root.is_none() { - return res; - } - let mut deq = VecDeque::new(); - deq.push_back((0, Vec::new(), root.clone())); - while !deq.is_empty() { - if let Some((acc, mut vec, Some(node))) = deq.pop_front() { - let acc = acc + node.borrow().val; - vec.push(node.borrow().val); - if node.borrow().left.is_none() && node.borrow().right.is_none() { - if acc == sum { - res.push(vec); - } - } else { - if node.borrow().left.is_some() { - deq.push_back((acc, vec.clone(), node.borrow().left.clone())); - } - if node.borrow().right.is_some() { - deq.push_back((acc, vec.clone(), node.borrow().right.clone())); - } - } - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_113() { - assert_eq!( - Solution::path_sum(tree![5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1], 22), - vec![vec![5, 4, 11, 2], vec![5, 8, 4, 5]] - ) - } -} diff --git a/src/solution/s0114_flatten_binary_tree_to_linked_list.rs b/src/solution/s0114_flatten_binary_tree_to_linked_list.rs deleted file mode 100644 index 63668c47..00000000 --- a/src/solution/s0114_flatten_binary_tree_to_linked_list.rs +++ /dev/null @@ -1,90 +0,0 @@ -/** - * [114] Flatten Binary Tree to Linked List - * - * Given a binary tree, flatten it to a linked list in-place. - * - * For example, given the following tree: - * - * - * 1 - * / \ - * 2 5 - * / \ \ - * 3 4 6 - * - * - * The flattened tree should look like: - * - * - * 1 - * \ - * 2 - * \ - * 3 - * \ - * 4 - * \ - * 5 - * \ - * 6 - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ -// discuss: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn flatten(root: &mut Option>>) { - Solution::flatten_helper(root.clone()); - } - - fn flatten_helper(root: Option>>) -> Option>> { - if let Some(node) = root { - let tail = Solution::flatten_helper(node.borrow().left.clone()); - Solution::flatten_helper(node.borrow_mut().right.clone()); - let mut right = node.borrow().right.clone(); - let mut ptr = node.clone(); - if let Some(tail) = tail { - let head = node.borrow_mut().left.take(); - node.borrow_mut().right = head; - tail.borrow_mut().right = right.clone(); - ptr = tail.clone(); - } - while let Some(next) = ptr.clone().borrow().right.clone() { - ptr = next - } - Some(ptr) - } else { - None - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_114() { - let mut tree = tree![1, 2, 5, 3, 4, null, 6]; - Solution::flatten(&mut tree); - assert_eq!(tree, tree![1, null, 2, null, 3, null, 4, null, 5, null, 6]); - - let mut tree = tree![1, 2, null, 3]; - Solution::flatten(&mut tree); - assert_eq!(tree, tree![1, null, 2, null, 3]); - - let mut tree = tree![1, null, 2, 3]; - Solution::flatten(&mut tree); - assert_eq!(tree, tree![1, null, 2, null, 3]); - } -} diff --git a/src/solution/s0115_distinct_subsequences.rs b/src/solution/s0115_distinct_subsequences.rs deleted file mode 100644 index 7af3d08b..00000000 --- a/src/solution/s0115_distinct_subsequences.rs +++ /dev/null @@ -1,122 +0,0 @@ -/** - * [115] Distinct Subsequences - * - * Given a string S and a string T, count the number of distinct subsequences of S which equals T. - * - * A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). - * - * Example 1: - * - * - * Input: S = "rabbbit", T = "rabbit" - * Output: 3 - * Explanation: - * - * As shown below, there are 3 ways you can generate "rabbit" from S. - * (The caret symbol ^ means the chosen letters) - * - * rabbbit - * ^^^^ ^^ - * rabbbit - * ^^ ^^^^ - * rabbbit - * ^^^ ^^^ - * - * - * Example 2: - * - * - * Input: S = "babgbag", T = "bag" - * Output: 5 - * Explanation: - * - * As shown below, there are 5 ways you can generate "bag" from S. - * (The caret symbol ^ means the chosen letters) - * - * babgbag - * ^^ ^ - * babgbag - * ^^ ^ - * babgbag - * ^ ^^ - * babgbag - * ^ ^^ - * babgbag - * ^^^ - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/distinct-subsequences/ -// discuss: https://leetcode.com/problems/distinct-subsequences/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -首先想到 DFS. 但这里 DFS 有重复计算, 因为我们不需要列出所有的路径, 复杂度可以考虑 "aaaaaaaaaaaaaaaaaaaa" -里找 "aaaaaaaaa", 直接搜索的话复杂度是指数级的(阶乘), 原因很明显, 这本身是个排列组合, 可以套 combination 公式 -20! / ((20-10)! * 10!) 得到结果是 184756 - -要把复杂度从指数级降下来, 那么必须干掉重复计算, 那就想到 memorize, 想到 memorize 就想到 DP 和 Bottom-Up 递推, -回顾一下 #62 和 #63 这两个问题 (unique paths), 使用的是Bottom-Up DP, 到达每个格子的可能路径是上下两个格子的 -可能路径的和. 这里就跳过了很多的计算, 不需要把每条路径都遍历出来了. 在 unique paths 问题中, 到达右下角的路径数的 -子问题是到达右下角左侧格子的路径数以及到达右下角上侧格子的路径数. 这个问题也是一样的道理, s 中找子序列 t: - -* s[0..i] 包含的 t 序列数就是所有 s[0..j] (j < i) 包含的 t[0..t.len()-1] 的序列数 - -以 babgbag 中找 bag 为例, 做一次 Bottom-Up 递推: - - b a b g b a g -b 1 1 1 3 找 'b' 这个子序列, 那么以 [0, 2, 4] 这三个下标结尾各有一种 -a 1 3 4 找 'ba' 这个子序列, 那么以 1 结尾有1种(0 < 1), 以 5 结尾有 3 种 (0,2,4 都 < 5) -g 1 4 5 同理, 以 3 结尾有 1 种, 以 6 结尾有 4 种, 共 5 种 - -显然, 计算第 N 行时只依赖第 N-1 行的结果, 因此我们不需要存储整个矩阵, 只需要存储一行即可 - -时间复杂度是 O(M*N), 空间复杂度是 O(M) -*/ -impl Solution { - pub fn num_distinct(s: String, t: String) -> i32 { - let s = s.chars().collect::>(); - let mut cache = vec![0; s.len()]; - for (i, ch) in t.chars().into_iter().enumerate() { - let mut acc = 0; - // first char initialization - if i == 0 { - for i in 0..s.len() { - if ch == s[i] { - cache[i] = 1 - } - } - continue; - } - for i in 0..s.len() { - let new_acc = acc + cache[i]; - cache[i] = if s[i] == ch { acc } else { 0 }; - acc = new_acc; - } - } - cache.into_iter().fold(0, |acc, x| acc + x) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_115() { - //assert_eq!(Solution::num_distinct("rabbbit".to_owned(), "rabbit".to_owned()), 3); - assert_eq!( - Solution::num_distinct("babgbag".to_owned(), "bag".to_owned()), - 5 - ); - assert_eq!( - Solution::num_distinct("aaaaaaaaaaaaaaaaaaaa".to_owned(), "aaaaaaaaaa".to_owned()), - 184756 - ); - } -} diff --git a/src/solution/s0118_pascals_triangle.rs b/src/solution/s0118_pascals_triangle.rs deleted file mode 100644 index d593242d..00000000 --- a/src/solution/s0118_pascals_triangle.rs +++ /dev/null @@ -1,70 +0,0 @@ -/** - * [118] Pascal's Triangle - * - * Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. - * - *
- * In Pascal's triangle, each number is the sum of the two numbers directly above it. - * - * Example: - * - * - * Input: 5 - * Output: - * [ - * [1], - * [1,1], - * [1,2,1], - * [1,3,3,1], - * [1,4,6,4,1] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/pascals-triangle/ -// discuss: https://leetcode.com/problems/pascals-triangle/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn generate(num_rows: i32) -> Vec> { - let mut res = Vec::new(); - if num_rows < 1 { - return res; - } - let mut curr = vec![1]; - for _ in 0..num_rows { - let mut next = vec![1; curr.len() + 1]; - for i in 1..curr.len() { - next[i] = curr[i - 1] + curr[i]; - } - res.push(curr); - curr = next; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_118() { - assert_eq!(Solution::generate(1), vec![vec![1]]); - assert_eq!( - Solution::generate(5), - vec![ - vec![1], - vec![1, 1], - vec![1, 2, 1], - vec![1, 3, 3, 1], - vec![1, 4, 6, 4, 1] - ] - ); - } -} diff --git a/src/solution/s0119_pascals_triangle_ii.rs b/src/solution/s0119_pascals_triangle_ii.rs deleted file mode 100644 index 588a9835..00000000 --- a/src/solution/s0119_pascals_triangle_ii.rs +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [119] Pascal's Triangle II - * - * Given a non-negative index k where k ≤ 33, return the k^th index row of the Pascal's triangle. - * - * Note that the row index starts from 0. - * - *
- * In Pascal's triangle, each number is the sum of the two numbers directly above it. - * - * Example: - * - * - * Input: 3 - * Output: [1,3,3,1] - * - * - * Follow up: - * - * Could you optimize your algorithm to use only O(k) extra space? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/pascals-triangle-ii/ -// discuss: https://leetcode.com/problems/pascals-triangle-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -in-place algorithm - -1 1 1 1 1 -1 2 1 1 1 -1 3 3 1 1 -1 4 6 4 1 -*/ -impl Solution { - pub fn get_row(row_index: i32) -> Vec { - let mut curr = vec![1; (row_index + 1) as usize]; - for i in 0..row_index + 1 { - let mut prev = 1; - for j in 1..i { - let temp = curr[j as usize]; - curr[j as usize] = temp + prev; - prev = temp; - } - } - curr - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_119() { - assert_eq!(Solution::get_row(0), vec![1]); - assert_eq!(Solution::get_row(4), vec![1, 4, 6, 4, 1]) - } -} diff --git a/src/solution/s0120_triangle.rs b/src/solution/s0120_triangle.rs deleted file mode 100644 index 93c38d33..00000000 --- a/src/solution/s0120_triangle.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [120] Triangle - * - * Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. - * - * For example, given the following triangle - * - * - * [ - * [2], - * [3,4], - * [6,5,7], - * [4,1,8,3] - * ] - * - * - * The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). - * - * Note: - * - * Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/triangle/ -// discuss: https://leetcode.com/problems/triangle/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn minimum_total(triangle: Vec>) -> i32 { - let mut cache = vec![0; triangle.len()]; - for row in triangle.iter() { - let mut prev = 0; - for i in 0..row.len() { - let temp = cache[i]; - cache[i] = if i == 0 { - cache[i] - } else if i == row.len() - 1 { - prev - } else { - i32::min(cache[i], prev) - } + row[i]; - prev = temp; - } - } - cache - .into_iter() - .fold(i32::max_value(), |min, x| i32::min(min, x)) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_120() { - assert_eq!( - Solution::minimum_total(vec![vec![2], vec![3, 4], vec![6, 5, 7], vec![4, 1, 8, 3]]), - 11 - ) - } -} diff --git a/src/solution/s0121_best_time_to_buy_and_sell_stock.rs b/src/solution/s0121_best_time_to_buy_and_sell_stock.rs deleted file mode 100644 index d5d3746d..00000000 --- a/src/solution/s0121_best_time_to_buy_and_sell_stock.rs +++ /dev/null @@ -1,62 +0,0 @@ -/** - * [121] Best Time to Buy and Sell Stock - * - * Say you have an array for which the i^th element is the price of a given stock on day i. - * - * If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. - * - * Note that you cannot sell a stock before you buy one. - * - * Example 1: - * - * - * Input: [7,1,5,3,6,4] - * Output: 5 - * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. - * Not 7-1 = 6, as selling price needs to be larger than buying price. - * - * - * Example 2: - * - * - * Input: [7,6,4,3,1] - * Output: 0 - * Explanation: In this case, no transaction is done, i.e. max profit = 0. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ -// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - let mut max = 0; - let mut curr = 0; - for i in 1..prices.len() { - curr = curr + prices[i] - prices[i - 1]; - if curr <= 0 { - curr = 0; - } else { - max = i32::max(max, curr); - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_121() { - assert_eq!(Solution::max_profit(vec![7, 1, 5, 3, 6, 4]), 5); - assert_eq!(Solution::max_profit(vec![7, 6, 4, 3, 1]), 0); - } -} diff --git a/src/solution/s0122_best_time_to_buy_and_sell_stock_ii.rs b/src/solution/s0122_best_time_to_buy_and_sell_stock_ii.rs deleted file mode 100644 index 803c71b6..00000000 --- a/src/solution/s0122_best_time_to_buy_and_sell_stock_ii.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [122] Best Time to Buy and Sell Stock II - * - * Say you have an array for which the i^th element is the price of a given stock on day i. - * - * Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). - * - * Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). - * - * Example 1: - * - * - * Input: [7,1,5,3,6,4] - * Output: 7 - * Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. - * Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. - * - * - * Example 2: - * - * - * Input: [1,2,3,4,5] - * Output: 4 - * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. - * Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are - * engaging multiple transactions at the same time. You must sell before buying again. - * - * - * Example 3: - * - * - * Input: [7,6,4,3,1] - * Output: 0 - * Explanation: In this case, no transaction is done, i.e. max profit = 0. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ -// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - let mut max = 0; - for i in 1..prices.len() { - if prices[i] > prices[i - 1] { - max += prices[i] - prices[i - 1]; - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_122() { - assert_eq!(Solution::max_profit(vec![7, 1, 5, 3, 6, 4]), 7); - assert_eq!(Solution::max_profit(vec![1, 2, 3, 4, 5]), 4); - } -} diff --git a/src/solution/s0123_best_time_to_buy_and_sell_stock_iii.rs b/src/solution/s0123_best_time_to_buy_and_sell_stock_iii.rs deleted file mode 100644 index bb068273..00000000 --- a/src/solution/s0123_best_time_to_buy_and_sell_stock_iii.rs +++ /dev/null @@ -1,106 +0,0 @@ -/** - * [123] Best Time to Buy and Sell Stock III - * - * Say you have an array for which the i^th element is the price of a given stock on day i. - * - * Design an algorithm to find the maximum profit. You may complete at most two transactions. - * - * Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). - * - * Example 1: - * - * - * Input: [3,3,5,0,0,3,1,4] - * Output: 6 - * Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. - * Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. - * - * Example 2: - * - * - * Input: [1,2,3,4,5] - * Output: 4 - * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. - * Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are - * engaging multiple transactions at the same time. You must sell before buying again. - * - * - * Example 3: - * - * - * Input: [7,6,4,3,1] - * Output: 0 - * Explanation: In this case, no transaction is done, i.e. max profit = 0. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ -// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -先考虑只进行 1 次交易的情况, 我们求以 i *为售出点*, 只进行 1 次交易获得的最大利润, 那么: - -f[i] = if f[i-1] > 0 { f[i-1] } else { 0 } + prices[i] - prices[i-1] - -这很容易解, 解完之后找出 f 里的最大值即可, 但这不容易推广到 K 次交易的情况, 因为这时 f[i] 不代表到 i *为止*的最大利润, 无法作为单独的交易帮助递推 -(到 i 为止的含义是售出点可以在 [0,i] 之间) - -我们可以稍作改进, 变成求以 i 为结束点, 只进行 1 次交易获得的最大利润, 那么: - -f[i] = max( - f[i-1], - prices[i] - min(prices[j] { j in [0, i-1] }) -) - -这仍然是一个 O(N) 的解法, 因为 min(prices[j] { j in [0, i-1] }) 不需要遍历, 可以在递推过程中直接维护好 - -现在再推广到进行 K 次交易的情况, 那我们要求以 i 为结束点, 进行 k 次交易获得的最大利润, 这时有了变化, 我们可以在 j 之前再进行 K - 1 次交易: - -f[k, i] = max( - f[k, i-1], - prices[i] + max(f[k-1, j] - prices[j]) { j in [0, i-1] } ) -) - -显然, f[0, i] = 0, f[k, 0] = 0 - -这个算法可以形象地描述一下, 在 k = 1 时, 我们每次要找的就是 i 之前的最低谷点作为这次交易的开始点 j, 而当 k > 1 时, -我们 i 之前就有可能已经进行过交易了, 这时我们在找开始点 j 时, 就要同时考虑 "直到 j 为止, k-1 次交易的最大收益" - "j 本身的值". 以此来找到一个最佳点 j - -在实现时, 假如用 Bottom-Up 递推, 那么只需要维护一个 vec[i], 因为每轮递推时只会考虑上一轮的数据, 我们可以复用这个 O(N) 的额外存储空间 -*/ -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - if prices.is_empty() { - return 0; - } - let max_trans = 2; - let mut cache = vec![0; prices.len()]; - for trans in 0..max_trans { - // best_by_in 维护了考虑前 N 次交易的最佳的买入点, 即 max(f[k-1, j] - prices[j]) { j in [0, i-1] } - let mut best_buy_in = cache[0] - prices[0]; - for i in 1..prices.len() { - // 复用 vec 前暂存一下前一次的计算结果 - let temp = cache[i]; - cache[i] = i32::max(cache[i - 1], best_buy_in + prices[i]); - // 更新 best_buy_in - best_buy_in = i32::max(best_buy_in, temp - prices[i]); - } - } - return *cache.last().unwrap(); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_123() { - assert_eq!(Solution::max_profit(vec![3, 3, 5, 0, 0, 3, 1, 4]), 6); - } -} diff --git a/src/solution/s0124_binary_tree_maximum_path_sum.rs b/src/solution/s0124_binary_tree_maximum_path_sum.rs deleted file mode 100644 index e7c57b49..00000000 --- a/src/solution/s0124_binary_tree_maximum_path_sum.rs +++ /dev/null @@ -1,100 +0,0 @@ -/** - * [124] Binary Tree Maximum Path Sum - * - * Given a non-empty binary tree, find the maximum path sum. - * - * For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. - * - * Example 1: - * - * - * Input: [1,2,3] - * - * 1 - * / \ - * 2 3 - * - * Output: 6 - * - * - * Example 2: - * - * - * Input: [-10,9,20,null,null,15,7] - * - * -10 - * / \ - * 9 20 - * / \ - * 15 7 - * - * Output: 42 - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-maximum-path-sum/ -// discuss: https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -典型的动态规划, 我们求以 node_i 为 root 的最大和, 可以下推到求 root 的左右子树, 这里要注意, 路径是不能分叉的, 因此 -我们记 f[node] 为以 node 为根的最大和, 记 g[node] 为 node 为根, *最多连通一侧子树*的最大和 - -我们在递推时要用 g[node], f[node] 在递推过程中每次计算一下用于更新 max 即可 - -g[node_i] = node_i.val + max(g[node_i.left], g[node_i.right], 0) -f[node_i] = node_i.val + max(g[node_i.left], 0) + max(g[node_i.right], 0) - -显然, g[None] = 0 (None 即空子树), 最终计算到 g[root] 中止, f 的最大值会在计算过程中出现(注意 f[root] 不一定是最大值) - -每个 node 最大和只依赖与其左右子树的最大和, 因此 Top-down 需要 O(N) 的空间 -Bottom-up 只需要 O(1) 空间 (做后序遍历从叶节点向上递推即可) -*/ -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn max_path_sum(root: Option>>) -> i32 { - let mut max = i32::min_value(); - Solution::postorder(root.as_ref(), &mut max); - max - } - - fn postorder(root: Option<&Rc>>, max: &mut i32) -> i32 { - if let Some(node) = root { - let left = Solution::postorder(node.borrow().left.as_ref(), max); - let right = Solution::postorder(node.borrow().right.as_ref(), max); - *max = i32::max( - node.borrow().val + i32::max(left, 0) + i32::max(right, 0), - *max, - ); - node.borrow().val + i32::max(i32::max(left, right), 0) - } else { - 0 - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_124() { - assert_eq!(Solution::max_path_sum(tree![1, 2, 3]), 6); - assert_eq!( - Solution::max_path_sum(tree![-10, 9, 20, null, null, 15, 7]), - 42 - ); - assert_eq!( - Solution::max_path_sum(tree![5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1]), - 48 - ); - assert_eq!(Solution::max_path_sum(tree![-3]), -3); - } -} diff --git a/src/solution/s0125_valid_palindrome.rs b/src/solution/s0125_valid_palindrome.rs deleted file mode 100644 index 2f090b72..00000000 --- a/src/solution/s0125_valid_palindrome.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [125] Valid Palindrome - * - * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. - * - * Note: For the purpose of this problem, we define empty string as valid palindrome. - * - * Example 1: - * - * - * Input: "A man, a plan, a canal: Panama" - * Output: true - * - * - * Example 2: - * - * - * Input: "race a car" - * Output: false - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/valid-palindrome/ -// discuss: https://leetcode.com/problems/valid-palindrome/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_palindrome(s: String) -> bool { - if s.is_empty() { - return true; - } - let seq = s.chars().collect::>(); - let (mut i, mut j) = (0_usize, seq.len() - 1); - while i < j { - while i < seq.len() && !seq[i].is_ascii_alphanumeric() { - i += 1; - } - while j > 0 && !seq[j].is_ascii_alphanumeric() { - j -= 1; - } - if i >= j { - break; - } - if seq[i].to_ascii_lowercase() != seq[j].to_ascii_lowercase() { - return false; - } - i += 1; - j -= 1; - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_125() { - assert_eq!( - Solution::is_palindrome("A man, a plan, a canal: Panama".to_owned()), - true - ); - assert_eq!(Solution::is_palindrome("race a car".to_owned()), false); - assert_eq!(Solution::is_palindrome("0P".to_owned()), false); - } -} diff --git a/src/solution/s0126_word_ladder_ii.rs b/src/solution/s0126_word_ladder_ii.rs deleted file mode 100644 index 32169865..00000000 --- a/src/solution/s0126_word_ladder_ii.rs +++ /dev/null @@ -1,258 +0,0 @@ -/** - * [126] Word Ladder II - * - * Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: - * - *
    - * Only one letter can be changed at a time - * Each transformed word must exist in the word list. Note that beginWord is not a transformed word. - *
- * - * Note: - * - * - * Return an empty list if there is no such transformation sequence. - * All words have the same length. - * All words contain only lowercase alphabetic characters. - * You may assume no duplicates in the word list. - * You may assume beginWord and endWord are non-empty and are not the same. - * - * - * Example 1: - * - * - * Input: - * beginWord = "hit", - * endWord = "cog", - * wordList = ["hot","dot","dog","lot","log","cog"] - * - * Output: - * [ - * ["hit","hot","dot","dog","cog"], - * ["hit","hot","lot","log","cog"] - * ] - * - * - * Example 2: - * - * - * Input: - * beginWord = "hit" - * endWord = "cog" - * wordList = ["hot","dot","dog","lot","log"] - * - * Output: [] - * - * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. - * - * - * - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-ladder-ii/ -// discuss: https://leetcode.com/problems/word-ladder-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -假如 A 经过一个字符的变换能得到 B, 则认为 A 与 B 之间有通路, 转化为一个 BFS 找无权图最短路径的问题 - -实现时, 可以先把图构造出来, 复杂度 O(L*N^2) (L 是字符串长度), 也可以每次都回到数组里去找连通点, 时间复杂度不变 - -由于要记录所有的路径, 因此我们需要把每个点的可能前置节点都记录下来, 最后用一个 DFS 或 BFS 找出所有路径 - -暂时想不到更好的办法 -*/ - -use std::collections::HashSet; -use std::collections::VecDeque; -impl Solution { - pub fn find_ladders( - begin_word: String, - end_word: String, - word_list: Vec, - ) -> Vec> { - let mut res = Vec::new(); - let len = word_list.len(); - let target = word_list.iter().position(|s| s == &end_word); - if target.is_none() { - return res; - } - let target = target.unwrap(); - let mut deq = VecDeque::new(); - deq.push_back(target); - // paths record the distance & previous index, we use 'len' to represent empty prev - let mut paths: Vec<(i32, Vec)> = vec![(i32::max_value(), vec![]); len]; - paths[target].0 = 0; - let mut find_shortest = false; - let mut shortest = i32::max_value(); - let mut in_queue = HashSet::new(); - while let Some(i) = deq.pop_front() { - if Solution::connect(&begin_word, &word_list[i]) { - // complete the path using dfs - if paths[i].0 > shortest { - continue; - } - Solution::dfs(i, vec![begin_word.clone()], &word_list, &paths, &mut res); - shortest = paths[i].0; - find_shortest = true; - } - // we have found the shortest path, just drain all the nodes in deq - if find_shortest { - continue; - } - for j in 0..len { - if j == i { - continue; - } - if Solution::connect(&word_list[i], &word_list[j]) { - if paths[i].0 + 1 <= paths[j].0 { - let mut prev = &mut paths[j].1; - prev.push(i); - paths[j].0 = paths[i].0 + 1; - if !in_queue.contains(&j) { - deq.push_back(j); - in_queue.insert(j); - } - } - } - } - } - res - } - - fn dfs( - curr: usize, - mut path: Vec, - words: &Vec, - paths: &Vec<(i32, Vec)>, - res: &mut Vec>, - ) { - path.push(words[curr].clone()); - if paths[curr].1.is_empty() { - res.push(path); - return; - } - for &prev in paths[curr].1.iter() { - Solution::dfs(prev, path.clone(), words, paths, res); - } - } - - #[inline(always)] - fn connect(s1: &str, s2: &str) -> bool { - if s1.len() != s2.len() { - return false; - } - let mut iter1 = s1.chars().into_iter(); - let mut iter2 = s2.chars().into_iter(); - let mut diff = 0; - while let (Some(c1), Some(c2)) = (iter1.next(), iter2.next()) { - if c1 != c2 { - diff += 1; - if diff >= 2 { - return false; - } - } - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_126() { - assert_eq!( - Solution::find_ladders( - "hit".to_owned(), - "cog".to_owned(), - vec_string!["hot", "dot", "dog", "lot", "log", "cog"] - ), - vec![ - vec_string!["hit", "hot", "dot", "dog", "cog"], - vec_string!["hit", "hot", "lot", "log", "cog"], - ] - ); - assert_eq!( - Solution::find_ladders( - "cet".to_owned(), - "ism".to_owned(), - vec_string![ - "kid", "tag", "pup", "ail", "tun", "woo", "erg", "luz", "brr", "gay", "sip", - "kay", "per", "val", "mes", "ohs", "now", "boa", "cet", "pal", "bar", "die", - "war", "hay", "eco", "pub", "lob", "rue", "fry", "lit", "rex", "jan", "cot", - "bid", "ali", "pay", "col", "gum", "ger", "row", "won", "dan", "rum", "fad", - "tut", "sag", "yip", "sui", "ark", "has", "zip", "fez", "own", "ump", "dis", - "ads", "max", "jaw", "out", "btu", "ana", "gap", "cry", "led", "abe", "box", - "ore", "pig", "fie", "toy", "fat", "cal", "lie", "noh", "sew", "ono", "tam", - "flu", "mgm", "ply", "awe", "pry", "tit", "tie", "yet", "too", "tax", "jim", - "san", "pan", "map", "ski", "ova", "wed", "non", "wac", "nut", "why", "bye", - "lye", "oct", "old", "fin", "feb", "chi", "sap", "owl", "log", "tod", "dot", - "bow", "fob", "for", "joe", "ivy", "fan", "age", "fax", "hip", "jib", "mel", - "hus", "sob", "ifs", "tab", "ara", "dab", "jag", "jar", "arm", "lot", "tom", - "sax", "tex", "yum", "pei", "wen", "wry", "ire", "irk", "far", "mew", "wit", - "doe", "gas", "rte", "ian", "pot", "ask", "wag", "hag", "amy", "nag", "ron", - "soy", "gin", "don", "tug", "fay", "vic", "boo", "nam", "ave", "buy", "sop", - "but", "orb", "fen", "paw", "his", "sub", "bob", "yea", "oft", "inn", "rod", - "yam", "pew", "web", "hod", "hun", "gyp", "wei", "wis", "rob", "gad", "pie", - "mon", "dog", "bib", "rub", "ere", "dig", "era", "cat", "fox", "bee", "mod", - "day", "apr", "vie", "nev", "jam", "pam", "new", "aye", "ani", "and", "ibm", - "yap", "can", "pyx", "tar", "kin", "fog", "hum", "pip", "cup", "dye", "lyx", - "jog", "nun", "par", "wan", "fey", "bus", "oak", "bad", "ats", "set", "qom", - "vat", "eat", "pus", "rev", "axe", "ion", "six", "ila", "lao", "mom", "mas", - "pro", "few", "opt", "poe", "art", "ash", "oar", "cap", "lop", "may", "shy", - "rid", "bat", "sum", "rim", "fee", "bmw", "sky", "maj", "hue", "thy", "ava", - "rap", "den", "fla", "auk", "cox", "ibo", "hey", "saw", "vim", "sec", "ltd", - "you", "its", "tat", "dew", "eva", "tog", "ram", "let", "see", "zit", "maw", - "nix", "ate", "gig", "rep", "owe", "ind", "hog", "eve", "sam", "zoo", "any", - "dow", "cod", "bed", "vet", "ham", "sis", "hex", "via", "fir", "nod", "mao", - "aug", "mum", "hoe", "bah", "hal", "keg", "hew", "zed", "tow", "gog", "ass", - "dem", "who", "bet", "gos", "son", "ear", "spy", "kit", "boy", "due", "sen", - "oaf", "mix", "hep", "fur", "ada", "bin", "nil", "mia", "ewe", "hit", "fix", - "sad", "rib", "eye", "hop", "haw", "wax", "mid", "tad", "ken", "wad", "rye", - "pap", "bog", "gut", "ito", "woe", "our", "ado", "sin", "mad", "ray", "hon", - "roy", "dip", "hen", "iva", "lug", "asp", "hui", "yak", "bay", "poi", "yep", - "bun", "try", "lad", "elm", "nat", "wyo", "gym", "dug", "toe", "dee", "wig", - "sly", "rip", "geo", "cog", "pas", "zen", "odd", "nan", "lay", "pod", "fit", - "hem", "joy", "bum", "rio", "yon", "dec", "leg", "put", "sue", "dim", "pet", - "yaw", "nub", "bit", "bur", "sid", "sun", "oil", "red", "doc", "moe", "caw", - "eel", "dix", "cub", "end", "gem", "off", "yew", "hug", "pop", "tub", "sgt", - "lid", "pun", "ton", "sol", "din", "yup", "jab", "pea", "bug", "gag", "mil", - "jig", "hub", "low", "did", "tin", "get", "gte", "sox", "lei", "mig", "fig", - "lon", "use", "ban", "flo", "nov", "jut", "bag", "mir", "sty", "lap", "two", - "ins", "con", "ant", "net", "tux", "ode", "stu", "mug", "cad", "nap", "gun", - "fop", "tot", "sow", "sal", "sic", "ted", "wot", "del", "imp", "cob", "way", - "ann", "tan", "mci", "job", "wet", "ism", "err", "him", "all", "pad", "hah", - "hie", "aim", "ike", "jed", "ego", "mac", "baa", "min", "com", "ill", "was", - "cab", "ago", "ina", "big", "ilk", "gal", "tap", "duh", "ola", "ran", "lab", - "top", "gob", "hot", "ora", "tia", "kip", "han", "met", "hut", "she", "sac", - "fed", "goo", "tee", "ell", "not", "act", "gil", "rut", "ala", "ape", "rig", - "cid", "god", "duo", "lin", "aid", "gel", "awl", "lag", "elf", "liz", "ref", - "aha", "fib", "oho", "tho", "her", "nor", "ace", "adz", "fun", "ned", "coo", - "win", "tao", "coy", "van", "man", "pit", "guy", "foe", "hid", "mai", "sup", - "jay", "hob", "mow", "jot", "are", "pol", "arc", "lax", "aft", "alb", "len", - "air", "pug", "pox", "vow", "got", "meg", "zoe", "amp", "ale", "bud", "gee", - "pin", "dun", "pat", "ten", "mob" - ] - ), - vec![ - vec_string![ - "cet", "get", "gee", "gte", "ate", "ats", "its", "ito", "ibo", "ibm", "ism" - ], - vec_string![ - "cet", "cat", "can", "ian", "inn", "ins", "its", "ito", "ibo", "ibm", "ism" - ], - vec_string![ - "cet", "cot", "con", "ion", "inn", "ins", "its", "ito", "ibo", "ibm", "ism" - ], - ] - ); - } -} diff --git a/src/solution/s0127_word_ladder.rs b/src/solution/s0127_word_ladder.rs deleted file mode 100644 index a67465fa..00000000 --- a/src/solution/s0127_word_ladder.rs +++ /dev/null @@ -1,132 +0,0 @@ -/** - * [127] Word Ladder - * - * Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: - * - *
    - * Only one letter can be changed at a time. - * Each transformed word must exist in the word list. Note that beginWord is not a transformed word. - *
- * - * Note: - * - * - * Return 0 if there is no such transformation sequence. - * All words have the same length. - * All words contain only lowercase alphabetic characters. - * You may assume no duplicates in the word list. - * You may assume beginWord and endWord are non-empty and are not the same. - * - * - * Example 1: - * - * - * Input: - * beginWord = "hit", - * endWord = "cog", - * wordList = ["hot","dot","dog","lot","log","cog"] - * - * Output: 5 - * - * Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", - * return its length 5. - * - * - * Example 2: - * - * - * Input: - * beginWord = "hit" - * endWord = "cog" - * wordList = ["hot","dot","dog","lot","log"] - * - * Output: 0 - * - * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-ladder/ -// discuss: https://leetcode.com/problems/word-ladder/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashSet; -use std::collections::VecDeque; -impl Solution { - pub fn ladder_length(begin_word: String, end_word: String, word_list: Vec) -> i32 { - let len = word_list.len(); - let target = word_list.iter().position(|s| s == &end_word); - if target.is_none() { - return 0; - } - let target = target.unwrap(); - let mut deq = VecDeque::new(); - let mut distance = vec![0; len]; - let mut remain = (0..len).collect::>(); - deq.push_back(target); - remain.remove(&target); - while let Some(i) = deq.pop_front() { - if Solution::connect(&begin_word, &word_list[i]) { - return distance[i] + 2; - } - remain.retain(|&j| { - if Solution::connect(&word_list[i], &word_list[j]) { - distance[j] = distance[i] + 1; - deq.push_back(j); - false - } else { - true - } - }); - } - 0 - } - - #[inline(always)] - fn connect(s1: &str, s2: &str) -> bool { - if s1.len() != s2.len() { - return false; - } - let mut iter1 = s1.chars().into_iter(); - let mut iter2 = s2.chars().into_iter(); - let mut diff = 0; - while let (Some(c1), Some(c2)) = (iter1.next(), iter2.next()) { - if c1 != c2 { - diff += 1; - if diff >= 2 { - return false; - } - } - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_127() { - assert_eq!( - Solution::ladder_length( - "hit".to_owned(), - "cog".to_owned(), - vec_string!["hot", "dot", "dog", "lot", "log", "cog"] - ), - 5 - ); - assert_eq!( - Solution::ladder_length( - "hit".to_owned(), - "cog".to_owned(), - vec_string!["hot", "dot", "dog", "lot", "log"] - ), - 0 - ); - } -} diff --git a/src/solution/s0128_longest_consecutive_sequence.rs b/src/solution/s0128_longest_consecutive_sequence.rs deleted file mode 100644 index f0e0806f..00000000 --- a/src/solution/s0128_longest_consecutive_sequence.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [128] Longest Consecutive Sequence - * - * Given an unsorted array of integers, find the length of the longest consecutive elements sequence. - * - * Your algorithm should run in O(n) complexity. - * - * Example: - * - * - * Input: [100, 4, 200, 1, 3, 2] - * Output: 4 - * Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-consecutive-sequence/ -// discuss: https://leetcode.com/problems/longest-consecutive-sequence/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -要找到连续子串, 基本策略就是对每个 num, 判断 num+1, num+2, num+3... 是否在数组中, 直到不再连续 - -工程里写的话用排序是最清晰可维护的(需求变了很好改), 排序之后查找 num+1 是否存在就只需要 O(1) 的复杂度了: -看下一个元素是不是 num+1 即可 - -但题目一定要求 O(N) 的解法, 只能想些奇怪的办法了, HashSet 也能达到 O(1) 的查找效率. 但假如对每个元素 -都做一遍, 最差就是 O(N^2) 了, 可以发现对于一个连续序列 1,2,3,4,5,6 我们从 1 开始查就能找到这个序列, -从 2,3,4,5,6 开始查都是在做重复计算, 因此对于一个 num, 假如 num-1 存在于 HashSet 中, 我们就不需要考虑 -它了, 因为它是一次重复的计算. -*/ -use std::collections::HashSet; -impl Solution { - pub fn longest_consecutive(nums: Vec) -> i32 { - let mut max = 0; - let nums = nums.into_iter().collect::>(); - for &num in nums.iter() { - if !nums.contains(&(num - 1)) { - let mut curr = num; - let mut curr_max = 1; - while nums.contains(&(curr + 1)) { - curr += 1; - curr_max += 1; - } - max = i32::max(curr_max, max); - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_128() { - assert_eq!(Solution::longest_consecutive(vec![100, 4, 200, 1, 3, 2]), 4) - } -} diff --git a/src/solution/s0129_sum_root_to_leaf_numbers.rs b/src/solution/s0129_sum_root_to_leaf_numbers.rs deleted file mode 100644 index 1e44fb68..00000000 --- a/src/solution/s0129_sum_root_to_leaf_numbers.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [129] Sum Root to Leaf Numbers - * - * Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. - * - * An example is the root-to-leaf path 1->2->3 which represents the number 123. - * - * Find the total sum of all root-to-leaf numbers. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * - * Input: [1,2,3] - * 1 - * / \ - * 2 3 - * Output: 25 - * Explanation: - * The root-to-leaf path 1->2 represents the number 12. - * The root-to-leaf path 1->3 represents the number 13. - * Therefore, sum = 12 + 13 = 25. - * - * Example 2: - * - * - * Input: [4,9,0,5,1] - * 4 - * / \ - * 9 0 - * / \ - * 5 1 - * Output: 1026 - * Explanation: - * The root-to-leaf path 4->9->5 represents the number 495. - * The root-to-leaf path 4->9->1 represents the number 491. - * The root-to-leaf path 4->0 represents the number 40. - * Therefore, sum = 495 + 491 + 40 = 1026. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/sum-root-to-leaf-numbers/ -// discuss: https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn sum_numbers(root: Option>>) -> i32 { - let mut sum = 0; - if root.is_none() { - return sum; - } - let mut deq = VecDeque::new(); - deq.push_back((root.clone(), 0)); - while let Some(item) = deq.pop_front() { - if let (Some(node), acc) = item { - let acc = acc * 10 + node.borrow().val; - if node.borrow().left.is_none() && node.borrow().right.is_none() { - sum += acc; - continue; - } - deq.push_back((node.borrow().left.clone(), acc)); - deq.push_back((node.borrow().right.clone(), acc)); - } - } - sum - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_129() { - assert_eq!(Solution::sum_numbers(tree![1, 2, 3]), 25); - assert_eq!(Solution::sum_numbers(tree![4, 9, 0, 5, 1]), 1026); - } -} diff --git a/src/solution/s0130_surrounded_regions.rs b/src/solution/s0130_surrounded_regions.rs deleted file mode 100644 index 411286b4..00000000 --- a/src/solution/s0130_surrounded_regions.rs +++ /dev/null @@ -1,221 +0,0 @@ -/** - * [130] Surrounded Regions - * - * Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. - * - * A region is captured by flipping all 'O's into 'X's in that surrounded region. - * - * Example: - * - * - * X X X X - * X O O X - * X X O X - * X O X X - * - * - * After running your function, the board should be: - * - * - * X X X X - * X X X X - * X X X X - * X O X X - * - * - * Explanation: - * - * Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/surrounded-regions/ -// discuss: https://leetcode.com/problems/surrounded-regions/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -从最外层开始, 基于为 'O' 的格子做 DFS, 将与边界连接的所有 'O' 标记为一个特殊 char, 最后将没有标记到的 'O' 全部标记为 'X' -*/ -impl Solution { - pub fn solve(board: &mut Vec>) { - if board.is_empty() || board[0].is_empty() { - return; - } - let (height, width) = (board.len(), board[0].len()); - // 遍历最外层的 4 条边 - for j in 0..width { - Solution::dfs(0, j, height, width, board); - Solution::dfs(height - 1, j, height, width, board); - } - for i in 1..height - 1 { - Solution::dfs(i, 0, height, width, board); - Solution::dfs(i, width - 1, height, width, board); - } - for k in 0..height * width { - board[k / width][k % width] = if board[k / width][k % width] == '_' { - 'O' - } else { - 'X' - } - } - } - - fn dfs(i: usize, j: usize, height: usize, width: usize, board: &mut Vec>) { - if board[i][j] == 'O' { - board[i][j] = '_'; - if i > 1 { - Solution::dfs(i - 1, j, height, width, board) - } - if j > 1 { - Solution::dfs(i, j - 1, height, width, board) - } - if i + 1 < height { - Solution::dfs(i + 1, j, height, width, board) - } - if j + 1 < width { - Solution::dfs(i, j + 1, height, width, board) - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_130() { - let mut matrix = vec![ - vec!['X', 'X', 'X', 'X'], - vec!['X', 'O', 'O', 'X'], - vec!['X', 'X', 'O', 'X'], - vec!['X', 'O', 'X', 'X'], - ]; - Solution::solve(&mut matrix); - assert_eq!( - matrix, - vec![ - vec!['X', 'X', 'X', 'X'], - vec!['X', 'X', 'X', 'X'], - vec!['X', 'X', 'X', 'X'], - vec!['X', 'O', 'X', 'X'], - ] - ); - - let mut matrix = vec![ - vec!['X', 'X', 'X', 'X'], - vec!['X', 'O', 'O', 'X'], - vec!['X', 'O', 'O', 'X'], - vec!['X', 'X', 'X', 'X'], - ]; - Solution::solve(&mut matrix); - assert_eq!( - matrix, - vec![ - vec!['X', 'X', 'X', 'X'], - vec!['X', 'X', 'X', 'X'], - vec!['X', 'X', 'X', 'X'], - vec!['X', 'X', 'X', 'X'], - ] - ); - - let mut matrix = vec![ - vec!['X', 'X', 'X', 'X'], - vec!['O', 'X', 'O', 'X'], - vec!['O', 'X', 'O', 'X'], - vec!['X', 'O', 'X', 'X'], - ]; - Solution::solve(&mut matrix); - assert_eq!( - matrix, - vec![ - vec!['X', 'X', 'X', 'X'], - vec!['O', 'X', 'X', 'X'], - vec!['O', 'X', 'X', 'X'], - vec!['X', 'O', 'X', 'X'], - ] - ); - - let mut matrix = vec![ - vec!['X', 'X', 'X', 'X', 'O', 'X'], - vec!['O', 'X', 'X', 'O', 'O', 'X'], - vec!['X', 'O', 'X', 'O', 'O', 'O'], - vec!['X', 'O', 'O', 'O', 'X', 'O'], - vec!['O', 'O', 'X', 'X', 'O', 'X'], - vec!['X', 'O', 'X', 'O', 'X', 'X'], - ]; - Solution::solve(&mut matrix); - assert_eq!( - matrix, - vec![ - vec!['X', 'X', 'X', 'X', 'O', 'X'], - vec!['O', 'X', 'X', 'O', 'O', 'X'], - vec!['X', 'O', 'X', 'O', 'O', 'O'], - vec!['X', 'O', 'O', 'O', 'X', 'O'], - vec!['O', 'O', 'X', 'X', 'X', 'X'], - vec!['X', 'O', 'X', 'O', 'X', 'X'], - ] - ); - - let mut matrix = vec![ - vec![ - 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'O', 'X', 'O', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - ]; - Solution::solve(&mut matrix); - assert_eq!( - matrix, - vec![ - vec![ - 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X' - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X' - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'O', 'X', 'O', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X' - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', - 'X', 'X', 'X', 'X' - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X' - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X' - ] - ] - ); - } -} diff --git a/src/solution/s0131_palindrome_partitioning.rs b/src/solution/s0131_palindrome_partitioning.rs deleted file mode 100644 index 22a92dfd..00000000 --- a/src/solution/s0131_palindrome_partitioning.rs +++ /dev/null @@ -1,120 +0,0 @@ -/** - * [131] Palindrome Partitioning - * - * Given a string s, partition s such that every substring of the partition is a palindrome. - * - * Return all possible palindrome partitioning of s. - * - * Example: - * - * - * Input: "aab" - * Output: - * [ - * ["aa","b"], - * ["a","a","b"] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/palindrome-partitioning/ -// discuss: https://leetcode.com/problems/palindrome-partitioning/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -记 n 个字符的回文拆分方式是 f(n) 种, 则: - -f(n) = (0..n).iter().fold(0, |acc, i| { - if is_palindrome(s[i..n]) { acc + f(i-1) } else { acc } -}) - -按这种方式向上递推即可, 时间复杂度为 O(N^3), 空间复杂度 O(N), 显然, is_palindrome 这一步仍然有重复计算 - -is_palindrome(s[i..n]) = s[i] == s[n] && is_palindrome(s[i+1..n-1]) - -存储所有 i, n 的 is_palindrome 结果, 则可以优化 is_palindrome 的时间到 O(1) - -最后的复杂度: 时间 O(N^2), 空间 O(N^2) -*/ -impl Solution { - pub fn partition(s: String) -> Vec> { - let s = s.chars().collect::>(); - if s.is_empty() { - return Vec::new(); - } - let mut palindrome_cache = vec![vec![None; s.len()]; s.len()]; - let mut res: Vec>> = Vec::with_capacity(s.len()); - res.push(vec![vec![(0, 1)]]); - for n in 1..s.len() { - let mut curr: Vec> = Vec::new(); - for i in 0..n + 1 { - if Solution::is_palindrome(&mut palindrome_cache, &s, i, n) { - if i > 0 { - for vec in res[i - 1].iter() { - let mut new_vec = vec.clone(); - new_vec.push((i, n + 1)); - curr.push(new_vec); - } - } else { - curr.push(vec![(i, n + 1)]); - } - } - } - res.push(curr); - } - (*res[s.len() - 1]) - .into_iter() - .map(|vec| { - vec.iter() - .map(|&range| s[range.0..range.1].iter().collect::()) - .collect::>() - }) - .collect() - } - - fn is_palindrome( - cache: &mut Vec>>, - s: &Vec, - i: usize, - j: usize, - ) -> bool { - if j <= i { - return true; - } - if let Some(result) = cache[i][j] { - result - } else { - let result = s[i] == s[j] - && (i + 1 > s.len() || j < 1 || Solution::is_palindrome(cache, s, i + 1, j - 1)); - cache[i][j] = Some(result); - result - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_131() { - assert_eq!( - Solution::partition("aab".to_owned()), - vec![vec_string!["aa", "b"], vec_string!["a", "a", "b"],] - ); - assert_eq!( - Solution::partition("aaa".to_owned()), - vec![ - vec_string!["aaa"], - vec_string!["a", "aa"], - vec_string!["aa", "a"], - vec_string!["a", "a", "a"], - ] - ); - } -} diff --git a/src/solution/s0132_palindrome_partitioning_ii.rs b/src/solution/s0132_palindrome_partitioning_ii.rs deleted file mode 100644 index 81b75cf6..00000000 --- a/src/solution/s0132_palindrome_partitioning_ii.rs +++ /dev/null @@ -1,91 +0,0 @@ -/** - * [132] Palindrome Partitioning II - * - * Given a string s, partition s such that every substring of the partition is a palindrome. - * - * Return the minimum cuts needed for a palindrome partitioning of s. - * - * Example: - * - * - * Input: "aab" - * Output: 1 - * Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/palindrome-partitioning-ii/ -// discuss: https://leetcode.com/problems/palindrome-partitioning-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -为了方便讨论, 我们记 n 个字符的最少回文分段是 f(n), 则切分次数为 f(n)-1, 接下来递推 f(n): - -f(n) = min(f(n-i) + 1) { i in [0..n] and s[i..n] is palindrome } - -显然, f(1) 为 1, f(0) 为 0 - -判断 is_palindrome 也需要优化, 使用一个备忘录, 将判断回文的操作优化到 O(1): - -is_palindrome(s[i..n]) = s[i] == s[n] && is_palindrome(s[i+1..n-1]) - -最后的复杂度: 时间 O(N^2), 空间 O(N^2) -*/ -impl Solution { - pub fn min_cut(s: String) -> i32 { - let s = s.chars().collect::>(); - if s.is_empty() { - return 0; - } - let mut palindrome_cache: Vec>> = vec![vec![None; s.len()]; s.len()]; - let mut min = Vec::with_capacity(s.len() + 1); - min.push(0); - min.push(1); - for i in 1..s.len() { - let mut local_min = i32::max_value(); - for j in 0..i + 1 { - if Solution::is_palindrome(&mut palindrome_cache, &s, j, i) { - local_min = i32::min(1 + min[j], local_min); - } - } - min.push(local_min); - } - min[s.len()] - 1 - } - - fn is_palindrome( - cache: &mut Vec>>, - s: &Vec, - i: usize, - j: usize, - ) -> bool { - if j <= i { - return true; - } - if let Some(result) = cache[i][j] { - result - } else { - let result = s[i] == s[j] - && (i + 1 > s.len() || j < 1 || Solution::is_palindrome(cache, s, i + 1, j - 1)); - cache[i][j] = Some(result); - result - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_132() { - assert_eq!(Solution::min_cut("aab".to_owned()), 1); - assert_eq!(Solution::min_cut("aaa".to_owned()), 0); - assert_eq!(Solution::min_cut("aabb".to_owned()), 1); - } -} diff --git a/src/solution/s0134_gas_station.rs b/src/solution/s0134_gas_station.rs deleted file mode 100644 index 352990f9..00000000 --- a/src/solution/s0134_gas_station.rs +++ /dev/null @@ -1,77 +0,0 @@ -/** - * [134] Gas Station - * - * There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. - * - * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. - * - * Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. - * - * Note: - * - * - * If there exists a solution, it is guaranteed to be unique. - * Both input arrays are non-empty and have the same length. - * Each element in the input arrays is a non-negative integer. - * - * - * Example 1: - * - * - * Input: - * gas = [1,2,3,4,5] - * cost = [3,4,5,1,2] - * - * Output: 3 - * - * Explanation: - * Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 - * Travel to station 4. Your tank = 4 - 1 + 5 = 8 - * Travel to station 0. Your tank = 8 - 2 + 1 = 7 - * Travel to station 1. Your tank = 7 - 3 + 2 = 6 - * Travel to station 2. Your tank = 6 - 4 + 3 = 5 - * Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. - * Therefore, return 3 as the starting index. - * - * - * Example 2: - * - * - * Input: - * gas = [2,3,4] - * cost = [3,4,3] - * - * Output: -1 - * - * Explanation: - * You can't start at station 0 or 1, as there is not enough gas to travel to the next station. - * Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 - * Travel to station 0. Your tank = 4 - 3 + 2 = 3 - * Travel to station 1. Your tank = 3 - 3 + 3 = 3 - * You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. - * Therefore, you can't travel around the circuit once no matter where you start. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/gas-station/ -// discuss: https://leetcode.com/problems/gas-station/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn can_complete_circuit(gas: Vec, cost: Vec) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_134() {} -} diff --git a/src/solution/s0135_candy.rs b/src/solution/s0135_candy.rs deleted file mode 100644 index debb29d0..00000000 --- a/src/solution/s0135_candy.rs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * [135] Candy - * - * There are N children standing in a line. Each child is assigned a rating value. - * - * You are giving candies to these children subjected to the following requirements: - * - * - * Each child must have at least one candy. - * Children with a higher rating get more candies than their neighbors. - * - * - * What is the minimum candies you must give? - * - * Example 1: - * - * - * Input: [1,0,2] - * Output: 5 - * Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. - * - * - * Example 2: - * - * - * Input: [1,2,2] - * Output: 4 - * Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. - * The third child gets 1 candy because it satisfies the above two conditions. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/candy/ -// discuss: https://leetcode.com/problems/candy/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn candy(ratings: Vec) -> i32 { - let mut from = 0; - let mut n = 1; - let mut last = 1; - let mut ascending = false; - for i in 1..ratings.len() { - if ratings[i] == ratings[i - 1] { - n += 1; - from = i; - ascending = false; - } else if ratings[i] >= ratings[i - 1] { - from = i; - ascending = true; - last += 1; - n += last; - } else { - if ascending { - last = 1; - from = i; - ascending = false; - } - n += (i - from + 1) as i32; - } - } - n - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_135() { - assert_eq!(Solution::candy(vec![3, 2, 1, 2, 3]), 11); - assert_eq!(Solution::candy(vec![2, 2, 1, 2, 2]), 7); - assert_eq!(Solution::candy(vec![1, 0, 2]), 5); - assert_eq!(Solution::candy(vec![1, 2, 2]), 4); - assert_eq!(Solution::candy(vec![1, 1, 1, 1, 1, 1]), 6); - assert_eq!(Solution::candy(vec![1, 2, 2, 2, 2, 2, 2, 0]), 10); - } -} diff --git a/src/solution/s0136_single_number.rs b/src/solution/s0136_single_number.rs index 580d1213..83973e54 100644 --- a/src/solution/s0136_single_number.rs +++ b/src/solution/s0136_single_number.rs @@ -1,41 +1,40 @@ /** * [136] Single Number * - * Given a non-empty array of integers, every element appears twice except for one. Find that single one. - * - * Note: - * - * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? + * Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. + * You must implement a solution with a linear runtime complexity and use only constant extra space. * * Example 1: - * - * - * Input: [2,2,1] + * Input: nums = [2,2,1] * Output: 1 * - * * Example 2: - * - * - * Input: [4,1,2,1,2] + * Input: nums = [4,1,2,1,2] * Output: 4 * + * Example 3: + * Input: nums = [1] + * Output: 1 + * + * Constraints: * + * 1 <= nums.length <= 3 * 104 + * -3 * 104 <= nums[i] <= 3 * 104 + * Each element in the array appears twice except for one element which appears only once. */ -pub struct Solution {} -// problem: https://leetcode.com/problems/single-number/ -// discuss: https://leetcode.com/problems/single-number/discuss/?currentPage=1&orderBy=most_votes&query= +pub struct Solution {} -// submission codes start here impl Solution { pub fn single_number(nums: Vec) -> i32 { - nums.iter().fold(0, |acc, &num| acc ^ num) + let mut single = 0; + for num in nums { + single ^= num; + } + single } } -// submission codes end - #[cfg(test)] mod tests { use super::*; @@ -43,6 +42,9 @@ mod tests { #[test] fn test_136() { assert_eq!(Solution::single_number(vec![2, 2, 1]), 1); + assert_eq!(Solution::single_number(vec![4, 1, 2, 1, 2]), 4); + + assert_eq!(Solution::single_number(vec![1]), 1); } } diff --git a/src/solution/s0137_single_number_ii.rs b/src/solution/s0137_single_number_ii.rs deleted file mode 100644 index 5e99cd84..00000000 --- a/src/solution/s0137_single_number_ii.rs +++ /dev/null @@ -1,94 +0,0 @@ -/** - * [137] Single Number II - * - * Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. - * - * Note: - * - * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? - * - * Example 1: - * - * - * Input: [2,2,3,2] - * Output: 3 - * - * - * Example 2: - * - * - * Input: [0,1,0,1,0,1,99] - * Output: 99 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/single-number-ii/ -// discuss: https://leetcode.com/problems/single-number-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -糅合了一下 https://leetcode.com/problems/single-number-ii/discuss/43296/An-General-Way-to-Handle-All-this-sort-of-questions. 和 https://leetcode.com/problems/single-number-ii/discuss/43294/Challenge-me-thx - -第一个链接给出了通用解法: 对于一个数出现 M 次其它数都出现了 K 的场景, 我们可以用位运算记录 K 种状态(作为一个计数器)来解 - -这题的真值表(3种状态使用2位): - -a b c/c a'b'/a'b' -0 0 1/0 0 1 /0 0 -0 1 1/0 1 0 /0 1 -1 0 1/0 0 0 /1 0 - -根据数电的知识, 要根据这个真值表写出逻辑表达式, 以输出端为 '1' 的结果为准, 将每行的输入变量写成 AND 形式, 其中为 0 的输入量需要取反, 再将这几个 AND 形式做 OR 即可 - -令 a' = 1, 则: - -a b c a' -0 1 1 1 ~a & b & c -1 0 0 1 a & ~b & ~c - -a' = (~a & b & c) | (a & ~b & ~c) - -同理: - -b' = (~a & b & ~c) | (~a & ~b & c) - -这个每轮计算的位次数达到 17 次, 可以再优化一下: - -对 b' 化简: b' = ~a & (b & ~c | ~b & c) = ~a & b ^ c - -但这时 a 仍然比较复杂, 我们可以考虑能否用每轮算出的 b' 来简化 a 的计算, 则: - -a (b) b' c a' b' -1 (0) 0 0 1 0 -0 (1) 0 1 1 0 - -重写一下就是 a' = (a & ~b' & ~c) | (~a & ~b' & c) = ~b' & (a & ~c | ~a & c) = ~b' & a ^ c - -这个就和最开始第二链接里给出的超简洁解法一致了 - -最后的话, a 或 b 为 1 都可以输出到 1 (目标数出现1次或出现2次), 输出 a | b 即可 -*/ -impl Solution { - pub fn single_number(nums: Vec) -> i32 { - let (mut a, mut b) = (0, 0); - for &num in nums.iter() { - b = !a & (b ^ num); - a = !b & (a ^ num); - } - return a | b; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_137() { - assert_eq!(Solution::single_number(vec![0, 0, 0, 1, 1, 1, 5]), 5); - } -} diff --git a/src/solution/s0139_word_break.rs b/src/solution/s0139_word_break.rs deleted file mode 100644 index ce9e2684..00000000 --- a/src/solution/s0139_word_break.rs +++ /dev/null @@ -1,93 +0,0 @@ -/** - * [139] Word Break - * - * Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. - * - * Note: - * - * - * The same word in the dictionary may be reused multiple times in the segmentation. - * You may assume the dictionary does not contain duplicate words. - * - * - * Example 1: - * - * - * Input: s = "leetcode", wordDict = ["leet", "code"] - * Output: true - * Explanation: Return true because "leetcode" can be segmented as "leet code". - * - * - * Example 2: - * - * - * Input: s = "applepenapple", wordDict = ["apple", "pen"] - * Output: true - * Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". - * Note that you are allowed to reuse a dictionary word. - * - * - * Example 3: - * - * - * Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] - * Output: false - * - * - */ -pub struct Solution {} - -/* -记 f[n] 表示从 0 开始长度为 n 的 substring 是否可以被组成,那么: - -f[n] = f[k] && (s[k..n] in dict) -f[0] = true - -DP 向上递推即可 - -BFS 也是可以的 -*/ - -// problem: https://leetcode.com/problems/word-break/ -// discuss: https://leetcode.com/problems/word-break/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashSet; -impl Solution { - pub fn word_break(s: String, word_dict: Vec) -> bool { - let word_dict = word_dict.into_iter().collect::>(); - let mut dp = vec![false; s.len() + 1]; - dp[0] = true; - for i in 1..s.len() + 1 { - for j in 0..s.len() { - if dp[j] && word_dict.contains(&s[j..i]) { - dp[i] = true; - } - } - } - dp[s.len()] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_139() { - assert_eq!( - Solution::word_break("leetcode".to_owned(), vec_string!["leet", "code"]), - true - ); - assert_eq!( - Solution::word_break( - "catsandog".to_owned(), - vec_string!["cats", "dog", "sand", "and", "cat"] - ), - false - ); - } -} diff --git a/src/solution/s0140_word_break_ii.rs b/src/solution/s0140_word_break_ii.rs deleted file mode 100644 index 68c1319e..00000000 --- a/src/solution/s0140_word_break_ii.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [140] Word Break II - * - * Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. - * - * Note: - * - * - * The same word in the dictionary may be reused multiple times in the segmentation. - * You may assume the dictionary does not contain duplicate words. - * - * - * Example 1: - * - * - * Input: - * s = "catsanddog" - * wordDict = ["cat", "cats", "and", "sand", "dog"] - * Output: - * [ - * "cats and dog", - * "cat sand dog" - * ] - * - * - * Example 2: - * - * - * Input: - * s = "pineapplepenapple" - * wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] - * Output: - * [ - * "pine apple pen apple", - * "pineapple pen apple", - * "pine applepen apple" - * ] - * Explanation: Note that you are allowed to reuse a dictionary word. - * - * - * Example 3: - * - * - * Input: - * s = "catsandog" - * wordDict = ["cats", "dog", "sand", "and", "cat"] - * Output: - * [] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-break-ii/ -// discuss: https://leetcode.com/problems/word-break-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn word_break(s: String, word_dict: Vec) -> Vec { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_140() {} -} diff --git a/src/solution/s0143_reorder_list.rs b/src/solution/s0143_reorder_list.rs deleted file mode 100644 index 1a7854cc..00000000 --- a/src/solution/s0143_reorder_list.rs +++ /dev/null @@ -1,50 +0,0 @@ -/** - * [143] Reorder List - * - * Given a singly linked list L: L0→L1→…→Ln-1→Ln,
- * reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… - * - * You may not modify the values in the list's nodes, only nodes itself may be changed. - * - * Example 1: - * - * - * Given 1->2->3->4, reorder it to 1->4->2->3. - * - * Example 2: - * - * - * Given 1->2->3->4->5, reorder it to 1->5->2->4->3. - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/reorder-list/ -// discuss: https://leetcode.com/problems/reorder-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* - 1->2->3->4->5 - - 1->2->3<-4<-5 - - 1->5->2->4->3 -*/ -impl Solution { - pub fn reorder_list(head: &mut Option>) { - // TODO - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_143() {} -} diff --git a/src/solution/s0144_binary_tree_preorder_traversal.rs b/src/solution/s0144_binary_tree_preorder_traversal.rs deleted file mode 100644 index 3d823976..00000000 --- a/src/solution/s0144_binary_tree_preorder_traversal.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [144] Binary Tree Preorder Traversal - * - * Given a binary tree, return the preorder traversal of its nodes' values. - * - * Example: - * - * - * Input: [1,null,2,3] - * 1 - * \ - * 2 - * / - * 3 - * - * Output: [1,2,3] - * - * - * Follow up: Recursive solution is trivial, could you do it iteratively? - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-preorder-traversal/ -// discuss: https://leetcode.com/problems/binary-tree-preorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn preorder_traversal(root: Option>>) -> Vec { - let mut res = Vec::new(); - Solution::helper(root, &mut res); - res - } - - fn helper(root: Option>>, vec: &mut Vec) { - if let Some(node) = root { - vec.push(node.borrow().val); - Solution::helper(node.borrow().left.clone(), vec); - Solution::helper(node.borrow().right.clone(), vec); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_144() { - assert_eq!( - Solution::preorder_traversal(tree![1, null, 2, 3]), - vec![1, 2, 3] - ); - } -} diff --git a/src/solution/s0145_binary_tree_postorder_traversal.rs b/src/solution/s0145_binary_tree_postorder_traversal.rs deleted file mode 100644 index 63197e88..00000000 --- a/src/solution/s0145_binary_tree_postorder_traversal.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [145] Binary Tree Postorder Traversal - * - * Given a binary tree, return the postorder traversal of its nodes' values. - * - * Example: - * - * - * Input: [1,null,2,3] - * 1 - * \ - * 2 - * / - * 3 - * - * Output: [3,2,1] - * - * - * Follow up: Recursive solution is trivial, could you do it iteratively? - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-postorder-traversal/ -// discuss: https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn postorder_traversal(root: Option>>) -> Vec { - let mut res = Vec::new(); - Solution::helper(root, &mut res); - res - } - - fn helper(root: Option>>, vec: &mut Vec) { - if let Some(node) = root { - Solution::helper(node.borrow().left.clone(), vec); - Solution::helper(node.borrow().right.clone(), vec); - vec.push(node.borrow().val); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_145() { - assert_eq!( - Solution::postorder_traversal(tree![1, null, 2, 3]), - vec![3, 2, 1] - ); - } -} diff --git a/src/solution/s0146_lru_cache.rs b/src/solution/s0146_lru_cache.rs deleted file mode 100644 index 226cbf77..00000000 --- a/src/solution/s0146_lru_cache.rs +++ /dev/null @@ -1,200 +0,0 @@ -/** - * [146] LRU Cache - * - * - * Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. - * - * - * - * get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
- * put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. - * - * - * Follow up:
- * Could you do both operations in O(1) time complexity? - * - * Example: - * - * LRUCache cache = new LRUCache( 2 /* capacity */ ); - * - * cache.put(1, 1); - * cache.put(2, 2); - * cache.get(1); // returns 1 - * cache.put(3, 3); // evicts key 2 - * cache.get(2); // returns -1 (not found) - * cache.put(4, 4); // evicts key 1 - * cache.get(1); // returns -1 (not found) - * cache.get(3); // returns 3 - * cache.get(4); // returns 4 - * - * - */ -// problem: https://leetcode.com/problems/lru-cache/ -// discuss: https://leetcode.com/problems/lru-cache/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -Least Recently Used, 最近最少使用, 关键在于追踪每一个 entry 的 age, 每次淘汰最小的那一个 key - -假如淘汰逻辑要做到 O(1) 复杂度, 我们可以引入一个链表, 每次 touch 一个值时, 就删掉它重新 push_back, 而当达到容量要驱逐时, 则 pop_front - -Rust 的链表不支持根据引用删除任意元素,也没有 LinkedHashMap,需要自己实现一个 -*/ -use std::collections::HashMap; -use std::mem; -use std::ptr; - -// Entry is either a map entry and a link-list node -pub struct LRUEntry { - key: i32, - val: i32, - prev: *mut LRUEntry, - next: *mut LRUEntry, -} - -impl LRUEntry { - pub fn new(key: i32, val: i32) -> Self { - LRUEntry { - key: key, - val: val, - prev: ptr::null_mut(), - next: ptr::null_mut(), - } - } -} - -pub struct LRUCache { - map: HashMap>, - cap: usize, - - // head and tail is dummy node of the double-linked-list - head: *mut LRUEntry, - tail: *mut LRUEntry, -} - -impl LRUCache { - pub fn new(capacity: i32) -> Self { - let capacity = capacity as usize; - let map = HashMap::with_capacity(capacity); - let cache = LRUCache { - map: map, - cap: capacity, - head: unsafe { Box::into_raw(Box::new(mem::uninitialized::())) }, - tail: unsafe { Box::into_raw(Box::new(mem::uninitialized::())) }, - }; - unsafe { - (*cache.head).next = cache.tail; - (*cache.tail).prev = cache.head; - } - - cache - } - - pub fn get(&mut self, key: i32) -> i32 { - let (ptr, val) = match self.map.get_mut(&key) { - None => (None, None), - Some(entry) => { - let ptr: *mut LRUEntry = &mut **entry; - (Some(ptr), Some(unsafe { (*entry).val })) - } - }; - - if let Some(ptr) = ptr { - self.detach(ptr); - self.push(ptr); - } - val.unwrap_or(-1) - } - - pub fn put(&mut self, key: i32, value: i32) { - let ptr = self.map.get_mut(&key).map(|entry| { - let ptr: *mut LRUEntry = &mut **entry; - ptr - }); - - match ptr { - Some(ptr) => { - // key already exist, update it - unsafe { (*ptr).val = value }; - self.detach(ptr); - self.push(ptr); - } - None => { - // insert new key, cache is full, evict - if self.map.len() == self.cap { - let mut old_entry = self.pop().unwrap(); - old_entry.key = key; - old_entry.val = value; - self.push(&mut *old_entry); - self.map.insert(key, old_entry); - } else { - let mut new_entry = Box::new(LRUEntry::new(key, value)); - self.push(&mut *new_entry); - self.map.insert(key, new_entry); - } - } - } - } - - // pop() remove the entry from map, detach the entry from head of linked-list, and return it - fn pop(&mut self) -> Option> { - let next; - unsafe { next = (*self.head).next } - // list is empty - if next == self.tail { - return None; - } - let key = unsafe { (*next).key }; - let mut old_entry = self.map.remove(&key).unwrap(); - self.detach(&mut *old_entry); - Some(old_entry) - } - - // push() pushs an entry to the tail of linked-list - fn push(&mut self, entry: *mut LRUEntry) { - unsafe { - // prev <-> tail - // prev <-> entry <-> tail - (*entry).prev = (*self.tail).prev; - (*entry).next = self.tail; - (*self.tail).prev = entry; - (*(*entry).prev).next = entry; - } - } - - // detach() remove an entry from the linked-list - fn detach(&mut self, entry: *mut LRUEntry) { - unsafe { - // prev <-> entry <-> next - // prev <-> next - (*(*entry).prev).next = (*entry).next; - (*(*entry).next).prev = (*entry).prev; - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_146() { - println!("init cache"); - let mut lru_cache = LRUCache::new(2); - lru_cache.put(1, 1); - lru_cache.put(2, 2); - println!("return 1"); - assert_eq!(lru_cache.get(1), 1); // returns 1 - println!("evict key 2"); - lru_cache.put(3, 3); // evicts key 2 - println!("return -1"); - assert_eq!(lru_cache.get(2), -1); // returns -1 (not found) - lru_cache.put(4, 4); // evicts key 1 - assert_eq!(lru_cache.get(1), -1); // returns -1 (not found) - assert_eq!(lru_cache.get(3), 3); // returns 3 - assert_eq!(lru_cache.get(4), 4); // returns 4 - } -} diff --git a/src/solution/s0147_insertion_sort_list.rs b/src/solution/s0147_insertion_sort_list.rs deleted file mode 100644 index 09aff82b..00000000 --- a/src/solution/s0147_insertion_sort_list.rs +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [147] Insertion Sort List - * - * Sort a linked list using insertion sort. - * - *
    - *
- * - *
- * A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
- * With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list

- * - * - *
    - *
- * - * Algorithm of Insertion Sort: - * - *
    - * Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. - * At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. - * It repeats until no input elements remain. - *
- * - *
- * Example 1: - * - * - * Input: 4->2->1->3 - * Output: 1->2->3->4 - * - * - * Example 2: - * - * - * Input: -1->5->3->4->0 - * Output: -1->0->3->4->5 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/insertion-sort-list/ -// discuss: https://leetcode.com/problems/insertion-sort-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO; boring -impl Solution { - pub fn insertion_sort_list(head: Option>) -> Option> { - None - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_147() {} -} diff --git a/src/solution/s0148_sort_list.rs b/src/solution/s0148_sort_list.rs deleted file mode 100644 index 78b7f08c..00000000 --- a/src/solution/s0148_sort_list.rs +++ /dev/null @@ -1,125 +0,0 @@ -/** - * [148] Sort List - * - * Sort a linked list in O(n log n) time using constant space complexity. - * - * Example 1: - * - * - * Input: 4->2->1->3 - * Output: 1->2->3->4 - * - * - * Example 2: - * - * - * Input: -1->5->3->4->0 - * Output: -1->0->3->4->5 - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/sort-list/ -// discuss: https://leetcode.com/problems/sort-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -堆排序需要额外空间, 不行 - -快排: - * 不行, 单链表要快排必须同时持有两个 mut 引用, 而 rust 里这是不可能的(不知道用 unsafe 行不行) - * 不用 rust 的话应该是可行的, Lomuto-partition, 用一个慢指针记录 no_lager_than 位置 - -归并,有点慢, 每次切分要遍历找到切分点, 而且递归栈深度 O(logN) 也不算严格的 O(1) 空间 - -Rust 标准库的 std::collections::LinkedList 都没有实现 sort() 你敢信... - -这题用 rust 解对我而言真的是 Hard 级而不是 Medium 级了... - -这里也是前置知识不足, GG 了解到链表的最佳排序方式确实就是 merge-sort -*/ -impl Solution { - pub fn sort_list(mut head: Option>) -> Option> { - let mut len = 0; - let mut ptr = head.as_ref(); - while let Some(node) = ptr { - len += 1; - ptr = node.next.as_ref(); - } - Solution::merge_sort(head, len) - } - - fn merge_sort(mut head: Option>, len: i32) -> Option> { - if len < 2 { - return head; - } - let mut next = head.as_mut(); - let mut i = 1; - while i < len / 2 { - next = next.unwrap().next.as_mut(); - i += 1; - } - let mut l2 = next.unwrap().next.take(); - let mut l1 = Solution::merge_sort(head, len / 2); - let mut l2 = Solution::merge_sort(l2, len - len / 2); - Solution::merge(l1, l2) - } - - fn merge( - mut l1: Option>, - mut l2: Option>, - ) -> Option> { - let mut dummy = Some(Box::new(ListNode::new(0))); - let mut next = dummy.as_mut(); - loop { - match (l1, l2) { - (Some(mut node1), Some(mut node2)) => { - let node = if node1.val > node2.val { - // give back ownership - l2 = node2.next.take(); - l1 = Some(node1); - node2 - } else { - l1 = node1.next.take(); - l2 = Some(node2); - node1 - }; - next.as_mut().unwrap().next = Some(node); - next = next.unwrap().next.as_mut(); - } - (Some(mut node1), None) => { - next.unwrap().next = Some(node1); - break; - } - (None, Some(mut node2)) => { - next.unwrap().next = Some(node2); - break; - } - (None, None) => break, - } - } - dummy.unwrap().next - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_148() { - assert_eq!( - Solution::sort_list(linked![4, 2, 1, 3]), - linked![1, 2, 3, 4] - ); - assert_eq!( - Solution::sort_list(linked![-1, 5, 3, 4, 0]), - linked![-1, 0, 3, 4, 5] - ); - assert_eq!(Solution::sort_list(linked![]), linked![]); - } -} diff --git a/src/solution/s0149_max_points_on_a_line.rs b/src/solution/s0149_max_points_on_a_line.rs deleted file mode 100644 index 31ea4c62..00000000 --- a/src/solution/s0149_max_points_on_a_line.rs +++ /dev/null @@ -1,178 +0,0 @@ -/** - * [149] Max Points on a Line - * - * Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. - * - * Example 1: - * - * - * Input: [[1,1],[2,2],[3,3]] - * Output: 3 - * Explanation: - * ^ - * | - * | o - * | o - * | o - * +-------------> - * 0 1 2 3 4 - * - * - * Example 2: - * - * - * Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] - * Output: 4 - * Explanation: - * ^ - * | - * | o - * | o o - * | o - * | o o - * +-------------------> - * 0 1 2 3 4 5 6 - * - * - */ -pub struct Solution {} -use crate::util::point::Point; - -// problem: https://leetcode.com/problems/max-points-on-a-line/ -// discuss: https://leetcode.com/problems/max-points-on-a-line/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -要回顾下高中数学:已知两点, 求解一般式: - - * Ax + By + C = 0 - * A = y2 - y1, B = x1 - x2, C = x2y1 - x1y2 - -有这个知识之后,化为一般式,做三层遍历就行,再加上一个 HashSet,避免对同一直线上点的重复计算,时间复杂度可以是 O(N^2) - -有两个坑要注意避免: - - * 给的 case 会导致 i32 溢出,这里直接用了 i64 表示 - * 给的 case 里有相同的点,直接处理相同点的话会导致最坏情况复杂度到 O(N^3),因此要先做一次转化,归并相同的点 - -用 Rust 实现有另一点注意的,给的 Point 没有实现 Hash Trait,要自己转化一下 -*/ -// straight-line expression: Ax + By + C = 0 -// A = y2 - y1, B = x1 - x2, C = x2y1 - x1y2 -#[derive(PartialEq, Hash, Eq, Debug)] -struct Line(i64, i64, i64); - -impl Line { - // Assumes that there is no same point - fn new(p1: &Point, p2: &Point) -> Self { - let x1 = p1.x as i64; - let x2 = p2.x as i64; - let y1 = p1.y as i64; - let y2 = p2.y as i64; - Line(y2 - y1, x1 - x2, x2 * y1 - x1 * y2) - } - fn contains(&self, p: &Point) -> bool { - self.0 * p.x as i64 + self.1 * p.y as i64 + self.2 == 0_i64 - } -} - -use std::collections::HashMap; -use std::collections::HashSet; -impl Solution { - pub fn max_points(points: Vec) -> i32 { - // fold same point, record the point count - let points: Vec<(Point, i32)> = points - .into_iter() - .fold(HashMap::new(), |mut map, v| { - *map.entry((v.x, v.y)).or_insert(0) += 1; - map - }) - .into_iter() - .map(|(k, v)| (Point::new(k.0, k.1), v)) // Point did not implement Hash trait - .collect(); - - // any two points in a straight-line, return quickly - if points.len() < 3 { - return points.into_iter().fold(0, |acc, v| acc + v.1); - } - let mut max = 2; - let mut set: HashSet = HashSet::new(); - for i in 0..(points.len() - 1) { - for j in i + 1..points.len() { - let line = Line::new(&points[i].0, &points[j].0); - if set.contains(&line) { - continue; - } - let mut curr = points[i].1 + points[j].1; - for k in j + 1..points.len() { - if line.contains(&points[k].0) { - curr += points[k].1; - } - } - max = i32::max(max, curr); - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_149() { - assert_eq!( - Solution::max_points(vec![point![1, 1], point![2, 2], point![3, 3]]), - 3 - ); - assert_eq!( - Solution::max_points(vec![ - point![1, 1], - point![3, 2], - point![5, 3], - point![4, 1], - point![2, 3], - point![1, 4] - ]), - 4 - ); - assert_eq!( - Solution::max_points(vec![point![0, 0], point![1, 65536], point![65536, 0]]), - 2 - ); - assert_eq!( - Solution::max_points(vec![point![1, 1], point![1, 1], point![1, 1]]), - 3 - ); - assert_eq!( - Solution::max_points(vec![ - point![0, 9], - point![138, 429], - point![115, 359], - point![115, 359], - point![-30, -102], - point![230, 709], - point![-150, -686], - point![-135, -613], - point![-60, -248], - point![-161, -481], - point![207, 639], - point![23, 79], - point![-230, -691], - point![-115, -341], - point![92, 289], - point![60, 336], - point![-105, -467], - point![135, 701], - point![-90, -394], - point![-184, -551], - point![150, 774] - ]), - 12 - ) - } -} diff --git a/src/solution/s0150_evaluate_reverse_polish_notation.rs b/src/solution/s0150_evaluate_reverse_polish_notation.rs deleted file mode 100644 index 048824dd..00000000 --- a/src/solution/s0150_evaluate_reverse_polish_notation.rs +++ /dev/null @@ -1,91 +0,0 @@ -/** - * [150] Evaluate Reverse Polish Notation - * - * Evaluate the value of an arithmetic expression in Reverse Polish Notation. - * - * Valid operators are +, -, *, /. Each operand may be an integer or another expression. - * - * Note: - * - * - * Division between two integers should truncate toward zero. - * The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation. - * - * - * Example 1: - * - * - * Input: ["2", "1", "+", "3", "*"] - * Output: 9 - * Explanation: ((2 + 1) * 3) = 9 - * - * - * Example 2: - * - * - * Input: ["4", "13", "5", "/", "+"] - * Output: 6 - * Explanation: (4 + (13 / 5)) = 6 - * - * - * Example 3: - * - * - * Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] - * Output: 22 - * Explanation: - * ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 - * = ((10 * (6 / (12 * -11))) + 17) + 5 - * = ((10 * (6 / -132)) + 17) + 5 - * = ((10 * 0) + 17) + 5 - * = (0 + 17) + 5 - * = 17 + 5 - * = 22 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/evaluate-reverse-polish-notation/ -// discuss: https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn eval_rpn(tokens: Vec) -> i32 { - let mut stack: Vec = Vec::new(); - for t in tokens.iter() { - if let Ok(num) = t.parse::() { - stack.push(num); - } else { - let right = stack.pop().unwrap(); - let left = stack.pop().unwrap(); - match (t as &str) { - "*" => stack.push(left * right), - "+" => stack.push(left + right), - "/" => stack.push(left / right), - "-" => stack.push(left - right), - _ => unreachable!(), - } - } - } - stack.pop().unwrap() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_150() { - assert_eq!( - Solution::eval_rpn(vec_string![ - "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" - ]), - 22 - ); - } -} diff --git a/src/solution/s0151_reverse_words_in_a_string.rs b/src/solution/s0151_reverse_words_in_a_string.rs deleted file mode 100644 index 627f0dd6..00000000 --- a/src/solution/s0151_reverse_words_in_a_string.rs +++ /dev/null @@ -1,93 +0,0 @@ -/** - * [151] Reverse Words in a String - * - * Given an input string, reverse the string word by word. - * - * - * - * Example 1: - * - * - * Input: "the sky is blue" - * Output: "blue is sky the" - * - * - * Example 2: - * - * - * Input: " hello world! " - * Output: "world! hello" - * Explanation: Your reversed string should not contain leading or trailing spaces. - * - * - * Example 3: - * - * - * Input: "a good example" - * Output: "example good a" - * Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. - * - * - * - * - * Note: - * - * - * A word is defined as a sequence of non-space characters. - * Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. - * You need to reduce multiple spaces between two words to a single space in the reversed string. - * - * - * - * - * Follow up: - * - * For C programmers, try to solve it in-place in O(1) extra space. - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/reverse-words-in-a-string/ -// discuss: https://leetcode.com/problems/reverse-words-in-a-string/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn reverse_words(mut s: String) -> String { - let mut seq = s.trim().chars().collect::>(); - seq.reverse(); - let mut start_idx = 0_usize; - let mut i = 0_usize; - while i < seq.len() { - if seq[i] == ' ' { - if i == start_idx { - seq.remove(i); - continue; - } - seq[start_idx..i].reverse(); - start_idx = i + 1; - } - i += 1; - } - seq[start_idx..].reverse(); - seq.into_iter().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_151() { - assert_eq!( - Solution::reverse_words("the sky is blue".to_owned()), - "blue is sky the".to_owned() - ); - assert_eq!( - Solution::reverse_words(" hello world! ".to_owned()), - "world! hello".to_owned() - ); - } -} diff --git a/src/solution/s0152_maximum_product_subarray.rs b/src/solution/s0152_maximum_product_subarray.rs deleted file mode 100644 index b85b5ecb..00000000 --- a/src/solution/s0152_maximum_product_subarray.rs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * [152] Maximum Product Subarray - * - * Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. - * - * Example 1: - * - * - * Input: [2,3,-2,4] - * Output: 6 - * Explanation: [2,3] has the largest product 6. - * - * - * Example 2: - * - * - * Input: [-2,0,-1] - * Output: 0 - * Explanation: The result cannot be 2, because [-2,-1] is not a subarray. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/maximum-product-subarray/ -// discuss: https://leetcode.com/problems/maximum-product-subarray/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -f[i], g[i] means the max positive value and max negative value for the sub-seq end with index i - -then we have: - -f[i], g[i] = if nums[i] == 0 { - 0, 0 -} else if nums[i] > 0 { - f[i-1] * nums[i], g[i-1] * nums[i] -} else if nums[i] < 0 { - g[i-1] * nums[i], f[i-1] * nums[i] -} -*/ - -impl Solution { - pub fn max_product(nums: Vec) -> i32 { - let mut max = nums[0]; - let mut neg_max = 0; - let mut pos_max = 0; - for num in nums.into_iter() { - if num == 0 { - neg_max = 0; - pos_max = 0; - max = i32::max(max, 0); - } else if num > 0 { - pos_max = i32::max(pos_max * num, num); - neg_max = neg_max * num; - } else { - let pos_pre = pos_max; - pos_max = neg_max * num; - neg_max = i32::min(pos_pre * num, num); - } - if pos_max != 0 { - max = i32::max(max, pos_max); - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_152() { - assert_eq!(Solution::max_product(vec![2, 3, -2, 4]), 6); - assert_eq!(Solution::max_product(vec![-2, 0, -1]), 0); - assert_eq!(Solution::max_product(vec![-4, -3, -2]), 12); - } -} diff --git a/src/solution/s0153_find_minimum_in_rotated_sorted_array.rs b/src/solution/s0153_find_minimum_in_rotated_sorted_array.rs deleted file mode 100644 index 03b7e7f1..00000000 --- a/src/solution/s0153_find_minimum_in_rotated_sorted_array.rs +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [153] Find Minimum in Rotated Sorted Array - * - * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. - * - * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). - * - * Find the minimum element. - * - * You may assume no duplicate exists in the array. - * - * Example 1: - * - * - * Input: [3,4,5,1,2] - * Output: 1 - * - * - * Example 2: - * - * - * Input: [4,5,6,7,0,1,2] - * Output: 0 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ -// discuss: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn find_min(nums: Vec) -> i32 { - let mut size = nums.len(); - if size == 0 { - return -1; - } - let mut base = 0_usize; - while size > 1 { - let half = size / 2; - let mid = base + half; - if nums[mid] > nums[base] { - base = mid; - } - size -= half; - } - i32::min(nums[base], nums[(base + 1) % nums.len()]) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_153() { - assert_eq!(Solution::find_min(vec![4, 5, 6, 1, 2, 3]), 1); - assert_eq!(Solution::find_min(vec![4, 5, 6, 7, 0, 1, 2]), 0); - } -} diff --git a/src/solution/s0154_find_minimum_in_rotated_sorted_array_ii.rs b/src/solution/s0154_find_minimum_in_rotated_sorted_array_ii.rs deleted file mode 100644 index cdb23ac3..00000000 --- a/src/solution/s0154_find_minimum_in_rotated_sorted_array_ii.rs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * [154] Find Minimum in Rotated Sorted Array II - * - * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. - * - * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). - * - * Find the minimum element. - * - * The array may contain duplicates. - * - * Example 1: - * - * - * Input: [1,3,5] - * Output: 1 - * - * Example 2: - * - * - * Input: [2,2,2,0,1] - * Output: 0 - * - * Note: - * - * - * This is a follow up problem to Find Minimum in Rotated Sorted Array. - * Would allow duplicates affect the run-time complexity? How and why? - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ -// discuss: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -针对无重复的做法, 只要二分搜索找折点即可: 假如 nums[mid] > nums[base] 那么转折点一定在右侧, 否则在左侧 - -但假如有重复, 就可能有 nums[mid] == nums[base], 这时就尴尬了, 无法确定转折点在左半部分还是右半部分 - -可以考虑一个数组, [1,1,1,1,1,1,1,0,1,1,1,1,1,1] 这个数组无论怎么去找 0, 时间复杂度无法低于 O(N) - -但假如不是这种极端情况, 那么二分搜索还是能优化的, 在 153 的基础上, 碰到相等就跳过即可 -*/ -impl Solution { - pub fn find_min(nums: Vec) -> i32 { - let mut lo = 0; - let mut hi = nums.len() - 1; - let mut mid = 0; - while lo < hi { - mid = lo + (hi - lo) / 2; - if (nums[mid] > nums[hi]) { - lo = mid + 1; - } else if (nums[mid] < nums[hi]) { - hi = mid; - } else { - hi -= 1; - } - } - return nums[lo]; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_154() { - assert_eq!(Solution::find_min(vec![1, 2, 2, 2, 2, 2]), 1); - assert_eq!(Solution::find_min(vec![1, 3, 3]), 1); - assert_eq!(Solution::find_min(vec![3, 1, 3, 3]), 1); - } -} diff --git a/src/solution/s0155_min_stack.rs b/src/solution/s0155_min_stack.rs deleted file mode 100644 index 99a96698..00000000 --- a/src/solution/s0155_min_stack.rs +++ /dev/null @@ -1,116 +0,0 @@ -/** - * [155] Min Stack - * - * - * Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. - * - * - * push(x) -- Push element x onto stack. - * - * - * pop() -- Removes the element on top of the stack. - * - * - * top() -- Get the top element. - * - * - * getMin() -- Retrieve the minimum element in the stack. - * - * - * - * - * Example:
- * - * MinStack minStack = new MinStack(); - * minStack.push(-2); - * minStack.push(0); - * minStack.push(-3); - * minStack.getMin(); --> Returns -3. - * minStack.pop(); - * minStack.top(); --> Returns 0. - * minStack.getMin(); --> Returns -2. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/min-stack/ -// discuss: https://leetcode.com/problems/min-stack/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -这题居然是 easy... 我怀疑人生了, getMin() 怎么能做到常数时间? Heap 也是 LogN 啊 - -看了最高票解之后...........天哪, 我可太菜了 - -核心思想是保证每次 pop 时都能以常数时间更新最小值, 这就需要在空间上以某种方式记录下来 - -那一种做法就是存储每个元素和最小值之间的差值, 这样 pop 的时候就能不断还原出原始值 - -另一种更直观的做法就是每次入栈 min 时, 都把前一个 min (当前第二小的数字) 放在它前面, 作为记录 -*/ -struct MinStack { - vec: Vec, - min: i32, -} - -impl MinStack { - /** initialize your data structure here. */ - pub fn new() -> Self { - MinStack { - vec: Vec::new(), - min: i32::max_value(), - } - } - - pub fn push(&mut self, x: i32) { - if x <= self.min { - self.vec.push(self.min); - self.min = x; - } - self.vec.push(x); - } - - pub fn pop(&mut self) { - if self.vec.pop().unwrap() == self.min { - self.min = self.vec.pop().unwrap(); - } - } - - pub fn top(&self) -> i32 { - *self.vec.last().unwrap() - } - - pub fn get_min(&self) -> i32 { - self.min - } -} - -/** - * Your MinStack object will be instantiated and called as such: - * let obj = MinStack::new(); - * obj.push(x); - * obj.pop(); - * let ret_3: i32 = obj.top(); - * let ret_4: i32 = obj.get_min(); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - pub fn test_155() { - let mut min_stack = MinStack::new(); - min_stack.push(-2); - min_stack.push(0); - min_stack.push(-3); - assert_eq!(min_stack.get_min(), -3); // --> Returns -3. - min_stack.pop(); - assert_eq!(min_stack.top(), 0); // --> Returns 0. - assert_eq!(min_stack.get_min(), -2); // --> Returns -2.[] - } -} diff --git a/src/solution/s0162_find_peak_element.rs b/src/solution/s0162_find_peak_element.rs deleted file mode 100644 index 3888b998..00000000 --- a/src/solution/s0162_find_peak_element.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [162] Find Peak Element - * - * A peak element is an element that is greater than its neighbors. - * - * Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. - * - * The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. - * - * You may imagine that nums[-1] = nums[n] = -∞. - * - * Example 1: - * - * - * Input: nums = [1,2,3,1] - * Output: 2 - * Explanation: 3 is a peak element and your function should return the index number 2. - * - * Example 2: - * - * - * Input: nums = [1,2,1,3,5,6,4] - * Output: 1 or 5 - * Explanation: Your function can return either index number 1 where the peak element is 2, - * or index number 5 where the peak element is 6. - * - * - * Note: - * - * Your solution should be in logarithmic complexity. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-peak-element/ -// discuss: https://leetcode.com/problems/find-peak-element/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn find_peak_element(nums: Vec) -> i32 { - let (mut lo, mut hi) = (0_usize, nums.len() - 1); - let mut mid = 0; - while lo < hi { - mid = (hi - lo) / 2 + lo; - if mid + 1 < nums.len() && nums[mid] < nums[mid + 1] { - lo = mid + 1; - } else { - hi = mid; - } - } - lo as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_162() { - assert_eq!(Solution::find_peak_element(vec![1, 2, 3, 1]), 2); - assert_eq!(Solution::find_peak_element(vec![1, 2, 1, 3, 5, 6, 4]), 5); - } -} diff --git a/src/solution/s0164_maximum_gap.rs b/src/solution/s0164_maximum_gap.rs deleted file mode 100644 index bd961db7..00000000 --- a/src/solution/s0164_maximum_gap.rs +++ /dev/null @@ -1,66 +0,0 @@ -/** - * [164] Maximum Gap - * - * Given an unsorted array, find the maximum difference between the successive elements in its sorted form. - * - * Return 0 if the array contains less than 2 elements. - * - * Example 1: - * - * - * Input: [3,6,9,1] - * Output: 3 - * Explanation: The sorted form of the array is [1,3,6,9], either - * (3,6) or (6,9) has the maximum difference 3. - * - * Example 2: - * - * - * Input: [10] - * Output: 0 - * Explanation: The array contains less than 2 elements, therefore return 0. - * - * Note: - * - * - * You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range. - * Try to solve it in linear time/space. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/maximum-gap/ -// discuss: https://leetcode.com/problems/maximum-gap/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -/* -想不出来, 一看解析居然是 Radix Sort 或 Bucket Sort, 我就 ??? 了... - -最佳算法是 Bucket Sort 吗? (桶大小取 max - min / len 那种), 看时间复杂度好像是这样 - -但假如整体排布非常稠密, 那么这个聪明的算法也就退化成了桶大小为 1 的桶排序 -*/ -impl Solution { - pub fn maximum_gap(nums: Vec) -> i32 { - let mut nums = nums; - nums.sort_unstable(); - let mut gap = 0; - for i in 1..nums.len() { - gap = i32::max(nums[i] - nums[i - 1], gap); - } - gap - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_164() { - assert_eq!(Solution::maximum_gap(vec![3, 6, 9, 1]), 3); - } -} diff --git a/src/solution/s0165_compare_version_numbers.rs b/src/solution/s0165_compare_version_numbers.rs deleted file mode 100644 index b53f1bbb..00000000 --- a/src/solution/s0165_compare_version_numbers.rs +++ /dev/null @@ -1,112 +0,0 @@ -/** - * [165] Compare Version Numbers - * - * Compare two version numbers version1 and version2.
- * If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. - * - * You may assume that the version strings are non-empty and contain only digits and the . character. - * The . character does not represent a decimal point and is used to separate number sequences. - * For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. - * You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0. - * - * - * - * Example 1: - * - * Input: version1 = "0.1", version2 = "1.1" - * Output: -1 - * - * Example 2: - * - * Input: version1 = "1.0.1", version2 = "1" - * Output: 1 - * - * Example 3: - * - * Input: version1 = "7.5.2.4", version2 = "7.5.3" - * Output: -1 - * - * Example 4: - * - * Input: version1 = "1.01", version2 = "1.001" - * Output: 0 - * Explanation: Ignoring leading zeroes, both “01” and “001" represent the same number “1” - * - * Example 5: - * - * Input: version1 = "1.0", version2 = "1.0.0" - * Output: 0 - * Explanation: The first version number does not have a third level revision number, which means its third level revision number is default to "0" - * - * - * - * Note: - *
    - * Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes. - * Version strings do not start or end with dots, and they will not be two consecutive dots. - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/compare-version-numbers/ -// discuss: https://leetcode.com/problems/compare-version-numbers/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn compare_version(version1: String, version2: String) -> i32 { - let v1: Vec<&str> = version1.split('.').collect::>(); - let v2: Vec<&str> = version2.split('.').collect::>(); - let mut i = 0_usize; - while i < v1.len() && i < v2.len() { - let left = v1[i].parse::().unwrap(); - let right = v2[i].parse::().unwrap(); - if left > right { - return 1; - } else if left < right { - return -1; - } - i += 1; - } - while i < v1.len() { - if v1[i].parse::().unwrap() > 0 { - return 1; - } - i += 1; - } - while i < v2.len() { - if v2[i].parse::().unwrap() > 0 { - return -1; - } - i += 1; - } - return 0; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_165() { - assert_eq!( - Solution::compare_version("0.1".to_owned(), "1.1".to_owned()), - -1 - ); - assert_eq!( - Solution::compare_version("1.0.1".to_owned(), "1".to_owned()), - 1 - ); - assert_eq!( - Solution::compare_version("7.5.2.4".to_owned(), "7.5.3".to_owned()), - -1 - ); - assert_eq!( - Solution::compare_version("1.01".to_owned(), "1.0001".to_owned()), - 0 - ); - } -} diff --git a/src/solution/s0167_two_sum_ii_input_array_is_sorted.rs b/src/solution/s0167_two_sum_ii_input_array_is_sorted.rs deleted file mode 100644 index 58de2e86..00000000 --- a/src/solution/s0167_two_sum_ii_input_array_is_sorted.rs +++ /dev/null @@ -1,58 +0,0 @@ -/** - * [167] Two Sum II - Input array is sorted - * - * Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. - * - * The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. - * - * Note: - * - * - * Your returned answers (both index1 and index2) are not zero-based. - * You may assume that each input would have exactly one solution and you may not use the same element twice. - * - * - * Example: - * - * - * Input: numbers = [2,7,11,15], target = 9 - * Output: [1,2] - * Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ -// discuss: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn two_sum(numbers: Vec, target: i32) -> Vec { - let mut i = 0_usize; - let mut j = numbers.len() - 1; - while i < j { - let sum = numbers[i] + numbers[j]; - if sum > target { - j -= 1; - } else if sum < target { - i += 1; - } else { - break; - } - } - return vec![i as i32 + 1, j as i32 + 1]; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_167() { - assert_eq!(Solution::two_sum(vec![2, 7, 11, 15], 9), vec![1, 2]); - } -} diff --git a/src/solution/s0168_excel_sheet_column_title.rs b/src/solution/s0168_excel_sheet_column_title.rs deleted file mode 100644 index 5a9dc585..00000000 --- a/src/solution/s0168_excel_sheet_column_title.rs +++ /dev/null @@ -1,78 +0,0 @@ -/** - * [168] Excel Sheet Column Title - * - * Given a positive integer, return its corresponding column title as appear in an Excel sheet. - * - * For example: - * - * - * 1 -> A - * 2 -> B - * 3 -> C - * ... - * 26 -> Z - * 27 -> AA - * 28 -> AB - * ... - * - * - * Example 1: - * - * - * Input: 1 - * Output: "A" - * - * - * Example 2: - * - * - * Input: 28 - * Output: "AB" - * - * - * Example 3: - * - * - * Input: 701 - * Output: "ZY" - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/excel-sheet-column-title/ -// discuss: https://leetcode.com/problems/excel-sheet-column-title/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn convert_to_title(n: i32) -> String { - let base = 26; - let mut n = n; - let mut res = Vec::new(); - while n > 0 { - let mut code = (n % base) as u8; - n = n / base; - if code == 0 { - n -= 1; - code = base as u8; - }; - let alphabetic = (('A' as u8) + (code - 1_u8)) as char; - res.push(alphabetic); - } - res.reverse(); - res.into_iter().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_168() { - assert_eq!(Solution::convert_to_title(28), "AB".to_owned()); - assert_eq!(Solution::convert_to_title(1), "A".to_owned()); - } -} diff --git a/src/solution/s0169_majority_element.rs b/src/solution/s0169_majority_element.rs deleted file mode 100644 index be59bea6..00000000 --- a/src/solution/s0169_majority_element.rs +++ /dev/null @@ -1,73 +0,0 @@ -/** - * [169] Majority Element - * - * Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. - * - * You may assume that the array is non-empty and the majority element always exist in the array. - * - * Example 1: - * - * - * Input: [3,2,3] - * Output: 3 - * - * Example 2: - * - * - * Input: [2,2,1,1,1,2,2] - * Output: 2 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/majority-element/ -// discuss: https://leetcode.com/problems/majority-element/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -抄的题解:Boyer-Moore Voting Algorithm -自己只能想到 HashMap 和排序, 真是太鸡儿菜了... - -Boyer-Moore Voting Algorithm 的思路是假设当前值为主元素, 碰到当前值则 +1, 非当前值则 -1, 计数器一旦归零, -就取下一个数为主元素 - -最后留下的数一定主元素 - -证明也很简单, 假设我们从第 i 位开始选择了一个数 A, 并且这个数 A 保持到了循环终止, 那么: - -我们知道, 第 nums[i..n] 中, A 是主元素, nums[0..i] 中, 有一个数 B 出现了一半的次数 - -假如 A = B, 那么 A 出现了大于一半的次数, A 一定是主元素 - -假如 A != B, 且主元素不是 A, 那么 B 包括其他任何数在整个数组中出现的次数一定不到一半(因为 B 包括其他任何数 -在前半部分**至多**出现一半, 而在后半部分不到一半), 因此不存在主元素, 这与题目给定的"一定存在主元素"矛盾, 因此 -A 一定是主元素 -*/ - -impl Solution { - pub fn majority_element(nums: Vec) -> i32 { - let mut count = 0; - let mut candidate = 0; - for &num in nums.iter() { - if count == 0 { - candidate = num; - } - count += if num == candidate { 1 } else { -1 }; - } - candidate - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_169() { - assert_eq!(Solution::majority_element(vec![2, 2, 1, 1, 1, 2, 2]), 2); - } -} diff --git a/src/solution/s0171_excel_sheet_column_number.rs b/src/solution/s0171_excel_sheet_column_number.rs deleted file mode 100644 index 1b2f611f..00000000 --- a/src/solution/s0171_excel_sheet_column_number.rs +++ /dev/null @@ -1,62 +0,0 @@ -/** - * [171] Excel Sheet Column Number - * - * Given a column title as appear in an Excel sheet, return its corresponding column number. - * - * For example: - * - * - * A -> 1 - * B -> 2 - * C -> 3 - * ... - * Z -> 26 - * AA -> 27 - * AB -> 28 - * ... - * - * - * Example 1: - * - * - * Input: "A" - * Output: 1 - * - * - * Example 2: - * - * - * Input: "AB" - * Output: 28 - * - * - * Example 3: - * - * - * Input: "ZY" - * Output: 701 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/excel-sheet-column-number/ -// discuss: https://leetcode.com/problems/excel-sheet-column-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: boring -impl Solution { - pub fn title_to_number(s: String) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_171() {} -} diff --git a/src/solution/s0172_factorial_trailing_zeroes.rs b/src/solution/s0172_factorial_trailing_zeroes.rs deleted file mode 100644 index 9a54916d..00000000 --- a/src/solution/s0172_factorial_trailing_zeroes.rs +++ /dev/null @@ -1,55 +0,0 @@ -/** - * [172] Factorial Trailing Zeroes - * - * Given an integer n, return the number of trailing zeroes in n!. - * - * Example 1: - * - * - * Input: 3 - * Output: 0 - * Explanation: 3! = 6, no trailing zero. - * - * Example 2: - * - * - * Input: 5 - * Output: 1 - * Explanation: 5! = 120, one trailing zero. - * - * Note: Your solution should be in logarithmic time complexity. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/factorial-trailing-zeroes/ -// discuss: https://leetcode.com/problems/factorial-trailing-zeroes/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn trailing_zeroes(n: i32) -> i32 { - let mut five_count = 0; - let mut n = n; - while n > 0 { - n = n / 5; - five_count += n; - } - five_count - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_172() { - assert_eq!(Solution::trailing_zeroes(3), 0); - assert_eq!(Solution::trailing_zeroes(5), 1); - assert_eq!(Solution::trailing_zeroes(20), 4); - assert_eq!(Solution::trailing_zeroes(1808548329), 452137076); - } -} diff --git a/src/solution/s0173_binary_search_tree_iterator.rs b/src/solution/s0173_binary_search_tree_iterator.rs deleted file mode 100644 index b350600d..00000000 --- a/src/solution/s0173_binary_search_tree_iterator.rs +++ /dev/null @@ -1,116 +0,0 @@ -/** - * [173] Binary Search Tree Iterator - * - * Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. - * - * Calling next() will return the next smallest number in the BST. - * - * - * - * - * - * - * Example: - * - * - * - * - * BSTIterator iterator = new BSTIterator(root); - * iterator.next(); // return 3 - * iterator.next(); // return 7 - * iterator.hasNext(); // return true - * iterator.next(); // return 9 - * iterator.hasNext(); // return true - * iterator.next(); // return 15 - * iterator.hasNext(); // return true - * iterator.next(); // return 20 - * iterator.hasNext(); // return false - * - * - * - * - * Note: - * - * - * next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. - * You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called. - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; -use std::cell::RefCell; -use std::rc::Rc; - -// problem: https://leetcode.com/problems/binary-search-tree-iterator/ -// discuss: https://leetcode.com/problems/binary-search-tree-iterator/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -非递归中序遍历 -*/ -pub struct BSTIterator { - stack: Vec>>, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl BSTIterator { - pub fn new(root: Option>>) -> Self { - let mut node = root; - let mut stack = Vec::new(); - while let Some(inner) = node.clone() { - stack.push(inner.clone()); - node = node.unwrap().borrow().left.clone(); - } - BSTIterator { stack: stack } - } - - /** @return the next smallest number */ - pub fn next(&mut self) -> i32 { - let node = self.stack.pop().unwrap(); - let res = node.borrow().val; - let mut next = node.borrow().right.clone(); - while let Some(inner) = next.clone() { - self.stack.push(inner.clone()); - next = next.unwrap().borrow().left.clone(); - } - res - } - - /** @return whether we have a next smallest number */ - pub fn has_next(&self) -> bool { - !self.stack.is_empty() - } -} - -/** - * Your BSTIterator object will be instantiated and called as such: - * let obj = BSTIterator::new(root); - * let ret_1: i32 = obj.next(); - * let ret_2: bool = obj.has_next(); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_173() { - let mut iterator = BSTIterator::new(tree![7, 3, 15, null, null, 9, 20]); - assert_eq!(iterator.next(), 3); // return 3 - assert_eq!(iterator.next(), 7); // return 7 - assert_eq!(iterator.has_next(), true); // return true - assert_eq!(iterator.next(), 9); // return 9 - assert_eq!(iterator.has_next(), true); // return true - assert_eq!(iterator.next(), 15); // return 15 - assert_eq!(iterator.has_next(), true); // return true - assert_eq!(iterator.next(), 20); // return 20 - assert_eq!(iterator.has_next(), false); // return false - } -} diff --git a/src/solution/s0174_dungeon_game.rs b/src/solution/s0174_dungeon_game.rs deleted file mode 100644 index 23be4d97..00000000 --- a/src/solution/s0174_dungeon_game.rs +++ /dev/null @@ -1,115 +0,0 @@ -/** - * [174] Dungeon Game - * - * - * The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess. - * - * The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. - * - * Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers). - * - * In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. - * - * - * - * Write a function to determine the knight's minimum initial health so that he is able to rescue the princess. - * - * For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
-2 (K)-33
-5-101
1030-5 (P)
- * - * - * - * Note: - * - * - * The knight's health has no upper bound. - * Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/dungeon-game/ -// discuss: https://leetcode.com/problems/dungeon-game/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -DP, 即从每个格子出发到达终点所需的最小生命值为 hp[i][j] - -则显然, hp[M-1][N-1] = min(dungeon[M-1][N-1], 0) + 1; - -hp[i][j] = min(min(hp[i+1][j], hp[i][j+1]) - dungeon[i][j], 1); - -倒推到 hp[0][0] 即可 - -这里倒推很重要, 因为正推很难 dp(有后效性) - -其实可以优化成 O(M+N) 空间复杂度, 从斜对角线往后推就只需要保存一个小数组, 但是下面这样更简明 -*/ -impl Solution { - pub fn calculate_minimum_hp(dungeon: Vec>) -> i32 { - let (height, width) = (dungeon.len(), dungeon[0].len()); - // Using dummy row to simplify logic - let mut hp = vec![vec![i32::max_value(); width + 1]; height + 1]; - hp[height][width - 1] = 1; - hp[height - 1][width] = 1; - for i in (0..height).rev() { - for j in (0..width).rev() { - hp[i][j] = i32::max(i32::min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j], 1); - } - } - hp[0][0] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_174() { - assert_eq!( - Solution::calculate_minimum_hp(vec![ - vec![-2, -3, 3], - vec![-5, -10, 1], - vec![10, 30, -5], - ]), - 7 - ); - assert_eq!( - Solution::calculate_minimum_hp(vec![vec![1, -4, 5, -99], vec![2, -2, -2, -1]]), - 3 - ); - } -} diff --git a/src/solution/s0179_largest_number.rs b/src/solution/s0179_largest_number.rs deleted file mode 100644 index 65348165..00000000 --- a/src/solution/s0179_largest_number.rs +++ /dev/null @@ -1,60 +0,0 @@ -/** - * [179] Largest Number - * - * Given a list of non negative integers, arrange them such that they form the largest number. - * - * Example 1: - * - * - * Input: [10,2] - * Output: "210" - * - * Example 2: - * - * - * Input: [3,30,34,5,9] - * Output: "9534330" - * - * - * Note: The result may be very large, so you need to return a string instead of an integer. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/largest-number/ -// discuss: https://leetcode.com/problems/largest-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn largest_number(nums: Vec) -> String { - let mut nums = nums - .into_iter() - .map(|num| num.to_string()) - .collect::>(); - nums.sort_unstable_by(|a, b| format!("{}{}", b, a).cmp(&format!("{}{}", a, b))); - if nums[0] == "0" { - return "0".to_owned(); - } - nums.iter().fold(String::new(), |mut s, num| { - s.push_str(num); - s - }) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_179() { - assert_eq!( - Solution::largest_number(vec![3, 30, 34, 5, 9]), - "9534330".to_owned() - ); - assert_eq!(Solution::largest_number(vec![121, 12]), "12121".to_owned()); - } -} diff --git a/src/solution/s0187_repeated_dna_sequences.rs b/src/solution/s0187_repeated_dna_sequences.rs deleted file mode 100644 index 9ceb86cb..00000000 --- a/src/solution/s0187_repeated_dna_sequences.rs +++ /dev/null @@ -1,100 +0,0 @@ -/** - * [187] Repeated DNA Sequences - * - * All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. - * - * Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. - * - * Example: - * - * - * Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" - * - * Output: ["AAAAACCCCC", "CCCCCAAAAA"] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/repeated-dna-sequences/ -// discuss: https://leetcode.com/problems/repeated-dna-sequences/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -首先想到直接长度为 10 的 sliding window 滑过去加一个 HashSet - -但这种方法在空间上和每次操作的耗时上都比较差, 可以转化为四进制或者二进制编码来考虑 - -A,C,G,T <-> [00, 01, 10, 11] - -那就简单很多了, 往后滑动一格不再需要调整整个 substring, 只需要移位, HashSet 也就存个 u32 即可 -*/ -use std::collections::HashSet; -impl Solution { - pub fn find_repeated_dna_sequences(s: String) -> Vec { - let mut seq_code: u32 = 0; - let mut set: HashSet = HashSet::new(); - let mut repeat: HashSet = HashSet::new(); - let mut count = 0; - for ch in s.chars() { - seq_code <<= 2; - match ch { - 'A' => seq_code |= 0_u32, - 'C' => seq_code |= 1_u32, - 'G' => seq_code |= 2_u32, - 'T' => seq_code |= 3_u32, - _ => unreachable!(), - } - // skip first 9 chars - if count < 9 { - count += 1; - continue; - } - // mask high 12-bits - seq_code &= 0b0000_0000_0000_1111_1111_1111_1111_1111; - if !set.insert(seq_code) { - repeat.insert(seq_code); - } - } - // bits code to seq string - repeat - .iter() - .map(|&code| { - let mut substr = String::new(); - let mut code = code; - for _ in 0..10 { - // take the first 2 bits each time - substr.push(match code & 0b0000_0000_0000_1100_0000_0000_0000_0000 { - 0b0000_0000_0000_0000_0000_0000_0000_0000 => 'A', - 0b0000_0000_0000_0100_0000_0000_0000_0000 => 'C', - 0b0000_0000_0000_1000_0000_0000_0000_0000 => 'G', - 0b0000_0000_0000_1100_0000_0000_0000_0000 => 'T', - _ => unreachable!(), - }); - code <<= 2; - } - substr - }) - .collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_187() { - assert_eq!( - Solution::find_repeated_dna_sequences("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT".to_owned()), - vec_string!["AAAAACCCCC", "CCCCCAAAAA"] - ); - assert_eq!( - Solution::find_repeated_dna_sequences("GAGAGAGAGAGA".to_owned()), - vec_string!["GAGAGAGAGA"] - ); - } -} diff --git a/src/solution/s0188_best_time_to_buy_and_sell_stock_iv.rs b/src/solution/s0188_best_time_to_buy_and_sell_stock_iv.rs deleted file mode 100644 index e9c23319..00000000 --- a/src/solution/s0188_best_time_to_buy_and_sell_stock_iv.rs +++ /dev/null @@ -1,103 +0,0 @@ -/** - * [188] Best Time to Buy and Sell Stock IV - * - * Say you have an array for which the i^th element is the price of a given stock on day i. - * - * Design an algorithm to find the maximum profit. You may complete at most k transactions. - * - * Note:
- * You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). - * - * Example 1: - * - * - * Input: [2,4,1], k = 2 - * Output: 2 - * Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. - * - * - * Example 2: - * - * - * Input: [3,2,6,5,0,3], k = 2 - * Output: 7 - * Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. - * Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ -// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -已经在 #123 里解过了, 为了方便阅读直接把那题的分析拷贝到这里 - -先考虑只进行 1 次交易的情况, 我们求以 i *为售出点*, 只进行 1 次交易获得的最大利润, 那么: - -f[i] = if f[i-1] > 0 { f[i-1] } else { 0 } + prices[i] - prices[i-1] - -这很容易解, 解完之后找出 f 里的最大值即可, 但这不容易推广到 K 次交易的情况, 因为这时 f[i] 不代表到 i *为止*的最大利润, 无法作为单独的交易帮助递推 -(到 i 为止的含义是售出点可以在 [0,i] 之间) - -我们可以稍作改进, 变成求以 i 为结束点, 只进行 1 次交易获得的最大利润, 那么: - -f[i] = max( - f[i-1], - prices[i] - min(prices[j] { j in [0, i-1] }) -) - -这仍然是一个 O(N) 的解法, 因为 min(prices[j] { j in [0, i-1] }) 不需要遍历, 可以在递推过程中直接维护好 - -现在再推广到进行 K 次交易的情况, 那我们要求以 i 为结束点, 进行 k 次交易获得的最大利润, 这时有了变化, 我们可以在 j 之前再进行 K - 1 次交易: - -f[k, i] = max( - f[k, i-1], - prices[i] + max(f[k-1, j] - prices[j]) { j in [0, i-1] } ) -) - -显然, f[0, i] = 0, f[k, 0] = 0 - -这个算法可以形象地描述一下, 在 k = 1 时, 我们每次要找的就是 i 之前的最低谷点作为这次交易的开始点 j, 而当 k > 1 时, -我们 i 之前就有可能已经进行过交易了, 这时我们在找开始点 j 时, 就要同时考虑 "直到 j 为止, k-1 次交易的最大收益" - "j 本身的值". 以此来找到一个最佳点 j - -在实现时, 假如用 Bottom-Up 递推, 那么只需要维护一个 vec[i], 因为每轮递推时只会考虑上一轮的数据, 我们可以复用这个 O(N) 的额外存储空间 - -最后, 这题会给 k 非常大的 corner case, 实际上 k 大于 prices.len() / 2 后面就没有意义了, 可以 shortcut 掉(== 允许无穷次交易的场景), 下面写的比较糙, -直接限制了一下循环次数, 实际跑的时候运行时间会长一点 -*/ -impl Solution { - pub fn max_profit(k: i32, prices: Vec) -> i32 { - if prices.is_empty() { - return 0; - } - let max_trans = k as usize; - let mut cache = vec![0; prices.len()]; - for _ in 0..usize::min(max_trans, prices.len() / 2 + 1) { - // best_by_in 维护了考虑前 N 次交易的最佳的买入点, 即 max(f[k-1, j] - prices[j]) { j in [0, i-1] } - let mut best_buy_in = cache[0] - prices[0]; - for i in 1..prices.len() { - // 复用 vec 前暂存一下前一次的计算结果 - let temp = cache[i]; - cache[i] = i32::max(cache[i - 1], best_buy_in + prices[i]); - // 更新 best_buy_in - best_buy_in = i32::max(best_buy_in, temp - prices[i]); - } - } - return *cache.last().unwrap(); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_188() { - assert_eq!(Solution::max_profit(2, vec![3, 2, 6, 5, 0, 3]), 7); - } -} diff --git a/src/solution/s0189_rotate_array.rs b/src/solution/s0189_rotate_array.rs deleted file mode 100644 index 1a4d2ab8..00000000 --- a/src/solution/s0189_rotate_array.rs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * [189] Rotate Array - * - * Given an array, rotate the array to the right by k steps, where k is non-negative. - * - * Example 1: - * - * - * Input: [1,2,3,4,5,6,7] and k = 3 - * Output: [5,6,7,1,2,3,4] - * Explanation: - * rotate 1 steps to the right: [7,1,2,3,4,5,6] - * rotate 2 steps to the right: [6,7,1,2,3,4,5] - * rotate 3 steps to the right: [5,6,7,1,2,3,4] - * - * - * Example 2: - * - * - * Input: [-1,-100,3,99] and k = 2 - * Output: [3,99,-1,-100] - * Explanation: - * rotate 1 steps to the right: [99,-1,-100,3] - * rotate 2 steps to the right: [3,99,-1,-100] - * - * - * Note: - * - * - * Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. - * Could you do it in-place with O(1) extra space? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/rotate-array/ -// discuss: https://leetcode.com/problems/rotate-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn rotate(nums: &mut Vec, k: i32) { - let offset = (k as usize) % nums.len(); - if offset == 0 { - return; - } - let mut idx = 0; - let mut num = nums[0]; - let mut start_idx = 0; - for _ in 0..nums.len() { - idx = (idx + offset) % nums.len(); - let temp = num; - num = nums[idx]; - nums[idx] = temp; - if idx == start_idx { - idx += 1; - start_idx = idx; - num = nums[idx]; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_189() { - let mut nums = vec![1, 2, 3, 4, 5, 6, 7]; - Solution::rotate(&mut nums, 3); - assert_eq!(nums, vec![5, 6, 7, 1, 2, 3, 4]); - let mut nums = vec![1, 2, 3, 4, 5, 6]; - Solution::rotate(&mut nums, 2); - assert_eq!(nums, vec![5, 6, 1, 2, 3, 4]); - } -} diff --git a/src/solution/s0198_house_robber.rs b/src/solution/s0198_house_robber.rs deleted file mode 100644 index 446e63f1..00000000 --- a/src/solution/s0198_house_robber.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [198] House Robber - * - * You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. - * - * Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. - * - * Example 1: - * - * - * Input: [1,2,3,1] - * Output: 4 - * Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). - * Total amount you can rob = 1 + 3 = 4. - * - * Example 2: - * - * - * Input: [2,7,9,3,1] - * Output: 12 - * Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). - * Total amount you can rob = 2 + 9 + 1 = 12. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/house-robber/ -// discuss: https://leetcode.com/problems/house-robber/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -动态规划, 记抢到第 i 户为止的最大收益为 F[i], 则: - -i 有两种情况, 抢或不抢, 抢的话则最大收益是 F[i-2] + nums[i], -不抢则保持和前一次结束的收益一致, 等于 F[i-1], 于是: - -F[i] = i32::max(nums[i] + F[i-2], F[i-1]) - -观察到 F[i] 只依赖 F[i-1] 和 F[i-2], 可以用常数空间复杂度完成 -*/ -impl Solution { - pub fn rob(nums: Vec) -> i32 { - let mut former_max = 0; - let mut curr_max = 0; - for &num in nums.iter() { - let mut temp = curr_max; - curr_max = i32::max(former_max + num, curr_max); - former_max = temp; - } - curr_max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_198() { - assert_eq!(Solution::rob(vec![2, 7, 9, 3, 1]), 12); - assert_eq!(Solution::rob(vec![2, 7, 9, 10, 1]), 17); - assert_eq!(Solution::rob(vec![2, 1, 1, 2]), 4); - } -} diff --git a/src/solution/s0199_binary_tree_right_side_view.rs b/src/solution/s0199_binary_tree_right_side_view.rs deleted file mode 100644 index e07dc998..00000000 --- a/src/solution/s0199_binary_tree_right_side_view.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [199] Binary Tree Right Side View - * - * Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. - * - * Example: - * - * - * Input: [1,2,3,null,5,null,4] - * Output: [1, 3, 4] - * Explanation: - * - * 1 <--- - * / \ - * 2 3 <--- - * \ \ - * 5 4 <--- - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-right-side-view/ -// discuss: https://leetcode.com/problems/binary-tree-right-side-view/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn right_side_view(root: Option>>) -> Vec { - let mut res = Vec::new(); - let mut current_level = 0; - if root.is_none() { - return res; - } - let mut deq = VecDeque::new(); - deq.push_back((0, root.clone())); - res.push(root.as_ref().unwrap().borrow().val); - while !deq.is_empty() { - if let Some((level, Some(node))) = deq.pop_front() { - deq.push_back((level + 1, node.borrow().right.clone())); - deq.push_back((level + 1, node.borrow().left.clone())); - if level > current_level { - res.push(node.borrow().val); - current_level = level; - } - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_199() { - assert_eq!( - Solution::right_side_view(tree![1, 2, 3, null, 5, null, 4]), - vec![1, 3, 4] - ); - } -} diff --git a/src/solution/s0200_number_of_islands.rs b/src/solution/s0200_number_of_islands.rs deleted file mode 100644 index 262f0315..00000000 --- a/src/solution/s0200_number_of_islands.rs +++ /dev/null @@ -1,122 +0,0 @@ -/** - * [200] Number of Islands - * - * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. - * - * Example 1: - * - * - * Input: - * 11110 - * 11010 - * 11000 - * 00000 - * - * Output: 1 - * - * - * Example 2: - * - * - * Input: - * 11000 - * 11000 - * 00100 - * 00011 - * - * Output: 3 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/number-of-islands/ -// discuss: https://leetcode.com/problems/number-of-islands/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Union-Find Set -impl Solution { - pub fn num_islands(grid: Vec>) -> i32 { - if grid.is_empty() || grid[0].is_empty() { - return 0; - } - let (height, width) = (grid.len(), grid[0].len()); - let mut parent = vec![vec![(width, height); width]; height]; - for i in 0..height { - for j in 0..width { - if grid[i][j] != '1' { - continue; - } - parent[i][j] = (i, j); - if i > 0 && grid[i - 1][j] == '1' { - Solution::union(&mut parent, (i, j), (i - 1, j)); - } - if j > 0 && grid[i][j - 1] == '1' { - Solution::union(&mut parent, (i, j), (i, j - 1)); - } - } - } - let mut cnt = 0; - for i in 0..height { - for j in 0..width { - if parent[i][j] == (i, j) { - cnt += 1; - } - } - } - cnt - } - - fn get_parent(parent: &mut Vec>, p: (usize, usize)) -> (usize, usize) { - let mut child = p; - let mut p = p; - while parent[p.0][p.1] != p { - p = parent[p.0][p.1]; - } - // path compression, adjust all the node's parent to root along the path - while child != p { - let temp = parent[child.0][child.1]; - parent[child.0][child.1] = p; - child = temp; - } - p - } - - fn union(parent: &mut Vec>, p1: (usize, usize), p2: (usize, usize)) { - let p1 = Solution::get_parent(parent, p1); - let p2 = Solution::get_parent(parent, p2); - if p1 == p2 { - return; - } - parent[p1.0][p1.1] = p2 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_200() { - assert_eq!( - Solution::num_islands(vec![ - vec!['1', '1', '1', '1', '0',], - vec!['1', '1', '0', '1', '0',], - vec!['1', '1', '0', '0', '0',], - vec!['0', '0', '0', '0', '0',], - ]), - 1 - ); - assert_eq!( - Solution::num_islands(vec![ - vec!['1', '1', 'o', '1', '0',], - vec!['1', '1', '0', '1', '0',], - vec!['1', '1', '0', '0', '0',], - vec!['0', '0', '0', '1', '1',], - ]), - 3 - ); - } -} diff --git a/src/solution/s0201_bitwise_and_of_numbers_range.rs b/src/solution/s0201_bitwise_and_of_numbers_range.rs deleted file mode 100644 index 6c46e74f..00000000 --- a/src/solution/s0201_bitwise_and_of_numbers_range.rs +++ /dev/null @@ -1,58 +0,0 @@ -/** - * [201] Bitwise AND of Numbers Range - * - * Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. - * - * Example 1: - * - * - * Input: [5,7] - * Output: 4 - * - * - * Example 2: - * - * - * Input: [0,1] - * Output: 0 - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/bitwise-and-of-numbers-range/ -// discuss: https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// just find the highest bit 1 of m and n -impl Solution { - pub fn range_bitwise_and(m: i32, n: i32) -> i32 { - let mut m = m; - let mut n = n; - if m == 0 { - return 0; - } - let mut step = 1; - while m != n { - // shortcut - if m == 0 { - return 0; - } - m >>= 1; - n >>= 1; - step <<= 1; - } - return m * step; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_201() { - assert_eq!(Solution::range_bitwise_and(5, 7), 4); - } -} diff --git a/src/solution/s0202_happy_number.rs b/src/solution/s0202_happy_number.rs deleted file mode 100644 index 076f2736..00000000 --- a/src/solution/s0202_happy_number.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [202] Happy Number - * - * Write an algorithm to determine if a number is "happy". - * - * A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. - * - * Example: - * - * - * Input: 19 - * Output: true - * Explanation: - * 1^2 + 9^2 = 82 - * 8^2 + 2^2 = 68 - * 6^2 + 8^2 = 100 - * 1^2 + 0^2 + 0^2 = 1 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/happy-number/ -// discuss: https://leetcode.com/problems/happy-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashSet; -impl Solution { - pub fn is_happy(n: i32) -> bool { - let mut set = HashSet::new(); - let mut n = n; - loop { - set.insert(n); - let temp = Solution::next(n); - if temp == 1 { - return true; - } - if !set.insert(temp) { - return false; - } - n = temp - } - return false; - } - - fn next(n: i32) -> i32 { - let mut res = 0; - let mut n = n; - while n != 0 { - res += (n % 10).pow(2); - n = n / 10; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_202() { - assert_eq!(Solution::is_happy(19), true); - assert_eq!(Solution::is_happy(235123), false); - } -} diff --git a/src/solution/s0203_remove_linked_list_elements.rs b/src/solution/s0203_remove_linked_list_elements.rs deleted file mode 100644 index 3e48d811..00000000 --- a/src/solution/s0203_remove_linked_list_elements.rs +++ /dev/null @@ -1,50 +0,0 @@ -/** - * [203] Remove Linked List Elements - * - * Remove all elements from a linked list of integers that have value val. - * - * Example: - * - * - * Input: 1->2->6->3->4->5->6, val = 6 - * Output: 1->2->3->4->5 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/remove-linked-list-elements/ -// discuss: https://leetcode.com/problems/remove-linked-list-elements/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn remove_elements(mut head: Option>, val: i32) -> Option> { - let mut dummy = Some(Box::new(ListNode::new(0))); - let mut next = dummy.as_mut(); - while let Some(mut inner) = head { - head = inner.next.take(); - if inner.val != val { - next.as_mut().unwrap().next = Some(inner); - next = next.unwrap().next.as_mut(); - } - } - dummy.unwrap().next - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_203() { - assert_eq!( - Solution::remove_elements(linked![1, 2, 6, 3, 4, 5, 6], 6), - linked![1, 2, 3, 4, 5] - ); - } -} diff --git a/src/solution/s0204_count_primes.rs b/src/solution/s0204_count_primes.rs deleted file mode 100644 index d6f0f134..00000000 --- a/src/solution/s0204_count_primes.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [204] Count Primes - * - * Count the number of prime numbers less than a non-negative number, n. - * - * Example: - * - * - * Input: 10 - * Output: 4 - * Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/count-primes/ -// discuss: https://leetcode.com/problems/count-primes/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn count_primes(n: i32) -> i32 { - if n <= 2 { - return 0; - } - let mut is_prime = vec![true; n as usize]; - is_prime[0] = false; - is_prime[1] = false; - let mut i = 2; - while i * i < n { - if !is_prime[i as usize] { - i += 1; - continue; - } - let mut j = i * i; - while j < n { - is_prime[j as usize] = false; - j += i; - } - i += 1; - } - let mut count = 0; - for &v in is_prime.iter() { - if v { - count += 1 - } - } - count - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_204() { - assert_eq!(Solution::count_primes(10), 4); - assert_eq!(Solution::count_primes(2), 0); - assert_eq!(Solution::count_primes(3), 1); - assert_eq!(Solution::count_primes(5), 2); - assert_eq!(Solution::count_primes(1), 0); - assert_eq!(Solution::count_primes(120), 30); - } -} diff --git a/src/solution/s0205_isomorphic_strings.rs b/src/solution/s0205_isomorphic_strings.rs deleted file mode 100644 index df697ebb..00000000 --- a/src/solution/s0205_isomorphic_strings.rs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * [205] Isomorphic Strings - * - * Given two strings s and t, determine if they are isomorphic. - * - * Two strings are isomorphic if the characters in s can be replaced to get t. - * - * All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. - * - * Example 1: - * - * - * Input: s = "egg", t = "add" - * Output: true - * - * - * Example 2: - * - * - * Input: s = "foo", t = "bar" - * Output: false - * - * Example 3: - * - * - * Input: s = "paper", t = "title" - * Output: true - * - * Note:
- * You may assume both s and t have the same length. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/isomorphic-strings/ -// discuss: https://leetcode.com/problems/isomorphic-strings/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::char; -use std::collections::hash_map::Entry; -use std::collections::HashMap; -impl Solution { - pub fn is_isomorphic(s: String, t: String) -> bool { - Solution::code(s) == Solution::code(t) - } - - fn code(s: String) -> String { - let mut map = HashMap::new(); - let mut start: char = '0'; - let mut res = String::new(); - for ch in s.chars() { - let v = map.entry(ch).or_insert_with(|| { - start = ((start as u8) + 1) as char; - start - }); - res.push(*v) - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_205() { - assert_eq!( - Solution::is_isomorphic("egg".to_owned(), "app".to_owned()), - true - ); - assert_eq!( - Solution::is_isomorphic("pecil".to_owned(), "this".to_owned()), - false - ); - assert_eq!( - Solution::is_isomorphic("paper".to_owned(), "title".to_owned()), - true - ); - } -} diff --git a/src/solution/s0206_reverse_linked_list.rs b/src/solution/s0206_reverse_linked_list.rs deleted file mode 100644 index b62aced8..00000000 --- a/src/solution/s0206_reverse_linked_list.rs +++ /dev/null @@ -1,52 +0,0 @@ -/** - * [206] Reverse Linked List - * - * Reverse a singly linked list. - * - * Example: - * - * - * Input: 1->2->3->4->5->NULL - * Output: 5->4->3->2->1->NULL - * - * - * Follow up: - * - * A linked list can be reversed either iteratively or recursively. Could you implement both? - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/reverse-linked-list/ -// discuss: https://leetcode.com/problems/reverse-linked-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn reverse_list(head: Option>) -> Option> { - let mut curr = head; - let mut next = None; - while let Some(mut inner) = curr { - curr = inner.next.take(); - inner.next = next; - next = Some(inner); - } - next - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_206() { - assert_eq!( - Solution::reverse_list(linked![1, 2, 3, 4, 5]), - linked![5, 4, 3, 2, 1] - ); - } -} diff --git a/src/solution/s0207_course_schedule.rs b/src/solution/s0207_course_schedule.rs deleted file mode 100644 index 2a793683..00000000 --- a/src/solution/s0207_course_schedule.rs +++ /dev/null @@ -1,105 +0,0 @@ -/** - * [207] Course Schedule - * - * There are a total of n courses you have to take, labeled from 0 to n-1. - * - * Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] - * - * Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? - * - * Example 1: - * - * - * Input: 2, [[1,0]] - * Output: true - * Explanation: There are a total of 2 courses to take. - * To take course 1 you should have finished course 0. So it is possible. - * - * Example 2: - * - * - * Input: 2, [[1,0],[0,1]] - * Output: false - * Explanation: There are a total of 2 courses to take. - * To take course 1 you should have finished course 0, and to take course 0 you should - * also have finished course 1. So it is impossible. - * - * - * Note: - * - *
    - * The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. - * You may assume that there are no duplicate edges in the input prerequisites. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/course-schedule/ -// discuss: https://leetcode.com/problems/course-schedule/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// topology sort, BFS -use std::collections::VecDeque; -impl Solution { - pub fn can_finish(num_courses: i32, prerequisites: Vec>) -> bool { - let num = num_courses as usize; - let mut matrix = vec![vec![false; num]; num]; - let mut in_degree = vec![0; num]; - // collects node in degree - for pre in prerequisites.iter() { - if !matrix[pre[1] as usize][pre[0] as usize] { - in_degree[pre[0] as usize] += 1; - } - matrix[pre[1] as usize][pre[0] as usize] = true; - } - let mut deq = VecDeque::new(); - // BFS starts with nodes with 0 in degree - for (node, &v) in in_degree.iter().enumerate() { - if v == 0 { - deq.push_back(node); - } - } - let mut cnt = 0; - while let Some(node) = deq.pop_front() { - cnt += 1; - for (i, &connect) in matrix[node].iter().enumerate() { - if connect { - in_degree[i] -= 1; - if in_degree[i] == 0 { - deq.push_back(i); - } - } - } - } - cnt == num_courses - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_207() { - assert_eq!(Solution::can_finish(2, vec![vec![1, 0]]), true); - assert_eq!(Solution::can_finish(2, vec![vec![1, 0], vec![0, 1]]), false); - assert_eq!( - Solution::can_finish( - 8, - vec![ - vec![1, 0], - vec![2, 6], - vec![1, 7], - vec![6, 4], - vec![7, 0], - vec![0, 5] - ] - ), - true - ); - } -} diff --git a/src/solution/s0208_implement_trie_prefix_tree.rs b/src/solution/s0208_implement_trie_prefix_tree.rs deleted file mode 100644 index 9ac8e470..00000000 --- a/src/solution/s0208_implement_trie_prefix_tree.rs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * [208] Implement Trie (Prefix Tree) - * - * Implement a trie with insert, search, and startsWith methods. - * - * Example: - * - * - * Trie trie = new Trie(); - * - * trie.insert("apple"); - * trie.search("apple"); // returns true - * trie.search("app"); // returns false - * trie.startsWith("app"); // returns true - * trie.insert("app"); - * trie.search("app"); // returns true - * - * - * Note: - * - * - * You may assume that all inputs are consist of lowercase letters a-z. - * All inputs are guaranteed to be non-empty strings. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/implement-trie-prefix-tree/ -// discuss: https://leetcode.com/problems/implement-trie-prefix-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -#[derive(Default)] -struct Trie { - is_end: bool, - nodes: [Option>; 26], -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl Trie { - /** Initialize your data structure here. */ - fn new() -> Self { - Default::default() - } - - /** insert a word into the trie. */ - fn insert(&mut self, word: String) { - let mut curr = self; - - for i in word.chars().map(|ch| (ch as u8 - 'a' as u8) as usize) { - curr = curr.nodes[i].get_or_insert_with(|| Box::new(Trie::new())); - } - curr.is_end = true; - } - - /** Returns if the word is in the trie. */ - fn search(&self, word: String) -> bool { - self.find(word).map_or(false, |t| t.is_end) - } - - /** Returns if there is any word in the trie that starts with the given prefix. */ - fn starts_with(&self, prefix: String) -> bool { - self.find(prefix).is_some() - } - - fn find(&self, word: String) -> Option<&Trie> { - let mut curr = self; - for i in word.chars().map(|ch| (ch as u8 - 'a' as u8) as usize) { - curr = curr.nodes[i].as_ref()?; - } - Some(curr) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_208() { - let mut trie = Trie::new(); - trie.insert("apple".to_owned()); - assert_eq!(trie.search("apple".to_owned()), true); // returns true - assert_eq!(trie.search("app".to_owned()), false); - assert_eq!(trie.starts_with("app".to_owned()), true); // returns true - trie.insert("app".to_owned()); - assert_eq!(trie.search("app".to_owned()), true); // returns true - } -} diff --git a/src/solution/s0209_minimum_size_subarray_sum.rs b/src/solution/s0209_minimum_size_subarray_sum.rs deleted file mode 100644 index b6a692d7..00000000 --- a/src/solution/s0209_minimum_size_subarray_sum.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [209] Minimum Size Subarray Sum - * - * Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. - * - * Example: - * - * - * Input: s = 7, nums = [2,3,1,2,4,3] - * Output: 2 - * Explanation: the subarray [4,3] has the minimal length under the problem constraint. - * - *
Follow up:
- * - *
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/minimum-size-subarray-sum/ -// discuss: https://leetcode.com/problems/minimum-size-subarray-sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn min_sub_array_len(s: i32, nums: Vec) -> i32 { - let (mut i, mut j) = (0_usize, 0_usize); - let mut min = i32::max_value(); - let mut found = false; - let mut sum = 0; - while j < nums.len() { - sum += nums[j]; - if sum >= s { - found = true; - while i <= j { - sum -= nums[i]; - i += 1; - if sum < s { - min = i32::min(min, j as i32 - i as i32 + 2); - break; - } - } - } - j += 1; - } - if found { - min - } else { - 0 - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_209() { - assert_eq!(Solution::min_sub_array_len(7, vec![2, 3, 1, 2, 4, 3]), 2); - assert_eq!(Solution::min_sub_array_len(4, vec![1, 4, 4]), 1); - } -} diff --git a/src/solution/s0210_course_schedule_ii.rs b/src/solution/s0210_course_schedule_ii.rs deleted file mode 100644 index dd3a1b03..00000000 --- a/src/solution/s0210_course_schedule_ii.rs +++ /dev/null @@ -1,98 +0,0 @@ -/** - * [210] Course Schedule II - * - * There are a total of n courses you have to take, labeled from 0 to n-1. - * - * Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] - * - * Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses. - * - * There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array. - * - * Example 1: - * - * - * Input: 2, [[1,0]] - * Output: [0,1] - * Explanation: There are a total of 2 courses to take. To take course 1 you should have finished - * course 0. So the correct course order is [0,1] . - * - * Example 2: - * - * - * Input: 4, [[1,0],[2,0],[3,1],[3,2]] - * Output: [0,1,2,3] or [0,2,1,3] - * Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both - * courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. - * So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] . - * - * Note: - * - *
    - * The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. - * You may assume that there are no duplicate edges in the input prerequisites. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/course-schedule-ii/ -// discuss: https://leetcode.com/problems/course-schedule-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::VecDeque; -impl Solution { - pub fn find_order(num_courses: i32, prerequisites: Vec>) -> Vec { - let num = num_courses as usize; - let mut matrix = vec![vec![false; num]; num]; - let mut in_degree = vec![0; num]; - // collects node in degree - for pre in prerequisites.iter() { - if !matrix[pre[1] as usize][pre[0] as usize] { - in_degree[pre[0] as usize] += 1; - } - matrix[pre[1] as usize][pre[0] as usize] = true; - } - let mut deq = VecDeque::new(); - // BFS starts with nodes with 0 in degree - for (node, &v) in in_degree.iter().enumerate() { - if v == 0 { - deq.push_back(node); - } - } - let mut res = Vec::with_capacity(num); - while let Some(node) = deq.pop_front() { - res.push(node as i32); - for (i, &connect) in matrix[node].iter().enumerate() { - if connect { - in_degree[i] -= 1; - if in_degree[i] == 0 { - deq.push_back(i); - } - } - } - } - if res.len() == num { - res - } else { - vec![] - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_210() { - assert_eq!(Solution::find_order(2, vec![vec![1, 0]]), vec![0, 1]); - assert_eq!( - Solution::find_order(4, vec![vec![1, 0], vec![2, 0], vec![3, 1], vec![3, 2]]), - vec![0, 1, 2, 3] - ); - } -} diff --git a/src/solution/s0211_add_and_search_word_data_structure_design.rs b/src/solution/s0211_add_and_search_word_data_structure_design.rs deleted file mode 100644 index 0652f951..00000000 --- a/src/solution/s0211_add_and_search_word_data_structure_design.rs +++ /dev/null @@ -1,129 +0,0 @@ -/** - * [211] Add and Search Word - Data structure design - * - * Design a data structure that supports the following two operations: - * - * - * void addWord(word) - * bool search(word) - * - * - * search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. - * - * Example: - * - * - * addWord("bad") - * addWord("dad") - * addWord("mad") - * search("pad") -> false - * search("bad") -> true - * search(".ad") -> true - * search("b..") -> true - * - * - * Note:
- * You may assume that all words are consist of lowercase letters a-z. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/add-and-search-word-data-structure-design/ -// discuss: https://leetcode.com/problems/add-and-search-word-data-structure-design/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct WordDictionary { - root: Option>, -} - -#[derive(Default)] -struct Trie { - is_end: bool, - marked: Vec, - nodes: [Option>; 26], -} - -impl Trie { - fn new() -> Self { - Default::default() - } -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl WordDictionary { - // /** Initialize your data structure here. */ - // fn new() -> Self { - // WordDictionary{ - // root: Some(Box::new(Trie::new())), - // } - // } - - // /** Adds a word into the data structure. */ - // fn add_word(&mut self, word: String) { - // let mut curr = self.root; - - // for i in word.chars().map(|ch| (ch as u8 - 'a' as u8) as usize) { - // curr = curr.as_ref().unwrap().nodes[i]; - // } - // curr.as_mut().unwrap().is_end = true; - // } - - // /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ - // fn search(&self, word: String) -> bool { - // let mut chs: Vec = word.chars().collect(); - // WordDictionary::search_from(self.root.as_ref(), &mut chs) - // } - - // fn search_from(node: Option<&Box>, chs: &mut [char]) -> bool { - // if node.is_none() { - // return false - // } - // let node = node.unwrap(); - // if chs.len() < 1 { - // return node.is_end - // } - // if chs[0] == '.' { - // // backtracking - // let mut sliced = &mut chs[1..]; - // for &idx in node.marked.iter() { - // if WordDictionary::search_from(node.nodes[idx].as_ref(), sliced) { - // return true - // } - // } - // false - // } else { - // let next = node.nodes[(chs[0] as u8 - 'a' as u8) as usize].as_ref(); - // WordDictionary::search_from(next, &mut chs[1..]) - // } - // } -} - -/** - * Your WordDictionary object will be instantiated and called as such: - * let obj = WordDictionary::new(); - * obj.add_word(word); - * let ret_2: bool = obj.search(word); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_211() { - // let mut dict = WordDictionary::new(); - // dict.add_word("bad".to_owned()); - // dict.add_word("dad".to_owned()); - // dict.add_word("mad".to_owned()); - // assert_eq!(dict.search("pad".to_owned()), false); - // assert_eq!(dict.search("bad".to_owned()), true); - // assert_eq!(dict.search(".ad".to_owned()), true); - // assert_eq!(dict.search("da.".to_owned()), true); - } -} diff --git a/src/solution/s0212_word_search_ii.rs b/src/solution/s0212_word_search_ii.rs deleted file mode 100644 index ada034c8..00000000 --- a/src/solution/s0212_word_search_ii.rs +++ /dev/null @@ -1,57 +0,0 @@ -/** - * [212] Word Search II - * - * Given a 2D board and a list of words from the dictionary, find all words in the board. - * - * Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. - * - * - * - * Example: - * - * - * Input: - * board = [ - * ['o','a','a','n'], - * ['e','t','a','e'], - * ['i','h','k','r'], - * ['i','f','l','v'] - * ] - * words = ["oath","pea","eat","rain"] - * - * Output: ["eat","oath"] - * - * - * - * - * Note: - * - *
    - * All inputs are consist of lowercase letters a-z. - * The values of words are distinct. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-search-ii/ -// discuss: https://leetcode.com/problems/word-search-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -// TODO - -impl Solution { - pub fn find_words(board: Vec>, words: Vec) -> Vec { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_212() {} -} diff --git a/src/solution/s0213_house_robber_ii.rs b/src/solution/s0213_house_robber_ii.rs deleted file mode 100644 index fbe55040..00000000 --- a/src/solution/s0213_house_robber_ii.rs +++ /dev/null @@ -1,69 +0,0 @@ -/** - * [213] House Robber II - * - * You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. - * - * Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. - * - * Example 1: - * - * - * Input: [2,3,2] - * Output: 3 - * Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), - * because they are adjacent houses. - * - * - * Example 2: - * - * - * Input: [1,2,3,1] - * Output: 4 - * Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). - * Total amount you can rob = 1 + 3 = 4. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/house-robber-ii/ -// discuss: https://leetcode.com/problems/house-robber-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// DP twice: rob first one || not rob first one -// F[i] = max(F[i-2] + num[i], F[i-1]) -impl Solution { - pub fn rob(nums: Vec) -> i32 { - let mut max = i32::min_value(); - for &rob_first in vec![true, false].iter() { - let (mut prev, mut curr) = (0, 0); - for (k, &num) in nums.iter().enumerate() { - if k == 0 && !rob_first { - continue; - } - // k is last element but not the first element - if k != 0 && k == (nums.len() - 1) && rob_first { - continue; - } - let next = i32::max(prev + num, curr); - prev = curr; - curr = next; - } - max = i32::max(max, curr) - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_213() { - assert_eq!(Solution::rob(vec![2, 3, 2]), 3); - assert_eq!(Solution::rob(vec![1, 2, 3, 1]), 4); - } -} diff --git a/src/solution/s0214_shortest_palindrome.rs b/src/solution/s0214_shortest_palindrome.rs deleted file mode 100644 index 425eec95..00000000 --- a/src/solution/s0214_shortest_palindrome.rs +++ /dev/null @@ -1,40 +0,0 @@ -/** - * [214] Shortest Palindrome - * - * Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. - * - * Example 1: - * - * - * Input: "aacecaaa" - * Output: "aaacecaaa" - * - * - * Example 2: - * - * - * Input: "abcd" - * Output: "dcbabcd" - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/shortest-palindrome/ -// discuss: https://leetcode.com/problems/shortest-palindrome/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn shortest_palindrome(s: String) -> String { - "".to_owned() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_214() {} -} diff --git a/src/solution/s0215_kth_largest_element_in_an_array.rs b/src/solution/s0215_kth_largest_element_in_an_array.rs deleted file mode 100644 index 159e7af6..00000000 --- a/src/solution/s0215_kth_largest_element_in_an_array.rs +++ /dev/null @@ -1,62 +0,0 @@ -/** - * [215] Kth Largest Element in an Array - * - * Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. - * - * Example 1: - * - * - * Input: [3,2,1,5,6,4] and k = 2 - * Output: 5 - * - * - * Example 2: - * - * - * Input: [3,2,3,1,2,4,5,5,6] and k = 4 - * Output: 4 - * - * Note:
- * You may assume k is always valid, 1 ≤ k ≤ array's length. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/kth-largest-element-in-an-array/ -// discuss: https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cmp::Reverse; -use std::collections::BinaryHeap; -impl Solution { - pub fn find_kth_largest(nums: Vec, k: i32) -> i32 { - let k = k as usize; - let mut heap = BinaryHeap::with_capacity(k); - for &num in nums.iter() { - if heap.len() < k as usize { - heap.push(Reverse(num)) - } else if num >= heap.peek().unwrap().0 { - heap.pop(); - heap.push(Reverse(num)); - } - } - heap.peek().unwrap().0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_215() { - assert_eq!( - Solution::find_kth_largest(vec![3, 2, 3, 1, 2, 4, 5, 5, 6], 4), - 4 - ); - assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5); - } -} diff --git a/src/solution/s0216_combination_sum_iii.rs b/src/solution/s0216_combination_sum_iii.rs deleted file mode 100644 index 0f714e01..00000000 --- a/src/solution/s0216_combination_sum_iii.rs +++ /dev/null @@ -1,83 +0,0 @@ -/** - * [216] Combination Sum III - * - *
- * Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. - * - * Note: - * - * - * All numbers will be positive integers. - * The solution set must not contain duplicate combinations. - * - * - * Example 1: - * - * - * Input: k = 3, n = 7 - * Output: [[1,2,4]] - * - * - * Example 2: - * - * - * Input: k = 3, n = 9 - * Output: [[1,2,6], [1,3,5], [2,3,4]] - * - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/combination-sum-iii/ -// discuss: https://leetcode.com/problems/combination-sum-iii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn combination_sum3(k: i32, n: i32) -> Vec> { - if k > 9 || k < 1 { - return vec![]; - } - let max = (0..k).fold(0, |acc, t| acc + 9 - t); - let min = (0..k).fold(0, |acc, t| acc + t); - if n < min || n > max { - return vec![]; - } - let mut res = Vec::new(); - let mut seed = Vec::new(); - Solution::helper(n, 0, k, seed, &mut res); - res - } - - fn helper(distance: i32, prev: i32, remain: i32, mut curr: Vec, res: &mut Vec>) { - if remain == 0 { - if distance == 0 { - res.push(curr); - } - return; - } - for i in (prev + 1..=9) { - if distance - i < 0 { - break; - } - let mut new_vec = curr.clone(); - new_vec.push(i); - Solution::helper(distance - i, i, remain - 1, new_vec, res); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_216() { - assert_eq!( - Solution::combination_sum3(3, 9), - vec![vec![1, 2, 6], vec![1, 3, 5], vec![2, 3, 4]] - ); - } -} diff --git a/src/solution/s0217_contains_duplicate.rs b/src/solution/s0217_contains_duplicate.rs deleted file mode 100644 index 0d2e5e12..00000000 --- a/src/solution/s0217_contains_duplicate.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [217] Contains Duplicate - * - * Given an array of integers, find if the array contains any duplicates. - * - * Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. - * - * Example 1: - * - * - * Input: [1,2,3,1] - * Output: true - * - * Example 2: - * - * - * Input: [1,2,3,4] - * Output: false - * - * Example 3: - * - * - * Input: [1,1,1,3,3,4,3,2,4,2] - * Output: true - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/contains-duplicate/ -// discuss: https://leetcode.com/problems/contains-duplicate/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn contains_duplicate(nums: Vec) -> bool { - if nums.is_empty() { - return false; - } - let mut nums = nums; - nums.sort_unstable(); - let mut prev = nums[0]; - for i in 1..nums.len() { - if nums[i] == prev { - return true; - } - prev = nums[i] - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_217() { - assert_eq!(Solution::contains_duplicate(vec![1]), false); - assert_eq!(Solution::contains_duplicate(vec![]), false); - assert_eq!(Solution::contains_duplicate(vec![1, 2, 3, 4]), false); - assert_eq!(Solution::contains_duplicate(vec![1, 2, 3, 1]), true); - } -} diff --git a/src/solution/s0218_the_skyline_problem.rs b/src/solution/s0218_the_skyline_problem.rs deleted file mode 100644 index 7f0ba3c1..00000000 --- a/src/solution/s0218_the_skyline_problem.rs +++ /dev/null @@ -1,46 +0,0 @@ -/** - * [218] The Skyline Problem - * - * A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B). - * Buildings Skyline Contour - * - * The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. - * - * For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] . - * - * The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour. - * - * For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ]. - * - * Notes: - * - * - * The number of buildings in any input list is guaranteed to be in the range [0, 10000]. - * The input list is already sorted in ascending order by the left x position Li. - * The output list must be sorted by the x position. - * There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/the-skyline-problem/ -// discuss: https://leetcode.com/problems/the-skyline-problem/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn get_skyline(buildings: Vec>) -> Vec> { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_218() {} -} diff --git a/src/solution/s0219_contains_duplicate_ii.rs b/src/solution/s0219_contains_duplicate_ii.rs deleted file mode 100644 index da446dae..00000000 --- a/src/solution/s0219_contains_duplicate_ii.rs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * [219] Contains Duplicate II - * - * Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. - * - *
- * Example 1: - * - * - * Input: nums = [1,2,3,1], k = 3 - * Output: true - * - * - *
- * Example 2: - * - * - * Input: nums = [1,0,1,1], k = 1 - * Output: true - * - * - *
- * Example 3: - * - * - * Input: nums = [1,2,3,1,2,3], k = 2 - * Output: false - * - *
- *
- *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/contains-duplicate-ii/ -// discuss: https://leetcode.com/problems/contains-duplicate-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashMap; -impl Solution { - pub fn contains_nearby_duplicate(nums: Vec, k: i32) -> bool { - let mut map = HashMap::new(); - for (idx, &num) in nums.iter().enumerate() { - match map.get(&num) { - Some(v) => { - if idx - v <= k as usize { - return true; - } - map.insert(num, idx); - } - None => { - map.insert(num, idx); - } - } - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_219() { - assert_eq!( - Solution::contains_nearby_duplicate(vec![1, 2, 3, 1, 2, 3], 2), - false - ); - assert_eq!( - Solution::contains_nearby_duplicate(vec![1, 2, 3, 1, 2, 3], 3), - true - ); - } -} diff --git a/src/solution/s0220_contains_duplicate_iii.rs b/src/solution/s0220_contains_duplicate_iii.rs deleted file mode 100644 index 0677b1d3..00000000 --- a/src/solution/s0220_contains_duplicate_iii.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [220] Contains Duplicate III - * - * Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. - * - *
- * Example 1: - * - * - * Input: nums = [1,2,3,1], k = 3, t = 0 - * Output: true - * - * - *
- * Example 2: - * - * - * Input: nums = [1,0,1,1], k = 1, t = 2 - * Output: true - * - * - *
- * Example 3: - * - * - * Input: nums = [1,5,9,1,5,9], k = 2, t = 3 - * Output: false - * - *
- *
- *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/contains-duplicate-iii/ -// discuss: https://leetcode.com/problems/contains-duplicate-iii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -use std::collections::HashMap; -impl Solution { - pub fn contains_nearby_almost_duplicate(nums: Vec, k: i32, t: i32) -> bool { - if k < 1 || t < 0 { - return false; - } - let mut map = HashMap::new(); - for i in 0..nums.len() { - let remap = nums[i] as i64 - i32::min_value() as i64; - let bucket = remap / (t as i64 + 1); - println!("{} {}", remap, bucket); - if map.contains_key(&bucket) - || map - .get(&(bucket - 1)) - .map_or(false, |v| remap - v <= t as i64) - || map - .get(&(bucket + 1)) - .map_or(false, |v| v - remap <= t as i64) - { - return true; - } - if i >= k as usize { - let last_bucket = - (nums[i - k as usize] as i64 - i32::min_value() as i64) / (t as i64 + 1); - map.remove(&last_bucket); - } - map.insert(bucket, remap); - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_220() { - // assert_eq!(Solution::contains_nearby_almost_duplicate(vec![1,5,9,1,5,9], 2, 3), false); - // assert_eq!(Solution::contains_nearby_almost_duplicate(vec![1,2,3,1], 3, 0), true); - assert_eq!( - Solution::contains_nearby_almost_duplicate(vec![-1, 2147483647], 1, 2147483647), - false - ); - } -} diff --git a/src/solution/s0221_maximal_square.rs b/src/solution/s0221_maximal_square.rs deleted file mode 100644 index 34f793ac..00000000 --- a/src/solution/s0221_maximal_square.rs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * [221] Maximal Square - * - * Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. - * - * Example: - * - * - * Input: - * - * 1 0 1 0 0 - * 1 0 1 1 1 - * 1 1 1 1 1 - * 1 0 0 1 0 - * - * Output: 4 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/maximal-square/ -// discuss: https://leetcode.com/problems/maximal-square/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -DP, f(i, j) to represent the max square of matrix that end with (i, j) (right bottom corener), then: - -f(0, 0) = matrix[0][0] -f(i, j) = if matrix[0][0] { min(f(i-1,j), f(i,j-1), f(i-1)(j-1)) + 1 } else { 0 } - -The equation explained: - -matrix: dp: -1 1 1 1 1 1 -1 1 1 -> 1 2 2 -1 1 1 1 2 3 -*/ -impl Solution { - pub fn maximal_square(matrix: Vec>) -> i32 { - if matrix.is_empty() || matrix[0].is_empty() { - return 0; - } - let (height, width) = (matrix.len(), matrix[0].len()); - let mut dp = vec![vec![0; width]; height]; - let mut max = 0; - for i in 0..height { - for j in 0..width { - if matrix[i][j] == '0' { - continue; - } - dp[i][j] = i32::min( - i32::min( - if i < 1 { 0 } else { dp[i - 1][j] }, - if j < 1 { 0 } else { dp[i][j - 1] }, - ), - if i < 1 || j < 1 { 0 } else { dp[i - 1][j - 1] }, - ) + 1; - max = i32::max(max, dp[i][j]) - } - } - max * max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_221() { - assert_eq!( - Solution::maximal_square(vec![ - vec!['1', '0', '1', '0', '0'], - vec!['1', '0', '1', '1', '1'], - vec!['1', '1', '1', '1', '1'], - vec!['1', '0', '0', '1', '0'], - ]), - 4 - ) - } -} diff --git a/src/solution/s0222_count_complete_tree_nodes.rs b/src/solution/s0222_count_complete_tree_nodes.rs deleted file mode 100644 index ae0d410b..00000000 --- a/src/solution/s0222_count_complete_tree_nodes.rs +++ /dev/null @@ -1,88 +0,0 @@ -/** - * [222] Count Complete Tree Nodes - * - * Given a complete binary tree, count the number of nodes. - * - * Note: - * - * Definition of a complete binary tree from Wikipedia:
- * In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2^h nodes inclusive at the last level h. - * - * Example: - * - * - * Input: - * 1 - * / \ - * 2 3 - * / \ / - * 4 5 6 - * - * Output: 6 - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/count-complete-tree-nodes/ -// discuss: https://leetcode.com/problems/count-complete-tree-nodes/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn count_nodes(root: Option>>) -> i32 { - // 0. get the hight of full nodes - let mut height = 0; - let mut curr = root.clone(); - let mut result = 0; - while let Some(inner) = curr { - height += 1; - result += 2_i32.pow(height - 1); - curr = inner.borrow().right.clone(); - } - if height == 0 { - return result; - } - // 1. 'binary search' to find the node number of the lowest level - // the lowest level may have 0~2^H-1 node - let mut curr_root = root.clone(); - while height > 1 { - // see if left tree is full - let mut node = curr_root.clone().unwrap().borrow().left.clone(); - let mut level = 2; - while level < height { - node = node.unwrap().borrow().right.clone(); - level += 1; - } - if node.unwrap().borrow().right.is_some() { - curr_root = curr_root.unwrap().borrow().right.clone(); - result += 2_i32.pow(height - 1); - } else { - curr_root = curr_root.unwrap().borrow().left.clone(); - } - height -= 1; - } - if curr_root.as_ref().unwrap().borrow().left.is_some() { - result += 1; - } - result - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_222() { - assert_eq!(Solution::count_nodes(tree![1, 1, 1, 1, 1, 1, 1]), 7); - assert_eq!(Solution::count_nodes(tree![]), 0); - assert_eq!(Solution::count_nodes(tree![1, 1]), 2); - assert_eq!(Solution::count_nodes(tree![1]), 1); - assert_eq!(Solution::count_nodes(tree![1, 1, 1]), 3); - } -} diff --git a/src/solution/s0223_rectangle_area.rs b/src/solution/s0223_rectangle_area.rs deleted file mode 100644 index 647b6b2a..00000000 --- a/src/solution/s0223_rectangle_area.rs +++ /dev/null @@ -1,62 +0,0 @@ -/** - * [223] Rectangle Area - * - * Find the total area covered by two rectilinear rectangles in a 2D plane. - * - * Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. - * - * Rectangle Area - * - * Example: - * - * - * Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2 - * Output: 45 - * - * Note: - * - * Assume that the total area is never beyond the maximum possible value of int. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/rectangle-area/ -// discuss: https://leetcode.com/problems/rectangle-area/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// mention the integer divition -impl Solution { - pub fn compute_area(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) -> i32 { - let center1 = ((a + c), (b + d)); - let center2 = ((e + g), (f + h)); - let rect1 = (c - a, d - b); - let rect2 = (g - e, h - f); - let x_intersect = i32::min( - (rect1.0 + rect2.0 - (center1.0 - center2.0).abs()), - i32::min(2 * rect1.0, 2 * rect2.0), - ) / 2; - let x_intersect = if x_intersect < 0 { 0 } else { x_intersect }; - let y_intersect = i32::min( - (rect1.1 + rect2.1 - (center1.1 - center2.1).abs()), - i32::min(2 * rect1.1, 2 * rect2.1), - ) / 2; - let y_intersect = if y_intersect < 0 { 0 } else { y_intersect }; - rect1.0 * rect1.1 - x_intersect * y_intersect + rect2.0 * rect2.1 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_223() { - assert_eq!(Solution::compute_area(0, 0, 0, 0, 0, 0, 0, 0), 0); - assert_eq!(Solution::compute_area(-3, 0, 3, 4, 0, -1, 9, 2), 45); - assert_eq!(Solution::compute_area(-2, -2, 2, 2, -2, -2, 2, 2), 16); - assert_eq!(Solution::compute_area(-2, -2, 2, 2, -1, 4, 1, 6), 20); - } -} diff --git a/src/solution/s0224_basic_calculator.rs b/src/solution/s0224_basic_calculator.rs deleted file mode 100644 index 5d917661..00000000 --- a/src/solution/s0224_basic_calculator.rs +++ /dev/null @@ -1,156 +0,0 @@ -/** - * [224] Basic Calculator - * - * Implement a basic calculator to evaluate a simple expression string. - * - * The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . - * - * Example 1: - * - * - * Input: "1 + 1" - * Output: 2 - * - * - * Example 2: - * - * - * Input: " 2-1 + 2 " - * Output: 3 - * - * Example 3: - * - * - * Input: "(1+(4+5+2)-3)+(6+8)" - * Output: 23 - * Note: - * - * - * You may assume that the given expression is always valid. - * Do not use the eval built-in library function. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/basic-calculator/ -// discuss: https://leetcode.com/problems/basic-calculator/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -#[derive(PartialEq, Copy, Clone, Debug)] -enum Token { - LeftBracket, - RightBracket, - PlusSign, - MinusSign, - Number(i64), -} - -impl Solution { - pub fn calculate(s: String) -> i32 { - // lexer - let mut token_stream = Vec::new(); - let mut num = 0_i64; - let mut in_num = false; - for ch in s.chars() { - match ch { - '0'..='9' => { - in_num = true; - num = 10 * num + (ch as u8 - '0' as u8) as i64; - } - _ => { - if in_num { - token_stream.push(Token::Number(num)); - num = 0; - in_num = false; - } - match ch { - '(' => { - token_stream.push(Token::LeftBracket); - } - ')' => { - token_stream.push(Token::RightBracket); - } - '+' => { - token_stream.push(Token::PlusSign); - } - '-' => { - token_stream.push(Token::MinusSign); - } - _ => {} - }; - } - } - } - if in_num { - token_stream.push(Token::Number(num)); - } - - // parser - let mut stack = Vec::new(); - let mut iter = token_stream.into_iter(); - let mut pause = false; - let mut token = Token::LeftBracket; - loop { - if !pause { - token = if let Some(token) = iter.next() { - token - } else { - break; - } - } else { - pause = false; - } - match token { - Token::LeftBracket => { - stack.push(token); - } - Token::RightBracket => { - if let Token::Number(right_hand) = stack.pop().unwrap() { - stack.pop(); - pause = true; - token = Token::Number(right_hand); - } - } - Token::PlusSign => { - stack.push(token); - } - Token::MinusSign => { - stack.push(token); - } - Token::Number(num) => { - if stack.is_empty() || Token::LeftBracket == *stack.last().unwrap() { - stack.push(Token::Number(num)); - } else { - let sign = stack.pop().unwrap(); - if let Token::Number(left_hand) = stack.pop().unwrap() { - let res = - left_hand + num * if Token::PlusSign == sign { 1 } else { -1 }; - stack.push(Token::Number(res)); - } - } - } - } - } - if let Token::Number(num) = stack.pop().unwrap() { - return num as i32; - } - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_224() { - assert_eq!(Solution::calculate("(1+(4+5+2)-3)+(6+8)".to_owned()), 23); - assert_eq!(Solution::calculate("1+1".to_owned()), 2); - assert_eq!(Solution::calculate("0".to_owned()), 0); - assert_eq!(Solution::calculate("2147483647".to_owned()), 2147483647); - } -} diff --git a/src/solution/s0225_implement_stack_using_queues.rs b/src/solution/s0225_implement_stack_using_queues.rs deleted file mode 100644 index f162e9a6..00000000 --- a/src/solution/s0225_implement_stack_using_queues.rs +++ /dev/null @@ -1,125 +0,0 @@ -/** - * [225] Implement Stack using Queues - * - * Implement the following operations of a stack using queues. - * - * - * push(x) -- Push element x onto stack. - * pop() -- Removes the element on top of the stack. - * top() -- Get the top element. - * empty() -- Return whether the stack is empty. - * - * - * Example: - * - * - * MyStack stack = new MyStack(); - * - * stack.push(1); - * stack.push(2); - * stack.top(); // returns 2 - * stack.pop(); // returns 2 - * stack.empty(); // returns false - * - * Notes: - * - * - * You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. - * Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. - * You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/implement-stack-using-queues/ -// discuss: https://leetcode.com/problems/implement-stack-using-queues/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct MyStack { - q1: VecDeque, - q2: VecDeque, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -use std::collections::VecDeque; -impl MyStack { - /** Initialize your data structure here. */ - fn new() -> Self { - MyStack { - q1: VecDeque::new(), - q2: VecDeque::new(), - } - } - - /** Push element x onto stack. */ - fn push(&mut self, x: i32) { - if self.q1.is_empty() { - self.q1.push_back(x); - while let Some(v) = self.q2.pop_front() { - self.q1.push_back(v); - } - } else { - self.q2.push_back(x); - while let Some(v) = self.q1.pop_front() { - self.q2.push_back(v); - } - } - } - - /** Removes the element on top of the stack and returns that element. */ - fn pop(&mut self) -> i32 { - if self.q1.is_empty() { - self.q2.pop_front().unwrap() - } else { - self.q1.pop_front().unwrap() - } - } - - /** Get the top element. */ - fn top(&self) -> i32 { - if self.q1.is_empty() { - *self.q2.front().unwrap() - } else { - *self.q1.front().unwrap() - } - } - - /** Returns whether the stack is empty. */ - fn empty(&self) -> bool { - self.q1.is_empty() && self.q2.is_empty() - } -} - -/** - * Your MyStack object will be instantiated and called as such: - * let obj = MyStack::new(); - * obj.push(x); - * let ret_2: i32 = obj.pop(); - * let ret_3: i32 = obj.top(); - * let ret_4: bool = obj.empty(); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_225() { - let mut stack = MyStack::new(); - - stack.push(1); - stack.push(2); - assert_eq!(stack.top(), 2); // returns 2 - assert_eq!(stack.pop(), 2); // returns 2 - assert_eq!(stack.empty(), false); // returns false - assert_eq!(stack.pop(), 1); - assert_eq!(stack.empty(), true); - } -} diff --git a/src/solution/s0226_invert_binary_tree.rs b/src/solution/s0226_invert_binary_tree.rs deleted file mode 100644 index 1a1b6115..00000000 --- a/src/solution/s0226_invert_binary_tree.rs +++ /dev/null @@ -1,69 +0,0 @@ -/** - * [226] Invert Binary Tree - * - * Invert a binary tree. - * - * Example: - * - * Input: - * - * - * 4 - * / \ - * 2 7 - * / \ / \ - * 1 3 6 9 - * - * Output: - * - * - * 4 - * / \ - * 7 2 - * / \ / \ - * 9 6 3 1 - * - * Trivia:
- * This problem was inspired by this original tweet by Max Howell: - * - *
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
- * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/invert-binary-tree/ -// discuss: https://leetcode.com/problems/invert-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn invert_tree(root: Option>>) -> Option>> { - if let Some(node) = root.clone() { - Solution::invert_tree(node.borrow().right.clone()); - Solution::invert_tree(node.borrow().left.clone()); - let left = node.borrow().left.clone(); - let right = node.borrow().right.clone(); - node.borrow_mut().left = right; - node.borrow_mut().right = left; - } - root - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_226() { - assert_eq!( - Solution::invert_tree(tree![4, 2, 7, 1, 3, 6, 9]), - tree![4, 7, 2, 9, 6, 3, 1] - ); - } -} diff --git a/src/solution/s0227_basic_calculator_ii.rs b/src/solution/s0227_basic_calculator_ii.rs deleted file mode 100644 index 07e349dd..00000000 --- a/src/solution/s0227_basic_calculator_ii.rs +++ /dev/null @@ -1,107 +0,0 @@ -/** - * [227] Basic Calculator II - * - * Implement a basic calculator to evaluate a simple expression string. - * - * The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. - * - * Example 1: - * - * - * Input: "3+2*2" - * Output: 7 - * - * - * Example 2: - * - * - * Input: " 3/2 " - * Output: 1 - * - * Example 3: - * - * - * Input: " 3+5 / 2 " - * Output: 5 - * - * - * Note: - * - * - * You may assume that the given expression is always valid. - * Do not use the eval built-in library function. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/basic-calculator-ii/ -// discuss: https://leetcode.com/problems/basic-calculator-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn calculate(s: String) -> i32 { - let mut acc = 0_i64; - let mut prev = 0_i64; - let mut curr = 0_i64; - let mut sign = 1; - let mut has_prev = false; - let mut multiple = true; - for ch in s.chars() { - match ch { - '0'..='9' => { - curr = 10 * curr + (ch as u8 - '0' as u8) as i64; - } - '+' | '-' => { - if has_prev { - if multiple { - curr = prev * curr; - } else { - curr = prev / curr; - } - has_prev = false; - } - acc += curr * sign; - curr = 0; - sign = if ch == '+' { 1 } else { -1 }; - } - '*' | '/' => { - if has_prev { - if multiple { - curr = prev * curr; - } else { - curr = prev / curr; - } - } - has_prev = true; - prev = curr; - curr = 0; - multiple = if ch == '*' { true } else { false }; - } - _ => {} - } - } - if has_prev { - if multiple { - curr = prev * curr; - } else { - curr = prev / curr; - } - } - acc += sign * curr; - acc as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_227() { - assert_eq!(Solution::calculate("3+2*2".to_owned()), 7); - } -} diff --git a/src/solution/s0228_summary_ranges.rs b/src/solution/s0228_summary_ranges.rs deleted file mode 100644 index 63e8fe77..00000000 --- a/src/solution/s0228_summary_ranges.rs +++ /dev/null @@ -1,74 +0,0 @@ -/** - * [228] Summary Ranges - * - * Given a sorted integer array without duplicates, return the summary of its ranges. - * - * Example 1: - * - * - * Input: [0,1,2,4,5,7] - * Output: ["0->2","4->5","7"] - * Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range. - * - * - * Example 2: - * - * - * Input: [0,2,3,4,6,8,9] - * Output: ["0","2->4","6","8->9"] - * Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/summary-ranges/ -// discuss: https://leetcode.com/problems/summary-ranges/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn summary_ranges(nums: Vec) -> Vec { - if nums.is_empty() { - return vec![]; - } - let mut res = Vec::new(); - let mut curr = nums[0]; - let mut start = nums[0]; - for num in nums.into_iter().skip(1) { - if num == curr + 1 { - curr = num; - } else { - // seq done - Solution::record(&mut res, start, curr); - start = num; - curr = num; - } - } - Solution::record(&mut res, start, curr); - res - } - - pub fn record(vec: &mut Vec, start: i32, end: i32) { - if start == end { - vec.push(format!("{}", start)) - } else { - vec.push(format!("{}->{}", start, end)) - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_228() { - assert_eq!( - Solution::summary_ranges(vec![0, 1, 2, 3, 4, 5, 6]), - vec_string!["0->6"] - ); - } -} diff --git a/src/solution/s0229_majority_element_ii.rs b/src/solution/s0229_majority_element_ii.rs deleted file mode 100644 index fab987ba..00000000 --- a/src/solution/s0229_majority_element_ii.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [229] Majority Element II - * - * Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. - * - * Note: The algorithm should run in linear time and in O(1) space. - * - * Example 1: - * - * - * Input: [3,2,3] - * Output: [3] - * - * Example 2: - * - * - * Input: [1,1,1,3,3,2,2,2] - * Output: [1,2] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/majority-element-ii/ -// discuss: https://leetcode.com/problems/majority-element-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn majority_element(nums: Vec) -> Vec { - if nums.is_empty() { - return vec![]; - } - let (mut vote0, mut vote1, mut candidate0, mut candidate1) = (0, 0, -1, -2); - for &num in nums.iter() { - if num == candidate0 { - vote0 += 1; - } else if num == candidate1 { - vote1 += 1; - } else if vote0 == 0 { - candidate0 = num; - vote0 = 1; - } else if vote1 == 0 { - candidate1 = num; - vote1 = 1; - } else { - vote0 -= 1; - vote1 -= 1; - } - } - // the presents of majority element is not guaranteed, we have to do a double check - let mut res = Vec::new(); - for &v in vec![candidate0, candidate1].iter() { - let mut count = 0; - for &num in nums.iter() { - if v == num { - count += 1; - } - } - if count > (nums.len() / 3) as i32 { - res.push(v); - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_229() { - assert_eq!( - Solution::majority_element(vec![1, 1, 1, 2, 2, 2, 3, 3, 3]), - vec![] - ); - assert_eq!( - Solution::majority_element(vec![1, 1, 1, 2, 2, 3, 3, 3]), - vec![1, 3] - ); - assert_eq!(Solution::majority_element(vec![1]), vec![1]); - assert_eq!(Solution::majority_element(vec![5, 6, 6]), vec![6]); - assert_eq!(Solution::majority_element(vec![1, 2, 3, 4]), vec![]); - } -} diff --git a/src/solution/s0230_kth_smallest_element_in_a_bst.rs b/src/solution/s0230_kth_smallest_element_in_a_bst.rs deleted file mode 100644 index 0533f705..00000000 --- a/src/solution/s0230_kth_smallest_element_in_a_bst.rs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * [230] Kth Smallest Element in a BST - * - * Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. - * - * Note:
- * You may assume k is always valid, 1 ≤ k ≤ BST's total elements. - * - * Example 1: - * - * - * Input: root = [3,1,4,null,2], k = 1 - * 3 - * / \ - * 1 4 - * \ - * 2 - * Output: 1 - * - * Example 2: - * - * - * Input: root = [5,3,6,2,4,null,null,1], k = 3 - * 5 - * / \ - * 3 6 - * / \ - * 2 4 - * / - * 1 - * Output: 3 - * - * - * Follow up:
- * What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/kth-smallest-element-in-a-bst/ -// discuss: https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn kth_smallest(root: Option>>, k: i32) -> i32 { - let mut res = 0; - Solution::helper(root, k, &mut res); - res - } - - pub fn helper(root: Option>>, k: i32, res: &mut i32) -> i32 { - if k <= 0 { - return 0; - } - if let Some(node) = root { - let left = Solution::helper(node.borrow().left.clone(), k, res); - if left == 1 { - *res = node.borrow().val; - } - let right = Solution::helper(node.borrow().right.clone(), left - 1, res); - right - } else { - k - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_230() { - assert_eq!(Solution::kth_smallest(tree![3, 1, 4, null, 2], 1), 1); - assert_eq!(Solution::kth_smallest(tree![3, 1, 4, null, 2], 2), 2); - assert_eq!(Solution::kth_smallest(tree![3, 1, 4, null, 2], 3), 3); - } -} diff --git a/src/solution/s0232_implement_queue_using_stacks.rs b/src/solution/s0232_implement_queue_using_stacks.rs deleted file mode 100644 index 70bf3735..00000000 --- a/src/solution/s0232_implement_queue_using_stacks.rs +++ /dev/null @@ -1,110 +0,0 @@ -/** - * [232] Implement Queue using Stacks - * - * Implement the following operations of a queue using stacks. - * - * - * push(x) -- Push element x to the back of queue. - * pop() -- Removes the element from in front of queue. - * peek() -- Get the front element. - * empty() -- Return whether the queue is empty. - * - * - * Example: - * - * - * MyQueue queue = new MyQueue(); - * - * queue.push(1); - * queue.push(2); - * queue.peek(); // returns 1 - * queue.pop(); // returns 1 - * queue.empty(); // returns false - * - * Notes: - * - * - * You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. - * Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. - * You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/implement-queue-using-stacks/ -// discuss: https://leetcode.com/problems/implement-queue-using-stacks/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct MyQueue { - vec1: Vec, - vec2: Vec, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl MyQueue { - /** Initialize your data structure here. */ - fn new() -> Self { - MyQueue { - vec1: Vec::new(), - vec2: Vec::new(), - } - } - - /** Push element x to the back of queue. */ - fn push(&mut self, x: i32) { - while let Some(v) = self.vec1.pop() { - self.vec2.push(v); - } - self.vec2.push(x); - while let Some(v) = self.vec2.pop() { - self.vec1.push(v); - } - } - - /** Removes the element from in front of queue and returns that element. */ - fn pop(&mut self) -> i32 { - self.vec1.pop().unwrap() - } - - /** Get the front element. */ - fn peek(&self) -> i32 { - *self.vec1.last().unwrap() - } - - /** Returns whether the queue is empty. */ - fn empty(&self) -> bool { - self.vec1.is_empty() - } -} - -/** - * Your MyQueue object will be instantiated and called as such: - * let obj = MyQueue::new(); - * obj.push(x); - * let ret_2: i32 = obj.pop(); - * let ret_3: i32 = obj.peek(); - * let ret_4: bool = obj.empty(); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_232() { - let mut queue = MyQueue::new(); - - queue.push(1); - queue.push(2); - assert_eq!(queue.peek(), 1); // returns 1 - assert_eq!(queue.pop(), 1); // returns 1 - assert_eq!(queue.empty(), false); // returns false - } -} diff --git a/src/solution/s0238_product_of_array_except_self.rs b/src/solution/s0238_product_of_array_except_self.rs deleted file mode 100644 index ef5683c4..00000000 --- a/src/solution/s0238_product_of_array_except_self.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [238] Product of Array Except Self - * - * Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. - * - * Example: - * - * - * Input: [1,2,3,4] - * Output: [24,12,8,6] - * - * - * Note: Please solve it without division and in O(n). - * - * Follow up:
- * Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/product-of-array-except-self/ -// discuss: https://leetcode.com/problems/product-of-array-except-self/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -x 2 3 4 = 24 -1 x 3 4 = 12 -1 2 x 4 = 8 -1 2 3 x = 6 - */ -impl Solution { - pub fn product_except_self(nums: Vec) -> Vec { - if nums.len() < 2 { - return vec![]; - } - let mut res = vec![1; nums.len()]; - let mut n = 1; - for i in (0..nums.len() - 1).rev() { - n *= nums[i + 1]; - res[i] = n; - } - n = 1; - for i in 1..nums.len() { - n *= nums[i - 1]; - res[i] *= n; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_238() { - assert_eq!( - Solution::product_except_self(vec![1, 2, 3, 4]), - vec![24, 12, 8, 6] - ); - } -} diff --git a/src/solution/s0239_sliding_window_maximum.rs b/src/solution/s0239_sliding_window_maximum.rs deleted file mode 100644 index f7509cb9..00000000 --- a/src/solution/s0239_sliding_window_maximum.rs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * [239] Sliding Window Maximum - * - * Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. - * - * Example: - * - * - * Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3 - * Output: [3,3,5,5,6,7] - * Explanation: - * - * Window position Max - * --------------- ----- - * [1 3 -1] -3 5 3 6 7 3 - * 1 [3 -1 -3] 5 3 6 7 3 - * 1 3 [-1 -3 5] 3 6 7 5 - * 1 3 -1 [-3 5 3] 6 7 5 - * 1 3 -1 -3 [5 3 6] 7 6 - * 1 3 -1 -3 5 [3 6 7] 7 - * - * - * Note:
- * You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array. - * - * Follow up:
- * Could you solve it in linear time? - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/sliding-window-maximum/ -// discuss: https://leetcode.com/problems/sliding-window-maximum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::VecDeque; -impl Solution { - pub fn max_sliding_window(nums: Vec, k: i32) -> Vec { - let mut deq: VecDeque<(usize, i32)> = VecDeque::new(); - let mut res = Vec::new(); - for i in 0..nums.len() { - // maintain sliding window - if !deq.is_empty() && (*deq.front().unwrap()).0 as i32 <= (i as i32) - k { - deq.pop_front(); - let mut max = i32::min_value(); - let mut count = 0_usize; - for (j, &v) in deq.iter().enumerate() { - if v.1 >= max { - max = v.1; - count = j; - } - } - for _ in 0..count { - deq.pop_front(); - } - } - let num = nums[i]; - if !deq.is_empty() && (*deq.front().unwrap()).1 <= num { - while !deq.is_empty() { - deq.pop_front(); - } - } - deq.push_back((i, num)); - if i + 1 >= k as usize { - res.push((*deq.front().unwrap()).1); - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_239() { - assert_eq!( - Solution::max_sliding_window(vec![9, 10, 9, -7, -4, -8, 2, -6], 5), - vec![10, 10, 9, 2] - ); - assert_eq!( - Solution::max_sliding_window(vec![1, 3, 1, 2, 0, 5], 3), - vec![3, 3, 2, 5] - ); - assert_eq!(Solution::max_sliding_window(vec![7, 2, 4], 2), vec![7, 4]); - assert_eq!(Solution::max_sliding_window(vec![1, -1], 1), vec![1, -1]); - assert_eq!( - Solution::max_sliding_window(vec![1, 3, -1, -3, 5, 3, 6, 7], 3), - vec![3, 3, 5, 5, 6, 7] - ); - } -} diff --git a/src/solution/s0241_different_ways_to_add_parentheses.rs b/src/solution/s0241_different_ways_to_add_parentheses.rs deleted file mode 100644 index a76bfa6a..00000000 --- a/src/solution/s0241_different_ways_to_add_parentheses.rs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * [241] Different Ways to Add Parentheses - * - * Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *. - * - * Example 1: - * - * - * Input: "2-1-1" - * Output: [0, 2] - * Explanation: - * ((2-1)-1) = 0 - * (2-(1-1)) = 2 - * - * Example 2: - * - * - * Input: "2*3-4*5" - * Output: [-34, -14, -10, -10, 10] - * Explanation: - * (2*(3-(4*5))) = -34 - * ((2*3)-(4*5)) = -14 - * ((2*(3-4))*5) = -10 - * (2*((3-4)*5)) = -10 - * (((2*3)-4)*5) = 10 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/different-ways-to-add-parentheses/ -// discuss: https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn diff_ways_to_compute(input: String) -> Vec { - Solution::helper(&input) - } - - pub fn helper(input: &str) -> Vec { - if input.is_empty() { - return vec![]; - } - if let Ok(digit) = input.parse::() { - return vec![digit]; - } - let mut res: Vec = Vec::new(); - for (i, ch) in input.chars().enumerate() { - if ch == '+' || ch == '-' || ch == '*' { - let left = Solution::helper(&input[..i]); - let right = Solution::helper(&input[i + 1..]); - for &a in left.iter() { - for &b in right.iter() { - res.push(match ch { - '+' => a + b, - '-' => a - b, - '*' => a * b, - _ => unreachable!(), - }) - } - } - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_241() { - assert_eq!( - Solution::diff_ways_to_compute("2*3-4*5".to_owned()), - vec![-34, -10, -14, -10, 10] - ); - } -} diff --git a/src/solution/s0242_valid_anagram.rs b/src/solution/s0242_valid_anagram.rs deleted file mode 100644 index ba7a58ae..00000000 --- a/src/solution/s0242_valid_anagram.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [242] Valid Anagram - * - * Given two strings s and t , write a function to determine if t is an anagram of s. - * - * Example 1: - * - * - * Input: s = "anagram", t = "nagaram" - * Output: true - * - * - * Example 2: - * - * - * Input: s = "rat", t = "car" - * Output: false - * - * - * Note:
- * You may assume the string contains only lowercase alphabets. - * - * Follow up:
- * What if the inputs contain unicode characters? How would you adapt your solution to such case? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/valid-anagram/ -// discuss: https://leetcode.com/problems/valid-anagram/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_anagram(s: String, t: String) -> bool { - Solution::hit(s) == Solution::hit(t) - } - - fn hit(s: String) -> Vec { - let mut hit = vec![0; 27]; - for ch in s.chars() { - hit[(ch as u8 - 'a' as u8) as usize] += 1; - } - hit - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_242() { - assert_eq!( - Solution::is_anagram("anagram".to_owned(), "nagaram".to_owned()), - true - ); - } -} diff --git a/src/solution/s0257_binary_tree_paths.rs b/src/solution/s0257_binary_tree_paths.rs deleted file mode 100644 index 6c7833e2..00000000 --- a/src/solution/s0257_binary_tree_paths.rs +++ /dev/null @@ -1,85 +0,0 @@ -/** - * [257] Binary Tree Paths - * - * Given a binary tree, return all root-to-leaf paths. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * - * Input: - * - * 1 - * / \ - * 2 3 - * \ - * 5 - * - * Output: ["1->2->5", "1->3"] - * - * Explanation: All root-to-leaf paths are: 1->2->5, 1->3 - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-paths/ -// discuss: https://leetcode.com/problems/binary-tree-paths/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn binary_tree_paths(root: Option>>) -> Vec { - let mut res = Vec::new(); - Solution::helper(root, "".to_owned(), &mut res); - res - } - - fn helper(root: Option>>, path: String, res: &mut Vec) { - if let Some(inner) = root { - if inner.borrow().left.is_none() && inner.borrow().right.is_none() { - res.push(format!("{}{}", path, inner.borrow().val)); - } else { - let path = format!("{}{}->", path, inner.borrow().val); - Solution::helper(inner.borrow().left.clone(), path.clone(), res); - Solution::helper(inner.borrow().right.clone(), path, res); - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_257() { - assert_eq!( - Solution::binary_tree_paths(tree![1, 2, 3, null, 5]), - vec_string!["1->2->5", "1->3"] - ); - } -} diff --git a/src/solution/s0258_add_digits.rs b/src/solution/s0258_add_digits.rs deleted file mode 100644 index 2248be1d..00000000 --- a/src/solution/s0258_add_digits.rs +++ /dev/null @@ -1,41 +0,0 @@ -/** - * [258] Add Digits - * - * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. - * - * Example: - * - * - * Input: 38 - * Output: 2 - * Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. - * Since 2 has only one digit, return it. - * - * - * Follow up:
- * Could you do it without any loop/recursion in O(1) runtime? - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/add-digits/ -// discuss: https://leetcode.com/problems/add-digits/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn add_digits(num: i32) -> i32 { - 1 + ((num - 1) % 9) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_258() { - assert_eq!(Solution::add_digits(1234), 1); - } -} diff --git a/src/solution/s0260_single_number_iii.rs b/src/solution/s0260_single_number_iii.rs deleted file mode 100644 index 09d7a920..00000000 --- a/src/solution/s0260_single_number_iii.rs +++ /dev/null @@ -1,57 +0,0 @@ -/** - * [260] Single Number III - * - * Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. - * - * Example: - * - * - * Input: [1,2,1,3,2,5] - * Output: [3,5] - * - * Note: - * - *
    - * The order of the result is not important. So in the above example, [5, 3] is also correct. - * Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/single-number-iii/ -// discuss: https://leetcode.com/problems/single-number-iii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn single_number(nums: Vec) -> Vec { - let mut res = 0; - for &num in nums.iter() { - res = res ^ num; - } - let right_most_set_bit = res & !(res - 1); - let mut bit_set = 0; - let mut bit_unset = 0; - for &num in nums.iter() { - if num & right_most_set_bit == 0 { - bit_unset = bit_unset ^ num; - } else { - bit_set = bit_set ^ num; - } - } - return vec![bit_set, bit_unset]; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_260() { - assert_eq!(Solution::single_number(vec![1, 2, 1, 2, 3, 4]), vec![3, 4]); - assert_eq!(Solution::single_number(vec![1, 2, 1, 3, 2, 5]), vec![3, 5]); - } -} diff --git a/src/solution/s0263_ugly_number.rs b/src/solution/s0263_ugly_number.rs deleted file mode 100644 index 9ef3bf57..00000000 --- a/src/solution/s0263_ugly_number.rs +++ /dev/null @@ -1,73 +0,0 @@ -/** - * [263] Ugly Number - * - * Write a program to check whether a given number is an ugly number. - * - * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. - * - * Example 1: - * - * - * Input: 6 - * Output: true - * Explanation: 6 = 2 × 3 - * - * Example 2: - * - * - * Input: 8 - * Output: true - * Explanation: 8 = 2 × 2 × 2 - * - * - * Example 3: - * - * - * Input: 14 - * Output: false - * Explanation: 14 is not ugly since it includes another prime factor 7. - * - * - * Note: - * - *
    - * 1 is typically treated as an ugly number. - * Input is within the 32-bit signed integer range: [-2^31, 2^31 - 1]. - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/ugly-number/ -// discuss: https://leetcode.com/problems/ugly-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_ugly(num: i32) -> bool { - if num <= 0 { - false - } else if num == 1 { - true - } else if num % 5 == 0 { - Solution::is_ugly(num / 5) - } else if num % 3 == 0 { - Solution::is_ugly(num / 3) - } else if num % 2 == 0 { - Solution::is_ugly(num / 2) - } else { - false - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_263() { - assert_eq!(Solution::is_ugly(25), true); - } -} diff --git a/src/solution/s0264_ugly_number_ii.rs b/src/solution/s0264_ugly_number_ii.rs deleted file mode 100644 index 8dda4f01..00000000 --- a/src/solution/s0264_ugly_number_ii.rs +++ /dev/null @@ -1,66 +0,0 @@ -/** - * [264] Ugly Number II - * - * Write a program to find the n-th ugly number. - * - * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. - * - * Example: - * - * - * Input: n = 10 - * Output: 12 - * Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. - * - * Note: - * - *
    - * 1 is typically treated as an ugly number. - * n does not exceed 1690. - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/ugly-number-ii/ -// discuss: https://leetcode.com/problems/ugly-number-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn nth_ugly_number(n: i32) -> i32 { - let mut base2 = 0; - let mut base3 = 0; - let mut base5 = 0; - let mut ugly = vec![1; 1]; - for _ in 1..n { - let next2 = ugly[base2] * 2; - let next3 = ugly[base3] * 3; - let next5 = ugly[base5] * 5; - let next = i32::min(next2, i32::min(next3, next5)); - if next2 == next { - base2 += 1 - } - if next3 == next { - base3 += 1 - } - if next5 == next { - base5 += 1 - } - ugly.push(next) - } - *ugly.last().unwrap() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_264() { - assert_eq!(Solution::nth_ugly_number(1), 1); - assert_eq!(Solution::nth_ugly_number(10), 12); - } -} diff --git a/src/solution/s0268_missing_number.rs b/src/solution/s0268_missing_number.rs deleted file mode 100644 index 63291ee0..00000000 --- a/src/solution/s0268_missing_number.rs +++ /dev/null @@ -1,46 +0,0 @@ -/** - * [268] Missing Number - * - * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. - * - * Example 1: - * - * - * Input: [3,0,1] - * Output: 2 - * - * - * Example 2: - * - * - * Input: [9,6,4,2,3,5,7,0,1] - * Output: 8 - * - * - * Note:
- * Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/missing-number/ -// discuss: https://leetcode.com/problems/missing-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn missing_number(nums: Vec) -> i32 { - ((nums.len() + 1) * nums.len()) as i32 / 2 - nums.into_iter().fold(0, |acc, v| acc + v) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_268() { - assert_eq!(Solution::missing_number(vec![3, 0, 1]), 2); - } -} diff --git a/src/solution/s0273_integer_to_english_words.rs b/src/solution/s0273_integer_to_english_words.rs deleted file mode 100644 index 123a1f9d..00000000 --- a/src/solution/s0273_integer_to_english_words.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [273] Integer to English Words - * - * Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1. - * - * Example 1: - * - * - * Input: 123 - * Output: "One Hundred Twenty Three" - * - * - * Example 2: - * - * - * Input: 12345 - * Output: "Twelve Thousand Three Hundred Forty Five" - * - * Example 3: - * - * - * Input: 1234567 - * Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" - * - * - * Example 4: - * - * - * Input: 1234567891 - * Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One" - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/integer-to-english-words/ -// discuss: https://leetcode.com/problems/integer-to-english-words/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// static digits: Vec<&str> = vec!["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]; -// static xteens: Vec<&str> = vec!["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventenn", "Eighteen", "Nineteen"]; -// static xtys: Vec<&str> = vec!["Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]; -// static hunderd: &str = "Hunderd"; -// static thousands: Vec<&str> = vec!["Thousand", "Million", "Billion"]; - -impl Solution { - pub fn number_to_words(num: i32) -> String { - "".to_owned() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_273() {} -} diff --git a/src/solution/s0274_h_index.rs b/src/solution/s0274_h_index.rs deleted file mode 100644 index b36f65a3..00000000 --- a/src/solution/s0274_h_index.rs +++ /dev/null @@ -1,53 +0,0 @@ -/** - * [274] H-Index - * - * Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. - * - * According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N - h papers have no more than h citations each." - * - * Example: - * - * - * Input: citations = [3,0,6,1,5] - * Output: 3 - * Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had - * received 3, 0, 6, 1, 5 citations respectively. - * Since the researcher has 3 papers with at least 3 citations each and the remaining - * two with no more than 3 citations each, her h-index is 3. - * - * Note: If there are several possible values for h, the maximum one is taken as the h-index. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/h-index/ -// discuss: https://leetcode.com/problems/h-index/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn h_index(mut citations: Vec) -> i32 { - citations.sort_unstable(); - let mut hidx = 0; - for &v in citations.iter().rev() { - if v >= hidx + 1 { - hidx += 1; - } else { - break; - } - } - hidx - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_274() { - assert_eq!(Solution::h_index(vec![3, 0, 6, 1, 5]), 3); - } -} diff --git a/src/solution/s0275_h_index_ii.rs b/src/solution/s0275_h_index_ii.rs deleted file mode 100644 index 027ad02a..00000000 --- a/src/solution/s0275_h_index_ii.rs +++ /dev/null @@ -1,74 +0,0 @@ -/** - * [275] H-Index II - * - * Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. - * - * According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N - h papers have no more than h citations each." - * - * Example: - * - * - * Input: citations = [0,1,3,5,6] - * Output: 3 - * Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had - * received 0, 1, 3, 5, 6 citations respectively. - * Since the researcher has 3 papers with at least 3 citations each and the remaining - * two with no more than 3 citations each, her h-index is 3. - * - * Note: - * - * If there are several possible values for h, the maximum one is taken as the h-index. - * - * Follow up: - * - * - * This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order. - * Could you solve it in logarithmic time complexity? - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/h-index-ii/ -// discuss: https://leetcode.com/problems/h-index-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn h_index(citations: Vec) -> i32 { - if citations.is_empty() { - return 0; - } - let len = citations.len(); - let (mut low, mut high) = (0_usize, len - 1); - while low <= high { - let mid = low + (high - low) / 2; - if citations[mid] >= (len - mid) as i32 { - if mid == 0 { - break; - } - high = mid - 1; - } else { - low = mid + 1; - } - } - (len - low) as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_275() { - assert_eq!(Solution::h_index(vec![]), 0); - assert_eq!(Solution::h_index(vec![0]), 0); - assert_eq!(Solution::h_index(vec![11, 15]), 2); - assert_eq!(Solution::h_index(vec![1]), 1); - assert_eq!(Solution::h_index(vec![0, 1, 3, 5, 6]), 3); - assert_eq!(Solution::h_index(vec![0, 4, 4, 5, 6]), 4); - } -} diff --git a/src/solution/s0279_perfect_squares.rs b/src/solution/s0279_perfect_squares.rs deleted file mode 100644 index fe5f0a01..00000000 --- a/src/solution/s0279_perfect_squares.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [279] Perfect Squares - * - * Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. - * - * Example 1: - * - * - * Input: n = 12 - * Output: 3 - * Explanation: 12 = 4 + 4 + 4. - * - * Example 2: - * - * - * Input: n = 13 - * Output: 2 - * Explanation: 13 = 4 + 9. - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/perfect-squares/ -// discuss: https://leetcode.com/problems/perfect-squares/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// BFS -use std::collections::VecDeque; -impl Solution { - pub fn num_squares(n: i32) -> i32 { - if n < 1 { - return 0; - } - let mut deq = VecDeque::new(); - deq.push_back((1, n)); - while let Some((level, num)) = deq.pop_front() { - let mut base = 1; - while base * base <= num { - if base * base == num { - return level; - } - deq.push_back((level + 1, num - base * base)); - base += 1; - } - } - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_279() { - assert_eq!(Solution::num_squares(13), 2); - assert_eq!(Solution::num_squares(12), 3); - } -} diff --git a/src/solution/s0282_expression_add_operators.rs b/src/solution/s0282_expression_add_operators.rs deleted file mode 100644 index 1c41367b..00000000 --- a/src/solution/s0282_expression_add_operators.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [282] Expression Add Operators - * - * Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. - * - * Example 1: - * - * - * Input: num = "123", target = 6 - * Output: ["1+2+3", "1*2*3"] - * - * - * Example 2: - * - * - * Input: num = "232", target = 8 - * Output: ["2*3+2", "2+3*2"] - * - * Example 3: - * - * - * Input: num = "105", target = 5 - * Output: ["1*0+5","10-5"] - * - * Example 4: - * - * - * Input: num = "00", target = 0 - * Output: ["0+0", "0-0", "0*0"] - * - * - * Example 5: - * - * - * Input: num = "3456237490", target = 9191 - * Output: [] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/expression-add-operators/ -// discuss: https://leetcode.com/problems/expression-add-operators/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn add_operators(num: String, target: i32) -> Vec { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_282() {} -} diff --git a/src/solution/s0283_move_zeroes.rs b/src/solution/s0283_move_zeroes.rs deleted file mode 100644 index 6581bcaf..00000000 --- a/src/solution/s0283_move_zeroes.rs +++ /dev/null @@ -1,50 +0,0 @@ -/** - * [283] Move Zeroes - * - * Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. - * - * Example: - * - * - * Input: [0,1,0,3,12] - * Output: [1,3,12,0,0] - * - * Note: - * - *
    - * You must do this in-place without making a copy of the array. - * Minimize the total number of operations. - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/move-zeroes/ -// discuss: https://leetcode.com/problems/move-zeroes/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn move_zeroes(nums: &mut Vec) { - let mut last_none_zero = 0_usize; - for i in 0..nums.len() { - if nums[i] != 0 { - nums.swap(last_none_zero, i); - last_none_zero += 1; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_283() { - let mut vec = vec![0, 1, 0, 3, 12]; - Solution::move_zeroes(&mut vec); - assert_eq!(vec, vec![1, 3, 12, 0, 0]); - } -} diff --git a/src/solution/s0287_find_the_duplicate_number.rs b/src/solution/s0287_find_the_duplicate_number.rs deleted file mode 100644 index cea65001..00000000 --- a/src/solution/s0287_find_the_duplicate_number.rs +++ /dev/null @@ -1,74 +0,0 @@ -/** - * [287] Find the Duplicate Number - * - * Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. - * - * Example 1: - * - * - * Input: [1,3,4,2,2] - * Output: 2 - * - * - * Example 2: - * - * - * Input: [3,1,3,4,2] - * Output: 3 - * - * Note: - * - *
    - * You must not modify the array (assume the array is read only). - * You must use only constant, O(1) extra space. - * Your runtime complexity should be less than O(n^2). - * There is only one duplicate number in the array, but it could be repeated more than once. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-the-duplicate-number/ -// discuss: https://leetcode.com/problems/find-the-duplicate-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// 假如把值看做 next node 的下标, 那么: -// 从 0 出发不会回到 0 -// 一定有环, 因为 1-n 全部落在下标范围 [0, n] 中 -// 从 0 遍历经过的环中, 一定存在重复数字 x, 且 x 就是入环点的下标: -// 1.从 0 走到入环点, 入环点的前驱值为 x; 2.入环点在环上的前驱值也是 x -// 由于我们不可能回到 0, 因此这两个节点下标不同, x 即为要找的重复数字 -impl Solution { - pub fn find_duplicate(nums: Vec) -> i32 { - let mut slow: usize = nums[0] as usize; - let mut fast: usize = nums[nums[0] as usize] as usize; - // util slow meet fast - while slow != fast { - slow = nums[slow] as usize; - fast = nums[nums[fast] as usize] as usize; - } - - fast = 0_usize; - while slow != fast { - fast = nums[fast] as usize; - slow = nums[slow] as usize; - } - slow as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_287() { - assert_eq!(Solution::find_duplicate(vec![1, 3, 4, 2, 2]), 2); - assert_eq!(Solution::find_duplicate(vec![3, 1, 3, 4, 2]), 3); - assert_eq!(Solution::find_duplicate(vec![1, 2, 3, 4, 5, 5]), 5); - assert_eq!(Solution::find_duplicate(vec![5, 1, 2, 3, 4, 5]), 5); - } -} diff --git a/src/solution/s0289_game_of_life.rs b/src/solution/s0289_game_of_life.rs deleted file mode 100644 index 53d34623..00000000 --- a/src/solution/s0289_game_of_life.rs +++ /dev/null @@ -1,118 +0,0 @@ -/** - * [289] Game of Life - * - * According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." - * - * Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): - * - *
    - * Any live cell with fewer than two live neighbors dies, as if caused by under-population. - * Any live cell with two or three live neighbors lives on to the next generation. - * Any live cell with more than three live neighbors dies, as if by over-population.. - * Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. - *
- * - * Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. - * - * Example: - * - * - * Input: - * [ - * [0,1,0], - * [0,0,1], - * [1,1,1], - * [0,0,0] - * ] - * Output: - * [ - * [0,0,0], - * [1,0,1], - * [0,1,1], - * [0,1,0] - * ] - * - * - * Follow up: - * - *
    - * Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells. - * In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/game-of-life/ -// discuss: https://leetcode.com/problems/game-of-life/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// in-place: 1: live->live, 0: die->die, 2: die->live, 3: live->die -impl Solution { - pub fn game_of_life(board: &mut Vec>) { - let (height, width) = (board.len(), board[0].len()); - let neighbors = vec![ - (-1, -1), - (-1, 0), - (-1, 1), - (0, -1), - (0, 1), - (1, -1), - (1, 0), - (1, 1), - ]; - for i in 0..height { - for j in 0..width { - let mut live = 0; - for offset in neighbors.iter() { - if (offset.0 < 0 && i == 0) - || (offset.0 > 0 && i == height - 1) - || (offset.1 < 0 && j == 0) - || (offset.1 > 0 && j == width - 1) - { - continue; - } - let v = board[(i as i32 + offset.0) as usize][(j as i32 + offset.1) as usize]; - if v == 1 || v == 3 { - live += 1; - } - } - if board[i][j] == 1 && (live < 2 || live > 3) { - // go die - board[i][j] = 3; - } else if board[i][j] == 0 && live == 3 { - // go live - board[i][j] = 2; - } - } - } - - for i in 0..height { - for j in 0..width { - if board[i][j] == 2 { - board[i][j] = 1; - } else if board[i][j] == 3 { - board[i][j] = 0; - } - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_289() { - let mut test = vec![vec![0, 1, 0], vec![0, 0, 1], vec![1, 1, 1], vec![0, 0, 0]]; - Solution::game_of_life(&mut test); - assert_eq!( - test, - vec![vec![0, 0, 0], vec![1, 0, 1], vec![0, 1, 1], vec![0, 1, 0],] - ); - } -} diff --git a/src/solution/s0290_word_pattern.rs b/src/solution/s0290_word_pattern.rs deleted file mode 100644 index c758f352..00000000 --- a/src/solution/s0290_word_pattern.rs +++ /dev/null @@ -1,86 +0,0 @@ -/** - * [290] Word Pattern - * - * Given a pattern and a string str, find if str follows the same pattern. - * - * Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. - * - * Example 1: - * - * - * Input: pattern = "abba", str = "dog cat cat dog" - * Output: true - * - * Example 2: - * - * - * Input:pattern = "abba", str = "dog cat cat fish" - * Output: false - * - * Example 3: - * - * - * Input: pattern = "aaaa", str = "dog cat cat dog" - * Output: false - * - * Example 4: - * - * - * Input: pattern = "abba", str = "dog dog dog dog" - * Output: false - * - * Notes:
- * You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-pattern/ -// discuss: https://leetcode.com/problems/word-pattern/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashMap; -impl Solution { - pub fn word_pattern(pattern: String, s: String) -> bool { - let mut p2s = HashMap::new(); - let mut s2p = HashMap::new(); - let mut s_iter = s.split(" "); - let mut p_iter = pattern.chars(); - loop { - match (s_iter.next(), p_iter.next()) { - (Some(sub), Some(ch)) => { - if *p2s.entry(ch).or_insert(sub) != sub || *s2p.entry(sub).or_insert(ch) != ch { - return false; - } - } - (None, None) => break, - _ => return false, - } - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_290() { - assert_eq!( - Solution::word_pattern("abba".to_owned(), "dog cat cat dog".to_owned()), - true - ); - assert_eq!( - Solution::word_pattern("aaaa".to_owned(), "dog cat cat dog".to_owned()), - false - ); - assert_eq!( - Solution::word_pattern("abba".to_owned(), "dog cat cat fish".to_owned()), - false - ); - } -} diff --git a/src/solution/s0292_nim_game.rs b/src/solution/s0292_nim_game.rs deleted file mode 100644 index 4c46505c..00000000 --- a/src/solution/s0292_nim_game.rs +++ /dev/null @@ -1,40 +0,0 @@ -/** - * [292] Nim Game - * - * You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. - * - * Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. - * - * Example: - * - * - * Input: 4 - * Output: false - * Explanation: If there are 4 stones in the heap, then you will never win the game; - * No matter 1, 2, or 3 stones you remove, the last stone will always be - * removed by your friend. - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/nim-game/ -// discuss: https://leetcode.com/problems/nim-game/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn can_win_nim(n: i32) -> bool { - n % 4 != 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_292() { - assert_eq!(Solution::can_win_nim(4), false); - } -} diff --git a/src/solution/s0295_find_median_from_data_stream.rs b/src/solution/s0295_find_median_from_data_stream.rs deleted file mode 100644 index 02dc5331..00000000 --- a/src/solution/s0295_find_median_from_data_stream.rs +++ /dev/null @@ -1,136 +0,0 @@ -/** - * [295] Find Median from Data Stream - * - * Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. - * For example, - * - * [2,3,4], the median is 3 - * - * [2,3], the median is (2 + 3) / 2 = 2.5 - * - * Design a data structure that supports the following two operations: - * - * - * void addNum(int num) - Add a integer number from the data stream to the data structure. - * double findMedian() - Return the median of all elements so far. - * - * - * - * - * Example: - * - * - * addNum(1) - * addNum(2) - * findMedian() -> 1.5 - * addNum(3) - * findMedian() -> 2 - * - * - * - * - * Follow up: - * - *
    - * If all integer numbers from the stream are between 0 and 100, how would you optimize it? - * If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it? - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-median-from-data-stream/ -// discuss: https://leetcode.com/problems/find-median-from-data-stream/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cmp::Ordering; -use std::collections::BinaryHeap; -#[derive(Eq, PartialEq)] -struct Invert { - value: i32, -} - -impl Ord for Invert { - fn cmp(&self, other: &Invert) -> Ordering { - other.value.cmp(&self.value) - } -} - -impl PartialOrd for Invert { - fn partial_cmp(&self, other: &Invert) -> Option { - Some(self.cmp(other)) - } -} - -struct MedianFinder { - head: BinaryHeap, - tail: BinaryHeap, - count: i32, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl MedianFinder { - /** initialize your data structure here. */ - fn new() -> Self { - MedianFinder { - head: BinaryHeap::new(), - tail: BinaryHeap::new(), - count: 0, - } - } - - fn add_num(&mut self, num: i32) { - self.count += 1; - if self.head.is_empty() || num > self.head.peek().unwrap().value { - self.head.push(Invert { value: num }); - } else { - self.tail.push(num); - } - // balance - if self.head.len() > self.tail.len() + 1 { - self.tail.push(self.head.pop().unwrap().value); - } else if self.head.len() + 1 < self.tail.len() { - self.head.push(Invert { - value: self.tail.pop().unwrap(), - }); - } - } - - fn find_median(&self) -> f64 { - if self.head.len() > self.tail.len() { - self.head.peek().unwrap().value as f64 - } else if self.head.len() < self.tail.len() { - *self.tail.peek().unwrap() as f64 - } else { - (self.head.peek().unwrap().value as f64 + *self.tail.peek().unwrap() as f64) / 2.0 - } - } -} - -/** - * Your MedianFinder object will be instantiated and called as such: - * let obj = MedianFinder::new(); - * obj.add_num(num); - * let ret_2: f64 = obj.find_median(); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_295() { - let mut obj = MedianFinder::new(); - obj.add_num(1); - obj.add_num(2); - assert_eq!(obj.find_median(), 1.5); - obj.add_num(3); - assert_eq!(obj.find_median(), 2_f64); - } -} diff --git a/src/solution/s0299_bulls_and_cows.rs b/src/solution/s0299_bulls_and_cows.rs deleted file mode 100644 index 08525c71..00000000 --- a/src/solution/s0299_bulls_and_cows.rs +++ /dev/null @@ -1,80 +0,0 @@ -/** - * [299] Bulls and Cows - * - * You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number. - * - * Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. - * - * Please note that both secret number and friend's guess may contain duplicate digits. - * - * Example 1: - * - * - * Input: secret = "1807", guess = "7810" - * - * Output: "1A3B" - * - * Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7. - * - * Example 2: - * - * - * Input: secret = "1123", guess = "0111" - * - * Output: "1A1B" - * - * Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow. - * - * Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal. - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/bulls-and-cows/ -// discuss: https://leetcode.com/problems/bulls-and-cows/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn get_hint(secret: String, guess: String) -> String { - let mut bulls = 0; - let mut cows = 0; - let mut s_iter = secret.chars(); - let mut g_iter = guess.chars(); - let mut bucket = vec![0; 10]; - let mut non_match = vec![]; - while let (Some(s), Some(g)) = (s_iter.next(), g_iter.next()) { - if s == g { - bulls += 1; - } else { - bucket[s.to_digit(10).unwrap() as usize] += 1; - non_match.push(g.to_digit(10).unwrap() as usize); - } - } - for &idx in non_match.iter() { - if bucket[idx] > 0 { - cows += 1; - bucket[idx] -= 1; - } - } - format!("{}A{}B", bulls, cows) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_299() { - assert_eq!( - Solution::get_hint("1807".to_owned(), "7810".to_owned()), - "1A3B".to_owned() - ); - assert_eq!( - Solution::get_hint("1123".to_owned(), "0111".to_owned()), - "1A1B".to_owned() - ); - } -} diff --git a/src/solution/s0300_longest_increasing_subsequence.rs b/src/solution/s0300_longest_increasing_subsequence.rs deleted file mode 100644 index c0b7eb27..00000000 --- a/src/solution/s0300_longest_increasing_subsequence.rs +++ /dev/null @@ -1,57 +0,0 @@ -/** - * [300] Longest Increasing Subsequence - * - * Given an unsorted array of integers, find the length of longest increasing subsequence. - * - * Example: - * - * - * Input: [10,9,2,5,3,7,101,18] - * Output: 4 - * Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. - * - * Note: - * - * - * There may be more than one LIS combination, it is only necessary for you to return the length. - * Your algorithm should run in O(n^2) complexity. - * - * - * Follow up: Could you improve it to O(n log n) time complexity? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-increasing-subsequence/ -// discuss: https://leetcode.com/problems/longest-increasing-subsequence/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -// N^2, DP: L[i] = max(1 + L[j]) for j in [0, i) and nums[j] < nums[i] -// N * logN, kick out strategy, maintain an increasing array, new elements kick out a formal one larger than it, if the new element is largest, expand the array -impl Solution { - pub fn length_of_lis(nums: Vec) -> i32 { - let mut incr = Vec::new(); - for &num in nums.iter() { - if let Err(idx) = incr.binary_search(&num) { - if idx >= incr.len() { - incr.push(num); - } else { - incr[idx] = num; - } - } - } - incr.len() as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_300() { - assert_eq!(Solution::length_of_lis(vec![10, 9, 2, 5, 3, 7, 101, 18]), 4); - } -} diff --git a/src/solution/s0301_remove_invalid_parentheses.rs b/src/solution/s0301_remove_invalid_parentheses.rs deleted file mode 100644 index 2cec757c..00000000 --- a/src/solution/s0301_remove_invalid_parentheses.rs +++ /dev/null @@ -1,131 +0,0 @@ -/** - * [301] Remove Invalid Parentheses - * - * Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. - * - * Note: The input string may contain letters other than the parentheses ( and ). - * - * Example 1: - * - * - * Input: "()())()" - * Output: ["()()()", "(())()"] - * - * - * Example 2: - * - * - * Input: "(a)())()" - * Output: ["(a)()()", "(a())()"] - * - * - * Example 3: - * - * - * Input: ")(" - * Output: [""] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/remove-invalid-parentheses/ -// discuss: https://leetcode.com/problems/remove-invalid-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// 1. Calculate the number of misplaced left parenthese and right parenthese -// 2. DFS the string to find the all possible removing policy -use std::collections::HashSet; -impl Solution { - pub fn remove_invalid_parentheses(s: String) -> Vec { - let (mut left, mut right) = (0, 0); - let mut chs: Vec = s.chars().collect(); - for &c in chs.iter() { - if c == '(' { - left += 1; - } else if c == ')' { - if left > 0 { - left -= 1; - } else { - right += 1; - } - } - } - - // Now, the number of left and right parentheses are 'left' and 'right' - let mut res: HashSet = HashSet::new(); - let mut seed: Vec = Vec::new(); - Solution::helper(&chs, 0, 0, left, right, &mut seed, &mut res); - res.into_iter().collect() - } - - fn helper( - chs: &Vec, - idx: usize, - left: i32, - l_remain: i32, - r_remain: i32, - exp: &mut Vec, - res: &mut HashSet, - ) { - if idx >= chs.len() { - if left == 0 { - res.insert(exp.iter().collect()); - } - return; - } - if chs[idx] == '(' { - if l_remain > 0 { - Solution::helper( - chs, - idx + 1, - left, - l_remain - 1, - r_remain, - &mut exp.clone(), - res, - ); - } - exp.push('('); - Solution::helper(chs, idx + 1, left + 1, l_remain, r_remain, exp, res); - } else if chs[idx] == ')' { - if r_remain > 0 { - Solution::helper( - chs, - idx + 1, - left, - l_remain, - r_remain - 1, - &mut exp.clone(), - res, - ); - } - if left > 0 { - exp.push(')'); - Solution::helper(chs, idx + 1, left - 1, l_remain, r_remain, exp, res); - } - } else { - exp.push(chs[idx]); - Solution::helper(chs, idx + 1, left, l_remain, r_remain, exp, res); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_301() { - assert_eq!( - Solution::remove_invalid_parentheses("()())()".to_owned()), - vec_string!["(())()", "()()()"] - ); - assert_eq!( - Solution::remove_invalid_parentheses("(a)())()".to_owned()), - vec_string!["(a)()()", "(a())()"] - ); - } -} diff --git a/src/solution/s0303_range_sum_query_immutable.rs b/src/solution/s0303_range_sum_query_immutable.rs deleted file mode 100644 index c56f8ae9..00000000 --- a/src/solution/s0303_range_sum_query_immutable.rs +++ /dev/null @@ -1,74 +0,0 @@ -/** - * [303] Range Sum Query - Immutable - * - * Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. - * - * Example:
- * - * Given nums = [-2, 0, 3, -5, 2, -1] - * - * sumRange(0, 2) -> 1 - * sumRange(2, 5) -> -1 - * sumRange(0, 5) -> -3 - * - * - * - * Note:
- *
    - * You may assume that the array does not change. - * There are many calls to sumRange function. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/range-sum-query-immutable/ -// discuss: https://leetcode.com/problems/range-sum-query-immutable/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct NumArray { - nums: Vec, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl NumArray { - fn new(nums: Vec) -> Self { - let mut res = 0; - let mut vec = Vec::with_capacity(nums.len()); - for &num in nums.iter() { - res += num; - vec.push(res); - } - NumArray { nums: vec } - } - - fn sum_range(&self, i: i32, j: i32) -> i32 { - let (i, j) = (i as usize, j as usize); - self.nums[j] - if i > 0 { self.nums[i - 1] } else { 0 } - } -} - -/** - * Your NumArray object will be instantiated and called as such: - * let obj = NumArray::new(nums); - * let ret_1: i32 = obj.sum_range(i, j); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_303() { - let mut nums = NumArray::new(vec![-2, 0, 3, -5, 2, -1]); - assert_eq!(nums.sum_range(0, 2), 1); - assert_eq!(nums.sum_range(2, 5), -1); - assert_eq!(nums.sum_range(0, 5), -3); - } -} diff --git a/src/solution/s0304_range_sum_query_2d_immutable.rs b/src/solution/s0304_range_sum_query_2d_immutable.rs deleted file mode 100644 index 42a0f41f..00000000 --- a/src/solution/s0304_range_sum_query_2d_immutable.rs +++ /dev/null @@ -1,124 +0,0 @@ -/** - * [304] Range Sum Query 2D - Immutable - * - * Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). - * - * - * Range Sum Query 2D
- * The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8. - * - * - * Example:
- * - * Given matrix = [ - * [3, 0, 1, 4, 2], - * [5, 6, 3, 2, 1], - * [1, 2, 0, 1, 5], - * [4, 1, 0, 1, 7], - * [1, 0, 3, 0, 5] - * ] - * - * sumRegion(2, 1, 4, 3) -> 8 - * sumRegion(1, 1, 2, 2) -> 11 - * sumRegion(1, 2, 2, 4) -> 12 - * - * - * - * Note:
- *
    - * You may assume that the matrix does not change. - * There are many calls to sumRegion function. - * You may assume that row1 ≤ row2 and col1 ≤ col2. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/range-sum-query-2d-immutable/ -// discuss: https://leetcode.com/problems/range-sum-query-2d-immutable/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct NumMatrix { - cache: Vec>, -} - -/** region[2, 2, 3, 4] = - * x x \ \ \ . square[3,4] - square[1,4] - square[3,1] + square[1,1] - * x x \ \ \ . - * / / o o o . - * / / o o o . - * . . . . . . - * . . . . . . - */ -impl NumMatrix { - fn new(matrix: Vec>) -> Self { - if matrix.is_empty() || matrix[0].is_empty() { - return NumMatrix { - cache: vec![vec![]], - }; - } - let (x_max, y_max) = (matrix.len(), matrix[0].len()); - let mut cache = vec![vec![0; y_max]; x_max]; - for x in 0..x_max { - for y in 0..y_max { - cache[x][y] = matrix[x][y] - + if y > 0 { cache[x][y - 1] } else { 0 } - + if x > 0 { cache[x - 1][y] } else { 0 } - - if x > 0 && y > 0 { - cache[x - 1][y - 1] - } else { - 0 - } - } - } - NumMatrix { cache: cache } - } - - fn sum_region(&self, row1: i32, col1: i32, row2: i32, col2: i32) -> i32 { - let (row1, col1, row2, col2) = (row1 as usize, col1 as usize, row2 as usize, col2 as usize); - self.cache[row2][col2] - - if row1 > 0 { - self.cache[row1 - 1][col2] - } else { - 0 - } - - if col1 > 0 { - self.cache[row2][col1 - 1] - } else { - 0 - } - + if row1 > 0 && col1 > 0 { - self.cache[row1 - 1][col1 - 1] - } else { - 0 - } - } -} - -/** - * Your NumMatrix object will be instantiated and called as such: - * let obj = NumMatrix::new(matrix); - * let ret_1: i32 = obj.sum_region(row1, col1, row2, col2); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_304() { - let matrix = NumMatrix::new(vec![ - vec![3, 0, 1, 4, 2], - vec![5, 6, 3, 2, 1], - vec![1, 2, 0, 1, 5], - vec![4, 1, 0, 1, 7], - vec![1, 0, 3, 0, 5], - ]); - assert_eq!(matrix.sum_region(1, 1, 2, 2), 11); - assert_eq!(matrix.sum_region(2, 1, 4, 3), 8); - assert_eq!(matrix.sum_region(1, 2, 2, 4), 12); - } -} diff --git a/src/solution/s0306_additive_number.rs b/src/solution/s0306_additive_number.rs deleted file mode 100644 index 38f6c0b2..00000000 --- a/src/solution/s0306_additive_number.rs +++ /dev/null @@ -1,113 +0,0 @@ -/** - * [306] Additive Number - * - * Additive number is a string whose digits can form additive sequence. - * - * A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. - * - * Given a string containing only digits '0'-'9', write a function to determine if it's an additive number. - * - * Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. - * - * Example 1: - * - * - * Input: "112358" - * Output: true - * Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. - * 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 - * - * - * Example 2: - * - * - * Input: "199100199" - * Output: true - * Explanation: The additive sequence is: 1, 99, 100, 199. - * 1 + 99 = 100, 99 + 100 = 199 - * - * Follow up:
- * How would you handle overflow for very large input integers? - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/additive-number/ -// discuss: https://leetcode.com/problems/additive-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// first_cut second_cut third_cut -// V V V -// 1 99 100 199 -impl Solution { - pub fn is_additive_number(num: String) -> bool { - let mut chs: Vec = num.chars().map(|c| c.to_digit(10).unwrap()).collect(); - let mut num1 = 0; - let len = chs.len(); - // first cut - for i in 0..(len / 2 + 1) { - num1 = num1 * 10 + chs[i]; - if Solution::second_cut(i + 1, len, num1, &chs) { - return true; - } - if num1 == 0 { - break; - } - } - false - } - - fn second_cut(from: usize, len: usize, num1: u32, chs: &Vec) -> bool { - let mut num2 = 0; - for i in from..len { - num2 = num2 * 10 + chs[i]; - if Solution::third_cut(i + 1, len, num1, num2, chs, false) { - return true; - } - if num2 == 0 { - break; - } - } - false - } - - fn third_cut( - from: usize, - len: usize, - num1: u32, - num2: u32, - chs: &Vec, - found: bool, - ) -> bool { - if found && from >= len { - return true; - } - let mut num3 = 0; - for i in from..len { - num3 = num3 * 10 + chs[i]; - if num3 == num2 + num1 { - if Solution::third_cut(i + 1, len, num2, num3, chs, true) { - return true; - } - } else if num3 == 0 || num3 > num1 + num2 { - break; - } - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_306() { - assert_eq!(Solution::is_additive_number("112358".to_owned()), true); - assert_eq!(Solution::is_additive_number("199100199".to_owned()), true); - assert_eq!(Solution::is_additive_number("1991001990".to_owned()), false); - assert_eq!(Solution::is_additive_number("1023".to_owned()), false); - } -} diff --git a/src/solution/s0307_range_sum_query_mutable.rs b/src/solution/s0307_range_sum_query_mutable.rs deleted file mode 100644 index bbaac119..00000000 --- a/src/solution/s0307_range_sum_query_mutable.rs +++ /dev/null @@ -1,151 +0,0 @@ -/** - * [307] Range Sum Query - Mutable - * - * Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. - * - * The update(i, val) function modifies nums by updating the element at index i to val. - * - * Example: - * - * - * Given nums = [1, 3, 5] - * - * sumRange(0, 2) -> 9 - * update(1, 2) - * sumRange(0, 2) -> 8 - * - * - * Note: - * - *
    - * The array is only modifiable by the update function. - * You may assume the number of calls to update and sumRange function is distributed evenly. - *
- * - */ -pub struct Solution {} - -// Segement Tree -// -// N[0:6] -// / \ -// / \ -// N[0:3] N[4:6] -// / \ / \ -// N[0:1] N[2:3] N[4:5] N[6] -// / \ / \ / \ -// N[0] N[1] N[2] N[3] N[4] N[5] -// -// problem: https://leetcode.com/problems/range-sum-query-mutable/ -// discuss: https://leetcode.com/problems/range-sum-query-mutable/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct NumArray { - tree: Vec, - n: usize, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl NumArray { - fn new(nums: Vec) -> Self { - let n = nums.len(); - let mut tree = vec![0; 4 * n]; - if n > 0 { - NumArray::build(1, 0, n - 1, &mut tree, &nums); - } - NumArray { tree: tree, n: n } - } - - fn update(&mut self, i: i32, val: i32) { - NumArray::update_internal(i as usize, val, 1, 0, self.n - 1, &mut self.tree); - } - - fn sum_range(&self, i: i32, j: i32) -> i32 { - NumArray::sum(1, 0, self.n - 1, i as usize, j as usize, &self.tree) - } - - fn build(node: usize, start: usize, end: usize, tree: &mut Vec, nums: &Vec) { - if start == end { - tree[node] = nums[start]; - } else { - let mid = (start + end) / 2; - NumArray::build(2 * node, start, mid, tree, nums); - NumArray::build(2 * node + 1, mid + 1, end, tree, nums); - tree[node] = tree[2 * node] + tree[2 * node + 1]; - } - } - - fn update_internal( - i: usize, - val: i32, - node: usize, - start: usize, - end: usize, - tree: &mut Vec, - ) { - if start == end { - tree[node] = val; - } else { - let mid = (start + end) / 2; - if i <= mid { - NumArray::update_internal(i, val, 2 * node, start, mid, tree); - } else { - NumArray::update_internal(i, val, 2 * node + 1, mid + 1, end, tree); - } - tree[node] = tree[2 * node] + tree[2 * node + 1]; - } - } - - fn sum( - node: usize, - start: usize, - end: usize, - left: usize, - right: usize, - tree: &Vec, - ) -> i32 { - if right < start || left > end { - // not in range - 0 - } else if left <= start && end <= right { - // completely in range - tree[node] - } else { - // partially in range - let mid = (start + end) / 2; - NumArray::sum(2 * node, start, mid, left, right, tree) - + NumArray::sum(2 * node + 1, mid + 1, end, left, right, tree) - } - } -} - -/** - * Your NumArray object will be instantiated and called as such: - * let obj = NumArray::new(nums); - * obj.update(i, val); - * let ret_2: i32 = obj.sum_range(i, j); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_307() { - let _empty = NumArray::new(vec![]); - let mut tree = NumArray::new(vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1]); - assert_eq!(tree.sum_range(0, 6), 7); - tree.update(0, 2); - assert_eq!(tree.sum_range(0, 6), 8); - tree.update(1, 2); - assert_eq!(tree.sum_range(0, 2), 5); - tree.update(6, 10); - assert_eq!(tree.sum_range(6, 6), 10); - } -} diff --git a/src/solution/s0309_best_time_to_buy_and_sell_stock_with_cooldown.rs b/src/solution/s0309_best_time_to_buy_and_sell_stock_with_cooldown.rs deleted file mode 100644 index 6f3e911d..00000000 --- a/src/solution/s0309_best_time_to_buy_and_sell_stock_with_cooldown.rs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * [309] Best Time to Buy and Sell Stock with Cooldown - * - * Say you have an array for which the i^th element is the price of a given stock on day i. - * - * Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions: - * - * - * You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). - * After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day) - * - * - * Example: - * - * - * Input: [1,2,3,0,2] - * Output: 3 - * Explanation: transactions = [buy, sell, cooldown, buy, sell] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ -// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -dp[i]: max profit with selling at day i -dp2[i]: max profit till day i - -dp[i] = max(dp[i-1] + p[i] - p[i-1], dp2[i-2], dp2[i-3] + p[i] - p[i-1]) -*/ -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - if prices.len() < 2 { - return 0; - } - if prices.len() == 2 { - return i32::max(0, prices[1] - prices[0]); - } - let mut dp = vec![0; prices.len()]; - let mut dp2 = vec![0; prices.len()]; - let mut max = 0; - dp[0] = 0; - dp2[0] = 0; - dp[1] = prices[1] - prices[0]; - dp2[1] = i32::max(dp2[0], dp[1]); - dp[2] = i32::max(prices[2] - prices[1], prices[2] - prices[0]); - dp2[2] = i32::max(dp2[1], dp[2]); - for i in 3..prices.len() { - dp[i] = i32::max( - dp[i - 1] + prices[i] - prices[i - 1], - i32::max(dp2[i - 2], dp2[i - 3] + prices[i] - prices[i - 1]), - ); - dp2[i] = i32::max(dp2[i - 1], dp[i]); - } - let mut temp = 0; - for &m in dp.iter() { - if m > temp { - temp = m; - } - } - temp - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_309() { - assert_eq!(Solution::max_profit(vec![1, 2, 3, 0, 2]), 3); - assert_eq!(Solution::max_profit(vec![4, 2, 7, 1, 11]), 10); - } -} diff --git a/src/solution/s0310_minimum_height_trees.rs b/src/solution/s0310_minimum_height_trees.rs deleted file mode 100644 index 4141273c..00000000 --- a/src/solution/s0310_minimum_height_trees.rs +++ /dev/null @@ -1,110 +0,0 @@ -/** - * [310] Minimum Height Trees - * - * For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels. - * - * Format
- * The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels). - * - * You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. - * - * Example 1 : - * - * - * Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]] - * - * 0 - * | - * 1 - * / \ - * 2 3 - * - * Output: [1] - * - * - * Example 2 : - * - * - * Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] - * - * 0 1 2 - * \ | / - * 3 - * | - * 4 - * | - * 5 - * - * Output: [3, 4] - * - * Note: - * - * - * According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.” - * The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/minimum-height-trees/ -// discuss: https://leetcode.com/problems/minimum-height-trees/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::mem; -impl Solution { - pub fn find_min_height_trees(n: i32, edges: Vec>) -> Vec { - let n = n as usize; - let mut matrix: Vec> = vec![vec![]; n]; - for edge in edges.iter() { - matrix[edge[0] as usize].push(edge[1] as usize); - matrix[edge[1] as usize].push(edge[0] as usize); - } - let mut count = n; - let mut la: Vec = vec![]; - let mut lb: Vec = vec![]; - for i in 0..n { - if matrix[i].len() <= 1 { - la.push(i); - } - } - while count > 2 { - count -= la.len(); - for &i in la.iter() { - let j = matrix[i][0]; - let idx = matrix[j].iter().position(|&r| r == i).unwrap(); - matrix[j].remove(idx); - if matrix[j].len() == 1 { - lb.push(j); - } - } - la.clear(); - mem::swap(&mut la, &mut lb); - } - la.into_iter().map(|i| i as i32).collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_310() { - assert_eq!( - Solution::find_min_height_trees(4, vec![vec![1, 0], vec![1, 2], vec![1, 3]]), - vec![1] - ); - assert_eq!( - Solution::find_min_height_trees( - 6, - vec![vec![0, 3], vec![1, 3], vec![2, 3], vec![4, 3], vec![5, 4]] - ), - vec![3, 4] - ); - assert_eq!(Solution::find_min_height_trees(1, vec![]), vec![0]); - } -} diff --git a/src/solution/s0312_burst_balloons.rs b/src/solution/s0312_burst_balloons.rs deleted file mode 100644 index f8833b5e..00000000 --- a/src/solution/s0312_burst_balloons.rs +++ /dev/null @@ -1,108 +0,0 @@ -/** - * [312] Burst Balloons - * - * Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent. - * - * Find the maximum coins you can collect by bursting the balloons wisely. - * - * Note: - * - * - * You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them. - * 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 - * - * - * Example: - * - * - * Input: [3,1,5,8] - * Output: 167 - * Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] - * coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/burst-balloons/ -// discuss: https://leetcode.com/problems/burst-balloons/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -The key idea is, for a sequence of balloon, select a balloon to be the last one to be bursted: - -max of [1 . a b c d e f . 1] - - ^ say we select 'c' as the last balloon to burst, then: - -= - max of [1 . a b . c] + - - max of [c . d e f . 1] + - - 1 * c * 1 - -Then we can use memorize to record the max of every sub sequence -*/ -impl Solution { - pub fn max_coins(nums: Vec) -> i32 { - if nums.is_empty() { - return 0; - } - let mut coins = vec![0; nums.len() + 2]; - let mut len = 0_usize; - // filter out zeros - for &num in nums.iter() { - if num != 0 { - len += 1; - coins[len] = num; - } - } - coins[0] = 1; - coins[len + 1] = 1; - - let mut memo = vec![vec![0; len + 1]; len + 1]; - Solution::max_subrange(&coins, 1, len, &mut memo) - } - - fn max_subrange(coins: &Vec, start: usize, end: usize, memo: &mut Vec>) -> i32 { - if memo[start][end] != 0 { - return memo[start][end]; - } - if start == end { - memo[start][end] = coins[start - 1] * coins[start] * coins[start + 1]; - return memo[start][end]; - } - let mut max = 0; - for i in start..end + 1 { - let left_max = if i > start { - Solution::max_subrange(coins, start, i - 1, memo) - } else { - 0 - }; - let right_max = if i < end { - Solution::max_subrange(coins, i + 1, end, memo) - } else { - 0 - }; - max = i32::max( - max, - left_max + right_max + coins[i] * coins[start - 1] * coins[end + 1], - ); - } - memo[start][end] = max; - return memo[start][end]; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_312() { - assert_eq!(Solution::max_coins(vec![3, 1, 5, 8]), 167); - } -} diff --git a/src/solution/s0313_super_ugly_number.rs b/src/solution/s0313_super_ugly_number.rs deleted file mode 100644 index bf99bcc8..00000000 --- a/src/solution/s0313_super_ugly_number.rs +++ /dev/null @@ -1,94 +0,0 @@ -/** - * [313] Super Ugly Number - * - * Write a program to find the n^th super ugly number. - * - * Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. - * - * Example: - * - * - * Input: n = 12, primes = [2,7,13,19] - * Output: 32 - * Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 - * super ugly numbers given primes = [2,7,13,19] of size 4. - * - * Note: - * - * - * 1 is a super ugly number for any given primes. - * The given numbers in primes are in ascending order. - * 0 < k ≤ 100, 0 < n ≤ 10^6, 0 < primes[i] < 1000. - * The n^th super ugly number is guaranteed to fit in a 32-bit signed integer. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/super-ugly-number/ -// discuss: https://leetcode.com/problems/super-ugly-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cmp::Ordering; -use std::collections::BinaryHeap; -#[derive(Eq, PartialEq)] -struct Invert { - base: i32, - idx: usize, - value: i32, -} - -impl Ord for Invert { - fn cmp(&self, other: &Invert) -> Ordering { - other.value.cmp(&self.value) - } -} - -impl PartialOrd for Invert { - fn partial_cmp(&self, other: &Invert) -> Option { - Some(self.cmp(other)) - } -} - -impl Solution { - pub fn nth_super_ugly_number(n: i32, primes: Vec) -> i32 { - let mut vec = vec![1; 1]; - let mut heap: BinaryHeap = BinaryHeap::new(); - for &prime in primes.iter() { - heap.push(Invert { - base: prime, - idx: 0, - value: prime, - }); - } - for _ in 0..n - 1 { - let mut min = 0; - if let Some(num) = heap.peek() { - min = num.value; - } - vec.push(min); - while heap.peek().unwrap().value == min { - let p = heap.pop().unwrap(); - heap.push(Invert { - base: p.base, - idx: p.idx + 1, - value: p.base * vec[p.idx + 1], - }); - } - } - *vec.last().unwrap() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_313() { - assert_eq!(Solution::nth_super_ugly_number(12, vec![2, 7, 13, 19]), 32); - } -} diff --git a/src/solution/s0509_fibonacci_number.rs b/src/solution/s0509_fibonacci_number.rs deleted file mode 100644 index 47a9b420..00000000 --- a/src/solution/s0509_fibonacci_number.rs +++ /dev/null @@ -1,78 +0,0 @@ -/** - * [1013] Fibonacci Number - * - * The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, - * - * - * F(0) = 0, F(1) = 1 - * F(N) = F(N - 1) + F(N - 2), for N > 1. - * - * - * Given N, calculate F(N). - * - * - * - * Example 1: - * - * - * Input: 2 - * Output: 1 - * Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. - * - * - * Example 2: - * - * - * Input: 3 - * Output: 2 - * Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. - * - * - * Example 3: - * - * - * Input: 4 - * Output: 3 - * Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. - * - * - * - * - * Note: - * - * 0 ≤ N ≤ 30. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/fibonacci-number/ -// discuss: https://leetcode.com/problems/fibonacci-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn fib(n: i32) -> i32 { - if n == 0 { - return 0; - } - let mut f = (0, 1); - for _ in 1..n { - f = (f.1, f.0 + f.1); - } - return f.1; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_1013() { - assert_eq!(Solution::fib(2), 1); - assert_eq!(Solution::fib(3), 2); - assert_eq!(Solution::fib(4), 3); - } -} diff --git a/src/solution/s0622_design_circular_queue.rs b/src/solution/s0622_design_circular_queue.rs new file mode 100644 index 00000000..7bc808c8 --- /dev/null +++ b/src/solution/s0622_design_circular_queue.rs @@ -0,0 +1,126 @@ +/** + * [622] 设计循环队列 + * + * 设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。 + * 循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。 + * + * 你的实现应该支持如下操作: + * + * MyCircularQueue(k): 构造器,设置队列长度为 k 。 + * Front: 从队首获取元素。如果队列为空,返回 -1 。 + * Rear: 获取队尾元素。如果队列为空,返回 -1 。 + * enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。 + * deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。 + * isEmpty(): 检查循环队列是否为空。 + * isFull(): 检查循环队列是否已满。 + * + * + * 示例: + * + * MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3 + * circularQueue.enQueue(1);  // 返回 true + * circularQueue.enQueue(2);  // 返回 true + * circularQueue.enQueue(3);  // 返回 true + * circularQueue.enQueue(4);  // 返回 false,队列已满 + * circularQueue.Rear();  // 返回 3 + * circularQueue.isFull();  // 返回 true + * circularQueue.deQueue();  // 返回 true + * circularQueue.enQueue(4);  // 返回 true + * vcircularQueue.Rear();  // 返回 4 + * + * 提示: + * + * 所有的值都在 0 至 1000 的范围内; + * 操作数将在 1 至 1000 的范围内; + * 请不要使用内置的队列库。 + */ + +struct MyCircularQueue { + data: Vec, + capcity: usize, + front: usize, + rear: usize, +} + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl MyCircularQueue { + + fn new(k: i32) -> Self { + let k = k as usize + 1; + MyCircularQueue { capcity: k, data: vec![0; k], front: 0, rear: 0 } + } + + fn en_queue(&mut self, value: i32) -> bool { + if self.is_full() { + return false; + } + self.rear = (self.rear + 1) % self.capcity; + self.data[self.rear] = value; + true + } + + fn de_queue(&mut self) -> bool { + if self.is_empty() { + return false; + } + self.front = (self.front + 1) % self.capcity; + true + } + + fn front(&self) -> i32 { + if self.is_empty() { + return -1; + } + let head = (self.front + 1) % self.capcity; + self.data[head] + } + + fn rear(&self) -> i32 { + if self.is_empty() { + return -1; + } + self.data[self.rear] + } + + fn is_empty(&self) -> bool { + self.front == self.rear + } + + fn is_full(&self) -> bool { + self.front == (self.rear + 1) % self.capcity + } +} + +/** + * Your MyCircularQueue object will be instantiated and called as such: + * let obj = MyCircularQueue::new(k); + * let ret_1: bool = obj.en_queue(value); + * let ret_2: bool = obj.de_queue(); + * let ret_3: i32 = obj.front(); + * let ret_4: i32 = obj.rear(); + * let ret_5: bool = obj.is_empty(); + * let ret_6: bool = obj.is_full(); + */ + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn test_622() { + let mut queue = MyCircularQueue::new(3); + assert!(queue.en_queue(1)); + assert!(queue.en_queue(2)); + assert!(queue.en_queue(3)); + assert!(!queue.en_queue(4)); + assert_eq!(queue.rear(), 3); + assert!(queue.is_full()); + assert!(queue.de_queue()); + assert!(queue.en_queue(4)); + assert_eq!(queue.rear(), 4); + } + } \ No newline at end of file diff --git a/src/solution/s0623_add_one_row_to_tree.rs b/src/solution/s0623_add_one_row_to_tree.rs new file mode 100644 index 00000000..f401a934 --- /dev/null +++ b/src/solution/s0623_add_one_row_to_tree.rs @@ -0,0 +1,187 @@ +/** + * [623] Add One Row to Tree + * + * Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth. + * Note that the root node is at depth 1. + * The adding rule is: + * + * Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root. + * cur's original left subtree should be the left subtree of the new left subtree root. + * cur's original right subtree should be the right subtree of the new right subtree root. + * If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree. + * + * + * Example 1: + * + * Input: root = [4,2,6,3,1,5], val = 1, depth = 2 + * Output: [4,1,1,2,null,null,6,3,1,5] + * + * Example 2: + * + * Input: root = [4,2,null,3,1], val = 1, depth = 3 + * Output: [4,2,null,1,1,3,null,null,1] + * + * + * Constraints: + * + * The number of nodes in the tree is in the range [1, 10^4]. + * The depth of the tree is in the range [1, 10^4]. + * -100 <= Node.val <= 100 + * -10^5 <= val <= 10^5 + * 1 <= depth <= the depth of tree + 1 + * + */ +pub struct Solution {} +use crate::util::tree::{to_tree, TreeNode}; + +// problem: https://leetcode.com/problems/add-one-row-to-tree/ +// discuss: https://leetcode.com/problems/add-one-row-to-tree/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } + +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn add_one_row( + root: Option>>, + val: i32, + depth: i32, + ) -> Option>> { + if (depth == 1) { + return Some(Rc::new(RefCell::new(TreeNode { + val: val, + left: root, + right: None, + }))); + } + if (depth == 2) { + let cur_root = Rc::clone(root.as_ref().unwrap()); + let mut node = cur_root.borrow_mut(); + node.left = Some(Rc::new(RefCell::new(TreeNode { + val, + left: if node.left.is_some() { + Some(Rc::clone(&node.left.as_ref().unwrap())) + } else { + None + }, + right: None, + }))); + node.right = Some(Rc::new(RefCell::new(TreeNode { + val, + left: None, + right: if node.right.is_some() { + Some(Rc::clone(&node.right.as_ref().unwrap())) + } else { + None + }, + }))); + return root; + } + let cur_root = Rc::clone(root.as_ref().unwrap()); + let mut node = cur_root.borrow_mut(); + + if let Some(left) = &node.left { + node.left = Self::add_one_row(Some(Rc::clone(left)), val, depth - 1); + } + if let Some(right) = &node.right { + node.right = Self::add_one_row(Some(Rc::clone(right)), val, depth - 1); + } + return root; + } + + pub fn add_one_row_bfs( + root: Option>>, + val: i32, + depth: i32, + ) -> Option>> { + if (depth == 1) { + return Some(Rc::new(RefCell::new(TreeNode { + val: val, + left: root, + right: None, + }))); + } + // 1. 遍历到深度为depth的节点,插入新节点 + let mut queue = vec![Some(Rc::clone(root.as_ref().unwrap()))]; + for d in 1..depth - 1 { + let mut temp = Vec::new(); + queue.iter().for_each(|node| { + let node = Rc::clone(node.as_ref().unwrap()); + let mut node = node.borrow_mut(); + if let Some(left_node) = &node.left { + temp.push(Some(Rc::clone(left_node))); + } + if let Some(right_node) = &node.right { + temp.push(Some(Rc::clone(right_node))); + } + }); + queue = temp; + } + + queue.iter().for_each(|node| { + let node = Rc::clone(node.as_ref().unwrap()); + let mut node = node.borrow_mut(); + node.left = Some(Rc::new(RefCell::new(TreeNode { + val, + left: if node.left.is_some() { + Some(Rc::clone(&node.left.as_ref().unwrap())) + } else { + None + }, + right: None, + }))); + node.right = Some(Rc::new(RefCell::new(TreeNode { + val, + left: None, + right: if node.right.is_some() { + Some(Rc::clone(&node.right.as_ref().unwrap())) + } else { + None + }, + }))); + }); + return root; + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_623() { + assert_eq!( + Solution::add_one_row_bfs(tree![1, 2, 3, 4], 5, 4), + tree![1, 2, 3, 4, null, null, null, 5, 5] + ); + assert_eq!( + Solution::add_one_row_bfs(tree![4, 2, 6, 3, 1, 5], 1, 2), + tree![4, 1, 1, 2, null, null, 6, 3, 1, 5] + ); + assert_eq!( + Solution::add_one_row_bfs(tree![4, 2, null, 3, 1], 1, 3), + tree![4, 2, null, 1, 1, 3, null, null, 1] + ) + } +} diff --git a/src/solution/s0636_exclusive_time_of_function.rs b/src/solution/s0636_exclusive_time_of_function.rs new file mode 100644 index 00000000..43925f49 --- /dev/null +++ b/src/solution/s0636_exclusive_time_of_function.rs @@ -0,0 +1,60 @@ +use core::time; + +/** + * [636] exclusive time of function + * https://leetcode.cn/problems/exclusive-time-of-functions/ + */ + +pub struct Solution {} + +impl Solution { + pub fn exclusive_time(n: i32, logs: Vec) -> Vec { + let mut times: Vec = vec![0; n as usize]; + let mut stack: Vec<(usize, i32)> = Vec::with_capacity(n as usize); + logs.iter().for_each(|log| { + let mut iterator = log.split(":"); + let id = iterator.next().unwrap().parse::().unwrap(); + let command = iterator.next().unwrap(); + let timestamp = iterator.next().unwrap().parse::().unwrap(); + + if command.eq("start") { + if !stack.is_empty() { + let (id, end_timestamp) = stack.last().unwrap(); + times[*id] += timestamp - end_timestamp; + let top = stack.len() - 1; + stack[top].1 = timestamp; + } + stack.push((id, timestamp)) + } else { + let (id, end_timestamp) = stack.pop().unwrap(); + times[id] += timestamp - end_timestamp + 1; + if !stack.is_empty() { + let top = stack.len() - 1; + stack[top].1 = timestamp + 1; + } + } + }); + times + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_636() { + assert_eq!( + Solution::exclusive_time( + 2, + vec![ + "0:start:0".to_string(), + "1:start:2".to_string(), + "1:end:5".to_string(), + "0:end:6".to_string() + ] + ), + [3, 4] + ) + } +} diff --git a/src/solution/s0640_solve_the_equation.rs b/src/solution/s0640_solve_the_equation.rs new file mode 100644 index 00000000..51949f56 --- /dev/null +++ b/src/solution/s0640_solve_the_equation.rs @@ -0,0 +1,75 @@ +use std::num; + +/** + * [640] solve the equation + * https://leetcode.cn/problems/solve-the-equation/ + */ + +pub struct Solution {} + +impl Solution { + pub fn solve_equation(equation: String) -> String { + let mut factor = 0; + let mut value = 0; + let mut sign1 = 1_i32; + let mut index = 0; + let len = equation.len(); + let chars: Vec = equation.chars().collect(); + + while index < len { + // 判断是否为等号,更改默认系数 + if chars[index] == '=' { + sign1 = -1; + index += 1; + continue; + } + + let mut sign2 = sign1; + let mut number = 0_i32; + let mut valid = false; + // 判断是否为正负号,设置当前项的系数 + if chars[index] == '-' || chars[index] == '+' { + sign2 = if chars[index] == '-' { -sign1 } else { sign1 }; + index += 1; + } + + // 判断是否为合法数字,并进行累加 + while index < len && chars[index].is_digit(10) { + number = number * 10 + chars[index].to_digit(10).unwrap() as i32; + index += 1; + valid = true; + } + + // 判断是否为变量x,并设置对 factor 累加 + if index < len && chars[index] == 'x' { + factor += if valid { number * sign2 } else { sign2 }; + index += 1; + } else { + value += sign2 * number; + } + } + // factor 等于 0 成立,说明 x 对方程无影响 + if factor == 0 { + if value == 0 { + "Infinite solutions".to_string() + } else { + "No solution".to_string() + } + } else { + format!("x={:}", (-value / factor)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_640() { + assert_eq!( + Solution::solve_equation("x+5-3+x=6+x-2".to_string()), + "x=2".to_string() + ) + } +} diff --git a/src/solution/s0641_design_circular_deque.rs b/src/solution/s0641_design_circular_deque.rs new file mode 100644 index 00000000..f842eeac --- /dev/null +++ b/src/solution/s0641_design_circular_deque.rs @@ -0,0 +1,145 @@ +/** +* [641] design circular deque +* https://leetcode.cn/problems/design-circular-deque/ +* +* 设计实现双端队列。 +* +* 实现 MyCircularDeque 类: +* +* MyCircularDeque(int k) :构造函数,双端队列最大为 k 。 +* boolean insertFront():将一个元素添加到双端队列头部。 如果操作成功返回 true ,否则返回 false 。 +* boolean insertLast() :将一个元素添加到双端队列尾部。如果操作成功返回 true ,否则返回 false 。 +* boolean deleteFront() :从双端队列头部删除一个元素。 如果操作成功返回 true ,否则返回 false 。 +* boolean deleteLast() :从双端队列尾部删除一个元素。如果操作成功返回 true ,否则返回 false 。 +* int getFront() ):从双端队列头部获得一个元素。如果双端队列为空,返回 -1 。 +* int getRear() :获得双端队列的最后一个元素。 如果双端队列为空,返回 -1 。 +* boolean isEmpty() :若双端队列为空,则返回 true ,否则返回 false  。 +* boolean isFull() :若双端队列满了,则返回 true ,否则返回 false 。 +* +* +* 示例 1: +* +* 输入 +* ["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"] +* [[3], [1], [2], [3], [4], [], [], [], [4], []] +* 输出 +* [null, true, true, true, false, 2, true, true, true, 4] +* +* 解释 +* MyCircularDeque circularDeque = new MycircularDeque(3); // 设置容量大小为3 +* circularDeque.insertLast(1); // 返回 true +* circularDeque.insertLast(2); // 返回 true +* circularDeque.insertFront(3); // 返回 true +* circularDeque.insertFront(4); // 已经满了,返回 false +* circularDeque.getRear(); // 返回 2 +* circularDeque.isFull(); // 返回 true +* circularDeque.deleteLast(); // 返回 true +* circularDeque.insertFront(4); // 返回 true +* circularDeque.getFront(); // 返回 4 + +* 提示: +* +* 1 <= k <= 1000 +* 0 <= value <= 1000 +* insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, isFull  调用次数不大于 2000 次 +*/ +struct MyCircularDeque { + data: Vec, + capacity: usize, + front: usize, + rear: usize, +} + +/** + * 1. 队列空一位可以用来判断队列满、空 + * 2. 队列头指针和尾指针的移动是不同的,这里是根据题意头指针左移动后赋值,尾指针赋值后右移 + * 3. 防止指针溢出,要对 self.capacity 取模,在 rust 里 (self.rear - 1 + self.capacity) % self.capacity 编译会报错 + * 要写成 (self.rear + self.capacity + 1) % self.capacity 才行 + * 4. Vec::with_capacity(capacity) 是有容量,但是 length 为 0,这时候用 data[0] 是赋值不了的,编译报错,一定要用 vec![0; capacity] + */ + +/** + * Your MyCircularDeque object will be instantiated and called as such: + * let obj = MyCircularDeque::new(k); + * let ret_1: bool = obj.insert_front(value); + * let ret_2: bool = obj.insert_last(value); + * let ret_3: bool = obj.delete_front(); + * let ret_4: bool = obj.delete_last(); + * let ret_5: i32 = obj.get_front(); + * let ret_6: i32 = obj.get_rear(); + * let ret_7: bool = obj.is_empty(); + * let ret_8: bool = obj.is_full(); + */ + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl MyCircularDeque { + fn new(k: i32) -> Self { + let capacity = (k + 1) as usize; + MyCircularDeque { + data: vec![0; capacity], + capacity, + front: 0, + rear: 0, + } + } + + fn insert_front(&mut self, value: i32) -> bool { + if self.is_full() { + return false; + } + self.front = (self.front + self.capacity - 1) % self.capacity; + self.data[self.front] = value; + true + } + + fn insert_last(&mut self, value: i32) -> bool { + if self.is_full() { + return false; + } + self.data[self.rear] = value; + self.rear = (self.rear + 1) % self.capacity; + true + } + + fn delete_front(&mut self) -> bool { + if self.is_empty() { + return false; + } + self.front = (self.front + 1) % self.capacity; + true + } + + fn delete_last(&mut self) -> bool { + if self.is_empty() { + return false; + } + self.rear = (self.rear + self.capacity - 1) % self.capacity; + true + } + + fn get_front(&self) -> i32 { + if self.is_empty() { + return -1; + } + self.data[self.front] + } + + fn get_rear(&self) -> i32 { + if self.is_empty() { + return -1; + } + let rear = (self.rear + self.capacity - 1) % self.capacity; + self.data[rear] + } + + fn is_empty(&self) -> bool { + self.front == self.rear + } + + fn is_full(&self) -> bool { + self.front == (self.rear + 1) % self.capacity + } +} diff --git a/src/solution/s0704_binary_search.rs b/src/solution/s0704_binary_search.rs deleted file mode 100644 index 26ed0c8d..00000000 --- a/src/solution/s0704_binary_search.rs +++ /dev/null @@ -1,83 +0,0 @@ -/** - * [792] Binary Search - * - * Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. - * - *
- * Example 1: - * - * - * Input: nums = [-1,0,3,5,9,12], target = 9 - * Output: 4 - * Explanation: 9 exists in nums and its index is 4 - * - * - * - * Example 2: - * - * - * Input: nums = [-1,0,3,5,9,12], target = 2 - * Output: -1 - * Explanation: 2 does not exist in nums so return -1 - * - * - * - * - * Note: - * - *
    - * You may assume that all elements in nums are unique. - * n will be in the range [1, 10000]. - * The value of each element in nums will be in the range [-9999, 9999]. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/binary-search/ -// discuss: https://leetcode.com/problems/binary-search/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -use std::cmp::Ordering; - -impl Solution { - pub fn search(nums: Vec, target: i32) -> i32 { - let mut lo = 0i32; - let mut hi = (nums.len() as i32) - 1; - while lo <= hi { - let mid = lo + (hi - lo) / 2; - match nums[mid as usize].cmp(&target) { - Ordering::Less => { - lo = mid + 1; - } - Ordering::Greater => { - hi = mid - 1; - } - Ordering::Equal => { - return mid; - } - } - } - -1 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_792() { - assert_eq!(Solution::search(vec![-1, 0, 3, 5, 9, 12], 9), 4); - assert_eq!(Solution::search(vec![-1, 0, 3, 5, 9, 12], 2), -1); - assert_eq!(Solution::search(vec![1], 1), 0); - assert_eq!(Solution::search(vec![5], -5), -1); - assert_eq!(Solution::search(vec![5], 6), -1); - assert_eq!(Solution::search(vec![1, 2], 0), -1); - assert_eq!(Solution::search(vec![1, 2], 1), 0); - assert_eq!(Solution::search(vec![1, 2], 2), 1); - assert_eq!(Solution::search(vec![1, 2], 3), -1); - } -} diff --git a/src/solution/s0735_asteroid_collision.rs b/src/solution/s0735_asteroid_collision.rs new file mode 100644 index 00000000..fcf80603 --- /dev/null +++ b/src/solution/s0735_asteroid_collision.rs @@ -0,0 +1,40 @@ +/** + * [735] asteroid collision + * https://leetcode.cn/problems/asteroid-collision/ + */ + +pub struct Solution {} + +impl Solution { + pub fn asteroid_collision(asteroids: Vec) -> Vec { + let mut statck: Vec = vec![]; + for (index, asteroid) in asteroids.iter().enumerate() { + let mut alive = true; + // 只有行星负方向移动,栈里还有正向移动的时候,才怕断那个会爆炸 + // 这一行代码基就是这个题的核心思路,栈是该题的核心数据结构 + while (alive && *asteroid < 0 && statck.len() > 0 && *statck.last().unwrap() > 0) { + let lastest = *statck.last().unwrap(); + alive = lastest < -asteroid; + if lastest <= -asteroid { + statck.pop(); + } + } + if alive { + statck.push(*asteroid); + } + } + statck + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_0735() { + assert_eq!(Solution::asteroid_collision(vec![5, 10, -5]), vec![5, 10]); + assert_eq!(Solution::asteroid_collision(vec![8, -8]), vec![]); + assert_eq!(Solution::asteroid_collision(vec![10, 2, -5]), vec![10]); + } +} diff --git a/src/solution/s0761_special_binary_string.rs b/src/solution/s0761_special_binary_string.rs new file mode 100644 index 00000000..6de2c42e --- /dev/null +++ b/src/solution/s0761_special_binary_string.rs @@ -0,0 +1,71 @@ +/** +* [761] special bineary string +* https://leetcode.cn/problems/special-binary-string/ +* See: 899 orderly queue +* +* 特殊的二进制序列是具有以下两个性质的二进制序列: +* +* 0 的数量与 1 的数量相等。 +* 二进制序列的每一个前缀码中 1 的数量要大于等于 0 的数量。 +* 给定一个特殊的二进制序列 S,以字符串形式表示。定义一个操作 为首先选择 S 的两个连续且非空的特殊的子串,然后将它们交换。(两个子串为连续的当且仅当第一个子串的最后一个字符恰好为第二个子串的第一个字符的前一个字符。) +* +* 在任意次数的操作之后,交换后的字符串按照字典序排列的最大的结果是什么? +* +* 示例 1: +* +* 输入: S = "11011000" +* 输出: "11100100" +* 解释: +* 将子串 "10" (在S[1]出现) 和 "1100" (在S[3]出现)进行交换。 +* 这是在进行若干次操作后按字典序排列最大的结果。 +* 说明: +* +* S 的长度不超过 50。 +* S 保证为一个满足上述定义的特殊 的二进制序列。 +*/ + +pub struct Solution {} + +impl Solution { + pub fn make_largest_special(s: String) -> String { + if s.len() <= 2 { + return s; + } + let mut count = 0; + let mut stack: Vec = Vec::new(); + let mut pre = 0; + for (i, c) in s.char_indices() { + if c == '1' { + count += 1; + } else { + count -= 1; + if count == 0 { + stack.push(format!( + "1{:}0", + Solution::make_largest_special(s[pre + 1..i].to_string()) + )); + pre = i + 1; + } + } + } + stack.sort_by(|a, b| b.cmp(a)); + stack.join("") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_761() { + assert_eq!( + Solution::make_largest_special(String::from("11011000")), + String::from("11100100") + ); + assert_eq!( + Solution::make_largest_special(String::from("101010")), + String::from("101010") + ) + } +} diff --git a/src/solution/s0768_max_chunks_to_make_sorted_ii.rs b/src/solution/s0768_max_chunks_to_make_sorted_ii.rs new file mode 100644 index 00000000..4033b78c --- /dev/null +++ b/src/solution/s0768_max_chunks_to_make_sorted_ii.rs @@ -0,0 +1,35 @@ +/** + * [768] max chunks to make sorted II + * https://leetcode.cn/problems/max-chunks-to-make-sorted-ii/ + */ + +pub struct Solution {} + +impl Solution { + pub fn max_chunks_to_sorted(arr: Vec) -> i32 { + let mut strategy = 0_i32; + let mut sorted_arr = arr.clone(); + sorted_arr.sort(); + let mut sum_arr = 0; + let mut sum_arr_sorted = 0; + for i in 0..arr.len() { + sum_arr += arr[i]; + sum_arr_sorted += sorted_arr[i]; + if sum_arr == sum_arr_sorted { + strategy += 1; + } + } + strategy + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_0768() { + assert_eq!(Solution::max_chunks_to_sorted(vec![5, 4, 3, 2, 1]), 1); + assert_eq!(Solution::max_chunks_to_sorted(vec![2, 1, 3, 4, 4]), 4); + } +} diff --git a/src/solution/s0769_max_chunks_to_make_sorted.rs b/src/solution/s0769_max_chunks_to_make_sorted.rs new file mode 100644 index 00000000..23cfd7a1 --- /dev/null +++ b/src/solution/s0769_max_chunks_to_make_sorted.rs @@ -0,0 +1,31 @@ +/** + * [769] max chunks to make sorted + * https://leetcode.cn/problems/max-chunks-to-make-sorted/ + */ + +pub struct Solution {} + +impl Solution { + pub fn max_chunks_to_sorted(arr: Vec) -> i32 { + let mut strategy = 0_i32; + let mut max = 0_i32; + for (index, number) in arr.iter().enumerate() { + max = max.max(*number); + if (index as i32) == max { + strategy += 1; + } + } + strategy + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_0769() { + assert_eq!(Solution::max_chunks_to_sorted(vec![4, 3, 2, 1, 0]), 1); + assert_eq!(Solution::max_chunks_to_sorted(vec![1, 0, 2, 3, 4]), 4); + } +} diff --git a/src/solution/s0899_orderly_queue.rs b/src/solution/s0899_orderly_queue.rs new file mode 100644 index 00000000..cae34547 --- /dev/null +++ b/src/solution/s0899_orderly_queue.rs @@ -0,0 +1,67 @@ +/** + * [899] 有序队列 + * + * 给定一个字符串 s 和一个整数 k 。你可以从 s 的前 k 个字母中选择一个,并把它加到字符串的末尾。 + * 返回 在应用上述步骤的任意数量的移动后,字典上最小的字符串 。 + * + * + * 示例 1: + * 输入:s = "cba", k = 1 + * 输出:"acb" + * 解释: + * 在第一步中,我们将第一个字符(“c”)移动到最后,获得字符串 “bac”。 + * 在第二步中,我们将第一个字符(“b”)移动到最后,获得最终结果 “acb”。 + * 示例 2: + * + * 输入:s = "baaca", k = 3 + * 输出:"aaabc" + * 解释: + * 在第一步中,我们将第一个字符(“b”)移动到最后,获得字符串 “aacab”。 + * 在第二步中,我们将第三个字符(“c”)移动到最后,获得最终结果 “aaabc”。 + * + * 提示: + * + * 1 <= k <= S.length <= 1000 + * s 只由小写字母组成。 +*/ + +struct Solution {} + +impl Solution { + pub fn orderly_queue(s: String, k: i32) -> String { + if (k == 1) { + let mut min_dic = s.clone(); + for i in 0..s.len() { + // let new_dic = String::from(&s[i..]) + &s[0..i]; + let new_dic = format!("{}{}", &s[i..], &s[0..i]); + if (new_dic < min_dic) { + min_dic = new_dic; + } + } + return min_dic; + } + + unsafe { + let mut vec = s.into_bytes(); + vec.sort(); + return String::from_utf8(vec).unwrap(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_899() { + assert_eq!( + Solution::orderly_queue(String::from("cba"), 1), + String::from("acb") + ); + assert_eq!( + Solution::orderly_queue(String::from("baaca"), 3), + String::from("aaabc") + ) + } +} diff --git a/src/solution/s0969_pancake_sorting.rs b/src/solution/s0969_pancake_sorting.rs deleted file mode 100644 index 541ae423..00000000 --- a/src/solution/s0969_pancake_sorting.rs +++ /dev/null @@ -1,148 +0,0 @@ -/** - * [1009] Pancake Sorting - * - * Given an array A, we can perform a pancake flip: We choose some positive integer k <= A.length, then reverse the order of the first k elements of A. We want to perform zero or more pancake flips (doing them one after another in succession) to sort the array A. - * - * Return the k-values corresponding to a sequence of pancake flips that sort A. Any valid answer that sorts the array within 10 * A.length flips will be judged as correct. - * - * - * - * Example 1: - * - * - * Input: [3,2,4,1] - * Output: [4,2,4,3] - * Explanation: - * We perform 4 pancake flips, with k values 4, 2, 4, and 3. - * Starting state: A = [3, 2, 4, 1] - * After 1st flip (k=4): A = [1, 4, 2, 3] - * After 2nd flip (k=2): A = [4, 1, 2, 3] - * After 3rd flip (k=4): A = [3, 2, 1, 4] - * After 4th flip (k=3): A = [1, 2, 3, 4], which is sorted. - * - * - *
- * Example 2: - * - * - * Input: [1,2,3] - * Output: [] - * Explanation: The input is already sorted, so there is no need to flip anything. - * Note that other answers, such as [3, 3], would also be accepted. - * - * - * - *
- * - * Note: - * - *
    - * 1 <= A.length <= 100 - * A[i] is a permutation of [1, 2, ..., A.length] - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/pancake-sorting/ -// discuss: https://leetcode.com/problems/pancake-sorting/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn pancake_sort(a: Vec) -> Vec { - let len = a.len(); - if len <= 1 { - return Vec::new(); - } - let mut b = a.clone(); - let mut res: Vec = Vec::new(); - for i in 0..len { - if i == (len - 1) { - break; - } - let k = (len - i) as i32; - let index = Solution::find_k(&b, k); - if index == (k - 1) as usize { - continue; - } - if index != 0usize { - Solution::pancake_oper(&mut b, index, &mut res); - } - Solution::pancake_oper(&mut b, (k - 1) as usize, &mut res); - } - // println!("{:?}", b); - res - } - - fn find_k(a: &Vec, k: i32) -> usize { - for i in 0..(k - 1) { - if a[i as usize] == k { - return i as usize; - } - } - (k - 1) as usize - } - - pub fn pancake_oper(a: &mut Vec, index: usize, res: &mut Vec) { - let mut helper = Vec::new(); - for i in 0..(index + 1) { - helper.push(a[index - i]); - } - for i in 0..(index + 1) { - a[i] = helper[i]; - } - res.push((index + 1) as i32); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - use rand::seq::SliceRandom; - use rand::{thread_rng, Rng}; - - #[test] - fn test_1009() { - for _i in 0..20 { - let mut rng = rand::thread_rng(); - let size = rng.gen_range(0, 1000); - let sorted_vector = make_sorted_vector(size); - let mut shuffled_vector = make_shuffled_vector(&sorted_vector); - let res = Solution::pancake_sort(shuffled_vector.clone()); - let oper_num = res.len(); - apply_pancake_sort_res(&mut shuffled_vector, res); - assert_eq!(shuffled_vector, sorted_vector); - assert!(oper_num < (size * 10) as usize); - } - } - - fn make_sorted_vector(i: i32) -> Vec { - (1..i + 1).collect() - } - - fn make_shuffled_vector(a: &Vec) -> Vec { - let mut rng = thread_rng(); - let mut res = a.clone(); - res.shuffle(&mut rng); - res - } - - fn apply_pancake_sort_res(shuffled_vecter: &mut Vec, oper: Vec) { - for i in oper { - pancake_oper(shuffled_vecter, (i - 1) as usize); - } - } - - pub fn pancake_oper(a: &mut Vec, index: usize) { - let mut helper = Vec::new(); - for i in 0..(index + 1) { - helper.push(a[index - i]); - } - for i in 0..(index + 1) { - a[i] = helper[i]; - } - } -} diff --git a/src/solution/s1018_binary_prefix_divisible_by_5.rs b/src/solution/s1018_binary_prefix_divisible_by_5.rs deleted file mode 100644 index b2bb1839..00000000 --- a/src/solution/s1018_binary_prefix_divisible_by_5.rs +++ /dev/null @@ -1,106 +0,0 @@ -/** - * [1071] Binary Prefix Divisible By 5 - * - * Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.) - * - * Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5. - * - * Example 1: - * - * - * Input: [0,1,1] - * Output: [true,false,false] - * Explanation: - * The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. Only the first number is divisible by 5, so answer[0] is true. - * - * - * Example 2: - * - * - * Input: [1,1,1] - * Output: [false,false,false] - * - * - * Example 3: - * - * - * Input: [0,1,1,1,1,1] - * Output: [true,false,false,false,true,false] - * - * - * Example 4: - * - * - * Input: [1,1,1,0,1] - * Output: [false,false,false,false,false] - * - * - * - * - * Note: - * - *
    - * 1 <= A.length <= 30000 - * A[i] is 0 or 1 - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/binary-prefix-divisible-by-5/ -// discuss: https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn prefixes_div_by5(a: Vec) -> Vec { - let mut ret = vec![]; - let mut n = 0; - for i in a { - let remain = (n * 2 + i) % 5; - ret.push(remain == 0); - n = remain; - } - - ret - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_1071() { - assert_eq!( - Solution::prefixes_div_by5(vec![0, 1, 1]), - vec![true, false, false] - ); - assert_eq!( - Solution::prefixes_div_by5(vec![1, 1, 1]), - vec![false, false, false] - ); - assert_eq!( - Solution::prefixes_div_by5(vec![0, 1, 1, 1, 1, 1]), - vec![true, false, false, false, true, false] - ); - assert_eq!( - Solution::prefixes_div_by5(vec![1, 1, 1, 0, 1]), - vec![false, false, false, false, false] - ); - assert_eq!( - Solution::prefixes_div_by5(vec![ - 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, - 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1 - ]), - vec![ - false, false, false, false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, true, false, false, true, true, - true, true, false - ] - ); - } -} diff --git a/src/solution/s1046_last_stone_weight.rs b/src/solution/s1046_last_stone_weight.rs deleted file mode 100644 index 871b4eb4..00000000 --- a/src/solution/s1046_last_stone_weight.rs +++ /dev/null @@ -1,78 +0,0 @@ -/** - * [1127] Last Stone Weight - * - * We have a collection of rocks, each rock has a positive integer weight. - * - * Each turn, we choose the two heaviest rocks and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: - * - * - * If x == y, both stones are totally destroyed; - * If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. - * - * - * At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.) - * - * - * - * Example 1: - * - * - * Input: [2,7,4,1,8,1] - * Output: 1 - * Explanation: - * We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, - * we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, - * we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, - * we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. - * - * - * - * Note: - * - *
    - * 1 <= stones.length <= 30 - * 1 <= stones[i] <= 1000 - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/last-stone-weight/ -// discuss: https://leetcode.com/problems/last-stone-weight/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::BinaryHeap; -impl Solution { - pub fn last_stone_weight(stones: Vec) -> i32 { - let mut heap = BinaryHeap::new(); - heap.extend(stones); - loop { - if let Some(rock1) = heap.pop() { - if let Some(rock2) = heap.pop() { - if rock1 > rock2 { - heap.push(rock1 - rock2); - } - } else { - return rock1; - } - } else { - return 0; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_1127() { - assert_eq!(Solution::last_stone_weight(vec![2, 7, 4, 1, 8, 1]), 1); - assert_eq!(Solution::last_stone_weight(vec![2]), 2); - assert_eq!(Solution::last_stone_weight(vec![2, 2]), 0); - assert_eq!(Solution::last_stone_weight(vec![1, 2, 2]), 1); - } -} diff --git a/src/solution/s1282_group_the_people_given_the_group_size_they_belong_to.rs b/src/solution/s1282_group_the_people_given_the_group_size_they_belong_to.rs new file mode 100644 index 00000000..9e3e7fbf --- /dev/null +++ b/src/solution/s1282_group_the_people_given_the_group_size_they_belong_to.rs @@ -0,0 +1,57 @@ +/** + * [1282] group the people given the group size they belong to + * https://leetcode.cn/problems/group-the-people-given-the-group-size-they-belong-to/ + */ +use std::collections::HashMap; + +pub struct Solution {} + +impl Solution { + pub fn group_the_people(group_sizes: Vec) -> Vec> { + let mut people_size_map: HashMap> = HashMap::new(); + for (index, size) in group_sizes.iter().enumerate() { + let index = index as i32; + match people_size_map.get_mut(size) { + None => { + let people = Vec::from([index]); + people_size_map.insert(*size, people); + } + Some(arr) => arr.push(index as i32), + } + } + println!("{:?}", people_size_map); + let mut groups: Vec> = Vec::new(); + for (size, people) in people_size_map { + let groups_for_size: Vec<&[i32]> = people.chunks(size as usize).collect(); + groups_for_size + .iter() + .for_each(|v| groups.push((**v).to_vec())); + + // let group_count = people.len() as i32 / size; + // for g in 0..group_count { + // let mut group = Vec::new(); + // let mut start = g * size; + // for j in 0..size { + // let index = (start + j) as usize; + // group.push(people[index]); + // } + // groups.push(group); + // } + } + + groups + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1282() { + assert_eq!( + Solution::group_the_people(vec![3, 3, 3, 3, 3, 1, 3]), + vec![vec![5], vec![0, 1, 2], vec![3, 4, 6]] + ); + } +} diff --git a/src/solution/s1302_deepest_leaves_sum.rs b/src/solution/s1302_deepest_leaves_sum.rs new file mode 100644 index 00000000..a48ca32b --- /dev/null +++ b/src/solution/s1302_deepest_leaves_sum.rs @@ -0,0 +1,94 @@ +/** + * [1302] deepest leaves sum + * https://leetcode.cn/problems/deepest-leaves-sum/ + * + * 给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。 + * + * 示例 1: + * + * 输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8] + * 输出:15 + * 示例 2: + * + * 输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] + * 输出:19 + * + * + * 提示: + * + * 树中节点数目在范围 [1, 104] 之间。 + * 1 <= Node.val <= 100 + */ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use crate::util::tree::{to_tree, TreeNode}; +use std::cell::RefCell; + +pub struct Solution {} + +use std::rc::Rc; +impl Solution { + pub fn deepest_leaves_sum(root: Option>>) -> i32 { + let mut queue = vec![root]; + + while queue.len() > 0 { + let mut list: Vec>>> = vec![]; + queue.iter().for_each(|node| { + let node = node.as_ref().unwrap().borrow(); + if node.left.is_some() { + list.push(Some(Rc::clone(node.left.as_ref().unwrap()))); + } + if node.right.is_some() { + list.push(Some(Rc::clone(node.right.as_ref().unwrap()))); + } + }); + if list.len() == 0 { + break; + } + queue = list; + } + + let mut sum = 0; + for node in queue.iter() { + sum += node.as_ref().unwrap().borrow().val; + } + sum + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1302() { + assert_eq!( + Solution::deepest_leaves_sum(tree![ + 1, 2, 3, 4, 5, null, 6, 7, null, null, null, null, 8 + ]), + 15 + ); + assert_eq!( + Solution::deepest_leaves_sum(tree![ + 6, 7, 8, 2, 7, 1, 3, 9, null, 1, 4, null, null, null, 5 + ]), + 19 + ); + } +} diff --git a/src/solution/s1374_generate_a_string_with_characters_that_have_odd_counts.rs b/src/solution/s1374_generate_a_string_with_characters_that_have_odd_counts.rs new file mode 100644 index 00000000..905ba1cd --- /dev/null +++ b/src/solution/s1374_generate_a_string_with_characters_that_have_odd_counts.rs @@ -0,0 +1,30 @@ +/** + * [1374] generate_a_string_with_characters_that_have_odd_counts + * https://leetcode.cn/problems/generate-a-string-with-characters-that-have-odd-counts/ + */ + +struct Solution; + +impl Solution { + pub fn generate_the_string(n: i32) -> String { + if (n & 1) == 1 { + (0..n).map(|_| 'a').collect::() + } else { + let mut strings = (0..n - 1).map(|_| 'b').collect::(); + strings.push('a'); + strings + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1374() { + assert_eq!(Solution::generate_the_string(1), "a"); + assert_eq!(Solution::generate_the_string(2), "ba"); + assert_eq!(Solution::generate_the_string(3), "aaa"); + } +} diff --git a/src/solution/s1403_minimum_subsequence_in_non_increasing_order.rs b/src/solution/s1403_minimum_subsequence_in_non_increasing_order.rs new file mode 100644 index 00000000..072d9a3d --- /dev/null +++ b/src/solution/s1403_minimum_subsequence_in_non_increasing_order.rs @@ -0,0 +1,63 @@ +/** + * [1403] minium subsequence in non-increasing order + * https://leetcode.com/problems/minium-subsequence-in-non-increasing-order/ + * 给你一个数组 nums,请你从中抽取一个子序列,满足该子序列的元素之和 严格 大于未包含在该子序列中的各元素之和。 + * 如果存在多个解决方案,只需返回 长度最小 的子序列。如果仍然有多个解决方案,则返回 元素之和最大 的子序列。 + * 与子数组不同的地方在于,「数组的子序列」不强调元素在原数组中的连续性,也就是说,它可以通过从数组中分离一些(也可能不分离)元素得到。 + * 注意,题目数据保证满足所有约束条件的解决方案是 唯一 的。同时,返回的答案应当按 非递增顺序 排列。 + * + * 示例 1: + * + * 输入:nums = [4,3,10,9,8] + * 输出:[10,9] + * 解释:子序列 [10,9] 和 [10,8] 是最小的、满足元素之和大于其他各元素之和的子序列。但是 [10,9] 的元素之和最大。 + * 示例 2: + * + * 输入:nums = [4,4,7,6,7] + * 输出:[7,7,6] + * 解释:子序列 [7,7] 的和为 14 ,不严格大于剩下的其他元素之和(14 = 4 + 4 + 6)。因此,[7,6,7] 是满足题意的最小子序列。注意,元素按非递增顺序返回。 + * 示例 3: + * + * 输入:nums = [6] + * 输出:[6] + * + * + * 提示: + * + * 1 <= nums.length <= 500 + * 1 <= nums[i] <= 100 +*/ + +struct Solution {} + +impl Solution { + pub fn min_subsequence(nums: Vec) -> Vec { + let mut nums = nums; + nums.sort_by(|a, b| b.cmp(a)); + let sum = nums.iter().sum::(); + let mut current = 0; + let index = nums + .iter() + .position(|&x| { + current += x; + current > sum - current + }) + .unwrap(); + nums[..=index].to_vec() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1403() { + assert_eq!(Solution::min_subsequence(vec![4, 3, 10, 9, 8]), vec![10, 9]); + assert_eq!( + Solution::min_subsequence(vec![4, 4, 7, 6, 7]), + vec![7, 7, 6] + ); + assert_eq!(Solution::min_subsequence(vec![6]), vec![6]); + } +} diff --git a/src/solution/s1408_string_matching_in_an_array.rs b/src/solution/s1408_string_matching_in_an_array.rs new file mode 100644 index 00000000..34197eeb --- /dev/null +++ b/src/solution/s1408_string_matching_in_an_array.rs @@ -0,0 +1,61 @@ +/** + * [1408] string_matching_in_an_array + * https://leetcode.cn/problems/string-matching-in-an-array/ + * + * 给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words 中是其他单词的子字符串的所有单词。 + * 如果你可以删除 words[j] 最左侧和/或最右侧的若干字符得到 word[i] ,那么字符串 words[i] 就是 words[j] 的一个子字符串。 + * + * 示例 1: + * + * 输入:words = ["mass","as","hero","superhero"] + * 输出:["as","hero"] + * 解释:"as" 是 "mass" 的子字符串,"hero" 是 "superhero" 的子字符串。 + * ["hero","as"] 也是有效的答案。 + * 示例 2: + * + * 输入:words = ["leetcode","et","code"] + * 输出:["et","code"] + * 解释:"et" 和 "code" 都是 "leetcode" 的子字符串。 + * 示例 3: + * + * 输入:words = ["blue","green","bu"] + * 输出:[] + * + * + * 提示: + * + * 1 <= words.length <= 100 + * 1 <= words[i].length <= 30 + * words[i] 仅包含小写英文字母。 + * 题目数据 保证 每个 words[i] 都是独一无二的。 + */ + +pub struct Solution {} + +impl Solution { + // 时间复杂度 O(n^2 * L2),空间复杂度 O(n) + // 题解里只提到了用 KMP 可以把复杂度优化到 O(n^2L),如果再进一步把 KMP 换成 AC 自动机就可以达到线性复杂度了。 + pub fn string_matching(words: Vec) -> Vec { + let mut arr = Vec::new(); + for (i, word1) in words.iter().enumerate() { + for (j, word2) in words.iter().enumerate() { + if i != j && word2.contains(word1) { + arr.push(word1); + break; + } + } + } + arr.iter().map(|s| s.to_string()).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1408() { + // assert_eq!(Solution::string_matching(vec!["mass","as","hero","superhero"]), vec!["as", "hero"]); + // assert_eq!(Solution::string_matching(vec!["leetcode","et","code"], vec!["et", "code"])); + } +} \ No newline at end of file diff --git a/src/solution/s1413_minimum_value_to_get_positive_step_by_step_sum.rs b/src/solution/s1413_minimum_value_to_get_positive_step_by_step_sum.rs new file mode 100644 index 00000000..182447ef --- /dev/null +++ b/src/solution/s1413_minimum_value_to_get_positive_step_by_step_sum.rs @@ -0,0 +1,64 @@ +/** + * [1413] minimum value to get positive step by step sum + * https://leetcode.cn/problems/minimum-value-to-get-positive-step-by-step-sum/ + * + * 给你一个整数数组 nums 。你可以选定任意的 正数 startValue 作为初始值。 + * + * 你需要从左到右遍历 nums 数组,并将 startValue 依次累加上 nums 数组中的值。 + * + * 请你在确保累加和始终大于等于 1 的前提下,选出一个最小的 正数 作为 startValue 。 + * + * + * + * 示例 1: + * + * 输入:nums = [-3,2,-3,4,2] + * 输出:5 + * 解释:如果你选择 startValue = 4,在第三次累加时,和小于 1 。 + * 累加求和 + *   startValue = 4 | startValue = 5 | nums + *   (4 -3 ) = 1 | (5 -3 ) = 2 | -3 + *   (1 +2 ) = 3 | (2 +2 ) = 4 | 2 + *   (3 -3 ) = 0 | (4 -3 ) = 1 | -3 + *   (0 +4 ) = 4 | (1 +4 ) = 5 | 4 + *   (4 +2 ) = 6 | (5 +2 ) = 7 | 2 + * 示例 2: + * + * 输入:nums = [1,2] + * 输出:1 + * 解释:最小的 startValue 需要是正数。 + * 示例 3: + * + * 输入:nums = [1,-2,-3] + * 输出:5 + * + * + * 提示: + * + * 1 <= nums.length <= 100 + * -100 <= nums[i] <= 100 + */ + +pub struct Solution {} + +impl Solution { + pub fn min_start_value(nums: Vec) -> i32 { + let mut acc = 0; + let mut min = 0; + for i in 0..nums.len() { + acc += nums[i]; + min = acc.min(min); + } + return 1 - min; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1413() { + assert_eq!(Solution::min_start_value(vec![-3, 2, -3, 4, 2]), 5); + } +} diff --git a/src/solution/s1417_reformat_the_string.rs b/src/solution/s1417_reformat_the_string.rs new file mode 100644 index 00000000..90effd5f --- /dev/null +++ b/src/solution/s1417_reformat_the_string.rs @@ -0,0 +1,58 @@ +/** + * [1417] reformat the string + * https://leetcode.cn/problems/reformat-the-string/ + */ +pub struct Solution {} + +impl Solution { + pub fn reformat(s: String) -> String { + let total_count = s.len() as i32; + let digit_count = s.chars().filter(|c| c.is_digit(10)).count() as i32; + let alphabetic_count = total_count - digit_count; + let diff = digit_count - alphabetic_count; + if diff.abs() > 1 { + return "".into(); + } + + let mut i = 0; + let mut j = 0; + if digit_count >= alphabetic_count { + j += 1; + } else { + i += 1; + } + let mut new_chars = vec!['_'; total_count as usize]; + s.chars().for_each(|c| { + if c.is_digit(10) { + new_chars[i] = c; + i += 2; + } else { + new_chars[j] = c; + j += 2; + } + }); + let mut result = String::new(); + new_chars.iter().for_each(|c| result.push(*c)); + result + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1417() { + assert_eq!( + Solution::reformat("a0b1c2".to_string()), + "0a1b2c".to_string() + ); + assert_eq!(Solution::reformat("leetcode".to_string()), "".to_string()); + assert_eq!(Solution::reformat("1229857369".to_string()), "".to_string()); + assert_eq!( + Solution::reformat("covid2019".to_string()), + "c2o0v1i9d".to_string() + ); + assert_eq!(Solution::reformat("ab123".to_string()), "1a2b3".to_string()); + } +} diff --git a/src/solution/s1422_maximum_score_after_splitting_a_string.rs b/src/solution/s1422_maximum_score_after_splitting_a_string.rs new file mode 100644 index 00000000..4d0c0c2e --- /dev/null +++ b/src/solution/s1422_maximum_score_after_splitting_a_string.rs @@ -0,0 +1,47 @@ +/** + * [1422] maximum score after aplitting a string + * https://leetcode.cn/problems/maximum-score-after-splitting-a-string/ + */ + +pub struct Solution {} + +impl Solution { + pub fn max_score(s: String) -> i32 { + let mut count_1 = 0; + let chars = s.chars().collect::>(); + // 左右字串非空 + // 左侧至少有一个,左侧第一个字符为0才得分 + if chars[0] == '0' { + count_1 += 1; + } + // 计算右子串的得分 + for index in 1..chars.len() { + if chars[index] == '1' { + count_1 += 1; + } + } + // 遍历所有拆分位置 + let mut max_score = count_1; + for index in 1..chars.len() - 1 { + if chars[index] == '1' { + count_1 -= 1; + } else { + count_1 += 1; + } + max_score = max_score.max(count_1); + } + max_score as i32 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1422() { + assert_eq!(Solution::max_score("011101".to_string()), 5); + assert_eq!(Solution::max_score("00111".to_string()), 5); + assert_eq!(Solution::max_score("1111".to_string()), 3); + } +} diff --git a/src/solution/s1450_number_of_students_doing_homework_at_a_given_time.rs b/src/solution/s1450_number_of_students_doing_homework_at_a_given_time.rs new file mode 100644 index 00000000..1f5fd51b --- /dev/null +++ b/src/solution/s1450_number_of_students_doing_homework_at_a_given_time.rs @@ -0,0 +1,71 @@ +/** + * [1450] Number of Students Doing Homework at a Given Time + * + * Given two integer arrays startTime and endTime and given an integer queryTime. + * The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i]. + * Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive. + * + * Example 1: + * + * Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4 + * Output: 1 + * Explanation: We have 3 students where: + * The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4. + * The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4. + * The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4. + * + * Example 2: + * + * Input: startTime = [4], endTime = [4], queryTime = 4 + * Output: 1 + * Explanation: The only student was doing their homework at the queryTime. + * + * + * Constraints: + * + * startTime.length == endTime.length + * 1 <= startTime.length <= 100 + * 1 <= startTime[i] <= endTime[i] <= 1000 + * 1 <= queryTime <= 1000 + * + */ +pub struct Solution {} + +// problem: https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time/ +// discuss: https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn busy_student(start_time: Vec, end_time: Vec, query_time: i32) -> i32 { + let mut sum = 0; + for (start_time, end_time) in start_time.iter().zip(end_time.iter()) { + if *start_time <= query_time && query_time <= *end_time { + sum += 1; + } + } + sum + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1450() { + assert_eq!(Solution::busy_student(vec![4], vec![4], 4), 1); + assert_eq!(Solution::busy_student(vec![1, 2, 3], vec![3, 2, 7], 4), 1); + assert_eq!(Solution::busy_student(vec![4], vec![4], 5), 0); + assert_eq!( + Solution::busy_student( + vec![9, 8, 7, 6, 5, 4, 3, 2, 1], + vec![10, 10, 10, 10, 10, 10, 10, 10, 10], + 5 + ), + 5 + ); + } +} diff --git a/src/solution/s1656_design_an_ordered_stream.rs b/src/solution/s1656_design_an_ordered_stream.rs new file mode 100644 index 00000000..5fd5ad98 --- /dev/null +++ b/src/solution/s1656_design_an_ordered_stream.rs @@ -0,0 +1,63 @@ +/** + * [1656] design an ordered stream + * https://leetcode.cn/problems/design-an-ordered-stream/ + */ + +struct OrderedStream { + data: Vec, + ptr: usize, +} + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl OrderedStream { + fn new(n: i32) -> Self { + OrderedStream { + data: vec![String::with_capacity(5); n as usize], + ptr: 1, + } + } + + fn insert(&mut self, id_key: i32, value: String) -> Vec { + let index = (id_key - 1) as usize; + self.data[index] = value; + + let mut list: Vec = vec![]; + if self.ptr != id_key as usize { + return list; + } + + let length = self.data.len(); + let mut position = self.ptr - 1; + while position < length && self.data[position].len() == 5 { + let item = self.data[position].clone(); + list.push(item); + position += 1; + } + self.ptr = position + 1; + list + } +} + +/** + * Your OrderedStream object will be instantiated and called as such: + * let obj = OrderedStream::new(n); + * let ret_1: Vec = obj.insert(idKey, value); + */ + +#[cfg(test)] +mod tests { + use super::OrderedStream; + + #[test] + fn test_1656() { + let mut os = OrderedStream::new(5); + assert_eq!(os.insert(3, "ccccc".to_string()), Vec::::new()); + assert_eq!(os.insert(1, "aaaaa".to_string()), vec!["aaaaa"]); + assert_eq!(os.insert(2, "bbbbb".to_string()), vec!["bbbbb", "ccccc"]); + assert_eq!(os.insert(5, "eeeee".to_string()), Vec::::new()); + assert_eq!(os.insert(4, "ddddd".to_string()), vec!["ddddd", "eeeee"]); + } +}