diff --git a/.gitignore b/.gitignore index 2f7896d1..96ef862d 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ target/ +.idea/ diff --git a/Cargo.lock b/Cargo.lock index 20204e97..a8df0eae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,1236 +1,2011 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "adler32" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d2e7343e7fc9de883d1b0341e0b13970f764c14101234857d2ddafa1cb1cac2" + [[package]] -name = "MacTypes-sys" -version = "1.3.0" +name = "aho-corasick" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58fb5e95d83b38284460a5fda7d6470aa0b8844d283a0b614b8535e880800d2d" dependencies = [ - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr", ] [[package]] -name = "adler32" -version = "1.0.3" +name = "anyhow" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7825f6833612eb2414095684fcf6c635becf3ce97fe48cf6421321e93bfbd53c" + +[[package]] +name = "autocfg" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b671c8fb71b457dd4ae18c4ba1e59aa81793daacc361d82fcd410cef0d491875" + +[[package]] +name = "autocfg" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] -name = "arrayvec" -version = "0.4.10" +name = "backtrace" +version = "0.3.38" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "690a62be8920ccf773ee00ef0968649b0e724cda8bd5b12286302b4ae955fdf5" dependencies = [ - "nodrop 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", + "backtrace-sys", + "cfg-if 0.1.10", + "libc", + "rustc-demangle", ] [[package]] -name = "autocfg" -version = "0.1.1" +name = "backtrace-sys" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82a830b4ef2d1124a711c71d263c5abdc710ef8e907bd508c88be475cebc422b" +dependencies = [ + "cc", + "libc", +] [[package]] name = "base64" -version = "0.10.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e" dependencies = [ - "byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)", + "byteorder", ] [[package]] name = "bitflags" -version = "1.0.4" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" + +[[package]] +name = "bumpalo" +version = "3.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37ccbd214614c6783386c1af30caf03192f17891059cecc394b4fb119e363de3" [[package]] name = "byteorder" -version = "1.2.7" +version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7c3dd8985a7111efc5c80b44e23ecdd8c007de8ade3b96595387e812b957cf5" [[package]] name = "bytes" -version = "0.4.11" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "206fdffcfa2df7cbe15601ef46c813fce0965eb3286db6b56c583b814b51c81c" +dependencies = [ + "byteorder", + "either", + "iovec", +] + +[[package]] +name = "c2-chacha" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d64d04786e0f528460fc884753cf8dddcc466be308f6026f8e355c41a0e4101" dependencies = [ - "byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)", - "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static", + "ppv-lite86", ] [[package]] name = "cc" -version = "1.0.28" +version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fc9a35e1f4290eb9e5fc54ba6cf40671ed2a2514c3eeb2b2a908dda2ea5a1be" [[package]] name = "cfg-if" -version = "0.1.6" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cloudabi" version = "0.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", + "bitflags", ] [[package]] -name = "core-foundation" -version = "0.5.1" +name = "cookie" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "888604f00b3db336d2af898ec3c1d5d0ddf5e6d462220f2ededc33a87ac4bbd5" dependencies = [ - "core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", + "time", + "url 1.7.2", ] [[package]] -name = "core-foundation-sys" -version = "0.5.1" +name = "cookie_store" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46750b3f362965f197996c4448e4a0935e791bf7d6631bfce9ee0af3d24c919c" dependencies = [ - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", + "cookie", + "failure", + "idna 0.1.5", + "log", + "publicsuffix", + "serde", + "serde_json", + "time", + "try_from", + "url 1.7.2", ] +[[package]] +name = "core-foundation" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25b9e03f145fd4f2bf705e07b900cd41fc636598fe5dc452fd0db1441c3f496d" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7ca8a5221364ef15ce201e8ed2f609fc312682a8f4e0e3d4aa5879764e0fa3b" + [[package]] name = "crc32fast" -version = "1.1.2" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1" dependencies = [ - "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10", ] [[package]] name = "crossbeam-channel" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ec7fcd21571dc78f96cc96243cab8d8f035247c3efd16c687be154c3fa9efa" dependencies = [ - "crossbeam-utils 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", - "smallvec 0.6.7 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.6.6", ] [[package]] name = "crossbeam-deque" -version = "0.6.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c20ff29ded3204c5106278a81a38f4b482636ed4fa1e6cfbeef193291beb29ed" dependencies = [ - "crossbeam-epoch 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-epoch", + "crossbeam-utils 0.7.2", + "maybe-uninit", ] [[package]] name = "crossbeam-epoch" -version = "0.7.0" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" +dependencies = [ + "autocfg 1.1.0", + "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 = [ - "arrayvec 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", - "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "memoffset 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.6.6", ] [[package]] name = "crossbeam-utils" -version = "0.6.3" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04973fa96e96579258a5091af6003abde64af786b860f18622b82e026cca60e6" +dependencies = [ + "cfg-if 0.1.10", + "lazy_static", +] + +[[package]] +name = "crossbeam-utils" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" +dependencies = [ + "autocfg 1.1.0", + "cfg-if 0.1.10", + "lazy_static", +] + +[[package]] +name = "curl" +version = "0.4.25" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06aa71e9208a54def20792d877bc663d6aae0732b9852e612c4a933177c31283" dependencies = [ - "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "curl-sys", + "libc", + "openssl-probe", + "openssl-sys", + "schannel", + "socket2", + "winapi 0.3.8", +] + +[[package]] +name = "curl-sys" +version = "0.4.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c38ca47d60b86d0cc9d42caa90a0885669c2abc9791f871c81f58cdf39e979b" +dependencies = [ + "cc", + "libc", + "libnghttp2-sys", + "libz-sys", + "openssl-sys", + "pkg-config", + "vcpkg", + "winapi 0.3.8", ] [[package]] name = "dtoa" -version = "0.4.3" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea57b42383d091c85abcc2706240b94ab2a8fa1fc81c10ff23c4de06e2a90b5e" + +[[package]] +name = "either" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" [[package]] name = "encoding_rs" -version = "0.8.14" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87240518927716f79692c2ed85bfe6e98196d18c6401ec75355760233a7e12e9" +dependencies = [ + "cfg-if 0.1.10", +] + +[[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" +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", +] + +[[package]] +name = "flate2" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad3c5233c9a940c8719031b423d7e6c16af66e031cb0420b0896f5245bf181d3" dependencies = [ - "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10", + "crc32fast", + "libc", + "miniz_oxide", ] [[package]] name = "fnv" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3" [[package]] name = "foreign-types" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" dependencies = [ - "foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "foreign-types-shared", ] [[package]] name = "foreign-types-shared" version = "0.1.1" 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" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "bitflags", + "fuchsia-zircon-sys", ] [[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.25" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b980f2816d6ee8673b6517b52cb0e808a180efc92e5c19d02cdda79066703ef" + +[[package]] +name = "futures" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c329ae8753502fb44ae4fc2b622fa2a94652c41e795143765ba0927f92ab780" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3083ce4b914124575708913bca19bfe887522d6e2e6d0952943f5eac4a74010" +dependencies = [ + "futures-core", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f674f3e1bcb15b37284a90cedf55afdba482ab061c407a9c0ebbd0f3109741ba" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc4045962a5a5e935ee2fdedaa4e08284547402885ab326734432bed5d12966b" + +[[package]] +name = "futures-io-preview" +version = "0.3.0-alpha.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4914ae450db1921a56c91bde97a27846287d062087d4a652efc09bb3a01ebda" + +[[package]] +name = "futures-macro" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33c1e13800337f4d4d7a316bf45a567dbcb6ffe087f16424852d97e97a91f512" +dependencies = [ + "proc-macro2 1.0.39", + "quote 1.0.2", + "syn 1.0.96", +] + +[[package]] +name = "futures-preview" +version = "0.3.0-alpha.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1dce2a0267ada5c6ff75a8ba864b4e679a9e2aa44262af7a3b5516d530d76e" +dependencies = [ + "futures-channel-preview", + "futures-core-preview", + "futures-executor-preview", + "futures-io-preview", + "futures-sink-preview", + "futures-util-preview", +] + +[[package]] +name = "futures-sink" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c66a976bf5909d801bbef33416c41372779507e7a6b3a5e25e4749c58f776a" + +[[package]] +name = "futures-util" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b7abd5d659d9b90c8cba917f6ec750a74e2dc23902ef9cd4cc8c8b22e6036a" dependencies = [ - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "num_cpus 1.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "futures-util-preview" +version = "0.3.0-alpha.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ce968633c17e5f97936bd2797b6e38fb56cf16a7422319f7ec2e30d3c470e8d" +dependencies = [ + "futures 0.1.29", + "futures-channel-preview", + "futures-core-preview", + "futures-io-preview", + "futures-sink-preview", + "memchr", + "pin-utils", + "slab", + "tokio-io", +] + +[[package]] +name = "getrandom" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "473a1265acc8ff1e808cd0a1af8cee3c2ee5200916058a2ca113c29f2d903571" +dependencies = [ + "cfg-if 0.1.10", + "libc", + "wasi", ] [[package]] name = "h2" -version = "0.1.14" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5b34c246847f938a410a03c5458c7fee2274436675e76d8b903c08efc29c462" dependencies = [ - "byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)", - "bytes 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)", - "fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", - "indexmap 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", - "string 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "byteorder", + "bytes", + "fnv", + "futures 0.1.29", + "http", + "indexmap", + "log", + "slab", + "string", + "tokio-io", +] + +[[package]] +name = "heck" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205" +dependencies = [ + "unicode-segmentation", ] [[package]] name = "http" -version = "0.1.14" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6ccf5ede3a895d8856620237b2f02972c1bbc78d2965ad7fe8838d4a0ed41f0" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6741c859c1b2463a423a1dbce98d418e6c3c3fc720fb0d45528657320920292d" dependencies = [ - "bytes 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)", - "fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", + "bytes", + "futures 0.1.29", + "http", + "tokio-buf", ] [[package]] name = "httparse" -version = "1.3.3" +version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9" [[package]] name = "hyper" -version = "0.12.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bytes 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "h2 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", - "httparse 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", - "time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-reactor 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-tcp 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-threadpool 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-timer 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", - "want 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)", +version = "0.12.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c843caf6296fc1f93444735205af9ed4e109a539005abb2564ae1d6fad34c52" +dependencies = [ + "bytes", + "futures 0.1.29", + "futures-cpupool", + "h2", + "http", + "http-body", + "httparse", + "iovec", + "itoa", + "log", + "net2", + "rustc_version", + "time", + "tokio", + "tokio-buf", + "tokio-executor", + "tokio-io", + "tokio-reactor", + "tokio-tcp", + "tokio-threadpool", + "tokio-timer", + "want", ] [[package]] name = "hyper-tls" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a800d6aa50af4b5850b2b0f659625ce9504df908e9733b635720483be26174f" dependencies = [ - "bytes 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.20 (registry+https://github.com/rust-lang/crates.io-index)", - "native-tls 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "bytes", + "futures 0.1.29", + "hyper", + "native-tls", + "tokio-io", ] [[package]] name = "idna" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e" +dependencies = [ + "matches", + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "idna" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02e2673c30ee86b5b96a9cb52ad15718aa1f966f5ab9ad54a8b95d5ca33120a9" dependencies = [ - "matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-normalization 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "matches", + "unicode-bidi", + "unicode-normalization", ] [[package]] name = "indexmap" -version = "1.0.2" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a61202fbe46c4a951e9404a720a0180bcf3212c750d735cb5c4ba4dc551299f3" [[package]] name = "iovec" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9636900aa73ffed13cdbb199f17cd955670bb300927c8d25b517dfa136b6567" dependencies = [ - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", + "libc", +] + +[[package]] +name = "isahc" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17b77027f12e53ae59a379f7074259d32eb10867e6183388020e922832d9c3fb" +dependencies = [ + "bytes", + "crossbeam-channel", + "crossbeam-utils 0.6.6", + "curl", + "curl-sys", + "futures-io-preview", + "futures-util-preview", + "http", + "lazy_static", + "log", + "slab", + "sluice", ] [[package]] name = "itoa" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "501266b7edd0174f8530248f87f99c88fbe60ca4ef3dd486835b8d8d53136f7f" [[package]] -name = "kernel32-sys" -version = "0.2.2" +name = "js-sys" +version = "0.3.35" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7889c7c36282151f6bf465be4700359318aef36baa951462382eae49e9577cf9" dependencies = [ - "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "wasm-bindgen", ] [[package]] -name = "lazy_static" -version = "1.2.0" +name = "kernel32-sys" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +dependencies = [ + "winapi 0.2.8", + "winapi-build", +] [[package]] -name = "lazycell" -version = "1.2.1" +name = "lazy_static" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "leetcode-rust" version = "0.1.0" dependencies = [ - "reqwest 0.9.8 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.34 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.3.4", + "rand 0.6.5", + "regex", + "reqwest", + "serde", + "serde_derive", + "serde_json", + "surf", ] [[package]] name = "libc" -version = "0.2.46" +version = "0.2.126" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" [[package]] -name = "libflate" -version = "0.1.19" +name = "libnghttp2-sys" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02254d44f4435dd79e695f2c2b83cd06a47919adea30216ceaf0c57ca0a72463" dependencies = [ - "adler32 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)", - "crc32fast 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "cc", + "libc", +] + +[[package]] +name = "libz-sys" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eb5e43362e38e2bca2fd5f5134c4d4564a23a5c28e9b95411652021a8675ebe" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", ] [[package]] name = "lock_api" -version = "0.1.5" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8912e782533a93a167888781b836336a6ca5da6175c05944c86cf28c31104dc" dependencies = [ - "owning_ref 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "scopeguard", ] [[package]] name = "log" -version = "0.4.6" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" dependencies = [ - "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10", ] [[package]] name = "matches" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" + +[[package]] +name = "maybe-uninit" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +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.2.1" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6075db033bbbb7ee5a0bbd3a3186bbae616f57fb001c485c7ff77955f8177f" +dependencies = [ + "rustc_version", +] [[package]] name = "mime" -version = "0.3.13" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd1d63acd1b78403cc0c325605908475dd9b9a3acbf65ed8bcab97e27014afcf" + +[[package]] +name = "mime_guess" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a0ed03949aef72dbdf3116a383d7b38b4768e6f960528cd6a6044aa9ed68599" dependencies = [ - "unicase 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "mime", + "unicase", ] [[package]] -name = "mime_guess" -version = "2.0.0-alpha.6" +name = "miniz_oxide" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "304f66c19be2afa56530fa7c39796192eef38618da8d19df725ad7c6d6b2aaae" dependencies = [ - "mime 0.3.13 (registry+https://github.com/rust-lang/crates.io-index)", - "phf 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)", - "phf_codegen 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)", - "unicase 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "adler32", ] [[package]] name = "mio" -version = "0.6.16" +version = "0.6.19" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83f51996a3ed004ef184e16818edc51fadffe8e7ca68be67f9dee67d84d0ff23" dependencies = [ - "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-zircon", + "fuchsia-zircon-sys", + "iovec", + "kernel32-sys", + "libc", + "log", + "miow", + "net2", + "slab", + "winapi 0.2.8", ] [[package]] name = "miow" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebd808424166322d4a38da87083bfddd3ac4c131334ed55856112eb06d46944d" dependencies = [ - "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", - "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "kernel32-sys", + "net2", + "winapi 0.2.8", + "ws2_32-sys", ] [[package]] name = "native-tls" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b2df1a4c22fd44a62147fd8f13dd0f95c9d8ca7b2610299b2a2f9cf8964274e" dependencies = [ - "lazy_static 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl 0.10.16 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl-probe 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl-sys 0.9.40 (registry+https://github.com/rust-lang/crates.io-index)", - "schannel 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", - "security-framework 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "security-framework-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "tempfile 3.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static", + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", ] [[package]] name = "net2" -version = "0.2.33" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "391630d12b68002ae1e25e8f974306474966550ad82dac6886fb8910c19568ae" dependencies = [ - "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10", + "libc", + "winapi 0.3.8", ] [[package]] -name = "nodrop" -version = "0.1.13" +name = "nom" +version = "4.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ad2a91a8e869eeb30b9cb3119ae87773a8f4ae617f41b1eb9c154b2905f7bd6" +dependencies = [ + "memchr", + "version_check", +] [[package]] name = "num_cpus" -version = "1.9.0" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcef43580c035376c0705c42792c294b66974abbfd2789b511784023f71f3273" dependencies = [ - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", + "libc", ] +[[package]] +name = "once_cell" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" + [[package]] name = "openssl" -version = "0.10.16" +version = "0.10.25" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f372b2b53ce10fb823a337aaa674e3a7d072b957c6264d0f4ff0bd86e657449" dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", - "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl-sys 0.9.40 (registry+https://github.com/rust-lang/crates.io-index)", + "bitflags", + "cfg-if 0.1.10", + "foreign-types", + "lazy_static", + "libc", + "openssl-sys", ] [[package]] name = "openssl-probe" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de" [[package]] name = "openssl-sys" -version = "0.9.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cc 1.0.28 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", - "vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "owning_ref" -version = "0.4.0" +version = "0.9.50" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c42dcccb832556b5926bc9ae61e8775f2a61e725ab07ab3d1e7fcf8ae62c3b6" dependencies = [ - "stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "autocfg 0.1.6", + "cc", + "libc", + "pkg-config", + "vcpkg", ] [[package]] name = "parking_lot" -version = "0.7.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f842b1982eb6c2fe34036a4fbfb06dd185a3f5c8edfaacdf7d1ea10b07de6252" dependencies = [ - "lock_api 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "lock_api", + "parking_lot_core", + "rustc_version", ] [[package]] name = "parking_lot_core" -version = "0.4.0" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b876b1b9e7ac6e1a74a6da34d25c42e17e8862aa409cbbbdcfc8d86c6f3bc62b" dependencies = [ - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "smallvec 0.6.7 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10", + "cloudabi", + "libc", + "redox_syscall", + "rustc_version", + "smallvec", + "winapi 0.3.8", ] [[package]] name = "percent-encoding" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831" [[package]] -name = "phf" -version = "0.7.24" +name = "percent-encoding" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "phf_shared 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)", -] +checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" [[package]] -name = "phf_codegen" -version = "0.7.24" +name = "pin-project-lite" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "phf_generator 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)", - "phf_shared 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)", -] +checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d5370d90f49f70bd033c3d75e87fc529fbfff9d6f7cccef07d6170079d91ea" [[package]] -name = "phf_generator" -version = "0.7.24" +name = "ppv-lite86" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3cbf9f658cdb5000fcf6f362b8ea2ba154b9f146a61c7a20d647034c6b6561b" + +[[package]] +name = "proc-macro2" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" dependencies = [ - "phf_shared 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid", ] [[package]] -name = "phf_shared" -version = "0.7.24" +name = "proc-macro2" +version = "1.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c54b25569025b7fc9651de43004ae593a75ad88543b17178aa5e1b9c4f15f56f" dependencies = [ - "siphasher 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "unicase 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-ident", ] [[package]] -name = "pkg-config" -version = "0.3.14" +name = "publicsuffix" +version = "1.5.3" 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", +] [[package]] -name = "proc-macro2" -version = "0.4.24" +name = "quote" +version = "0.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" dependencies = [ - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 0.4.30", ] [[package]] name = "quote" -version = "0.6.10" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" dependencies = [ - "proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.39", ] [[package]] name = "rand" -version = "0.5.5" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca" dependencies = [ - "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "rand_core 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "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", ] [[package]] name = "rand" -version = "0.6.4" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae1b169243eaf61759b8475a998f0a385e42042370f3a7dbaf35246eacc8412" dependencies = [ - "autocfg 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "rand_chacha 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "rand_hc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "rand_isaac 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "rand_os 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "rand_pcg 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "rand_xorshift 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "getrandom", + "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.1 (registry+https://github.com/rust-lang/crates.io-index)", - "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "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.2.2" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" dependencies = [ - "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.4.2", ] [[package]] name = "rand_core" -version = "0.3.0" +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.0 (registry+https://github.com/rust-lang/crates.io-index)", + "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", ] [[package]] name = "rand_isaac" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" +dependencies = [ + "rand_core 0.3.1", +] + +[[package]] +name = "rand_jitter" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b" dependencies = [ - "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "libc", + "rand_core 0.4.2", + "winapi 0.3.8", ] [[package]] name = "rand_os" -version = "0.1.1" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" dependencies = [ - "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "rdrand 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "cloudabi", + "fuchsia-cprng", + "libc", + "rand_core 0.4.2", + "rdrand", + "winapi 0.3.8", ] [[package]] name = "rand_pcg" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44" dependencies = [ - "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "autocfg 0.1.6", + "rand_core 0.4.2", ] [[package]] name = "rand_xorshift" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" dependencies = [ - "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1", ] [[package]] name = "rdrand" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" dependencies = [ - "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1", ] [[package]] name = "redox_syscall" -version = "0.1.50" +version = "0.1.56" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" + +[[package]] +name = "regex" +version = "1.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "322cf97724bea3ee221b78fe25ac9c46114ebb51747ad5babd51a2fc6a8235a8" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", + "thread_local", +] + +[[package]] +name = "regex-syntax" +version = "0.6.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b28dfe3fe9badec5dbf0a79a9cccad2cfc2ab5484bdb3e44cbd1ae8b3ba2be06" [[package]] name = "remove_dir_all" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a83fa3702a688b9359eccba92d153ac33fd2e8462f9e0e3fdf155239ea7792e" dependencies = [ - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8", ] [[package]] name = "reqwest" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "base64 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", - "bytes 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)", - "encoding_rs 0.8.14 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.20 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper-tls 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "libflate 0.1.19 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "mime 0.3.13 (registry+https://github.com/rust-lang/crates.io-index)", - "mime_guess 2.0.0-alpha.6 (registry+https://github.com/rust-lang/crates.io-index)", - "native-tls 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.34 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_urlencoded 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-threadpool 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-timer 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)", - "uuid 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", -] +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b7e953e14c6f3102b7e8d1f1ee3abf5ecee80b427f5565c9389835cecae95c" +dependencies = [ + "base64", + "bytes", + "cookie", + "cookie_store", + "encoding_rs", + "flate2", + "futures 0.1.29", + "http", + "hyper", + "hyper-tls", + "log", + "mime", + "mime_guess", + "native-tls", + "serde", + "serde_json", + "serde_urlencoded 0.5.5", + "time", + "tokio", + "tokio-executor", + "tokio-io", + "tokio-threadpool", + "tokio-timer", + "url 1.7.2", + "uuid", + "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" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" dependencies = [ - "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "semver", ] [[package]] name = "ryu" -version = "0.2.7" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92464b447c0ee8c4fb3824ecc8383b81717b9f1e74ba2e72540aef7b9f82997" [[package]] name = "schannel" -version = "0.1.14" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f550b06b6cba9c8b8be3ee73f391990116bf527450d2556e9b9ce263b9a021" dependencies = [ - "lazy_static 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static", + "winapi 0.3.8", ] [[package]] name = "scopeguard" -version = "0.3.3" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e15e59b18a828bbf5c58ea01debb36b9b096346de35d941dcb89009f24a0d" [[package]] name = "security-framework" -version = "0.2.1" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eee63d0f4a9ec776eeb30e220f0bc1e092c3ad744b2a379e3993070364d3adc2" dependencies = [ - "core-foundation 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "security-framework-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", ] [[package]] name = "security-framework-sys" -version = "0.2.2" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9636f8989cbf61385ae4824b98c1aaa54c994d7d8b41f11c601ed799f0549a56" dependencies = [ - "MacTypes-sys 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation-sys", ] [[package]] name = "semver" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" dependencies = [ - "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "semver-parser", ] [[package]] name = "semver-parser" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" [[package]] name = "serde" -version = "1.0.84" +version = "1.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9796c9b7ba2ffe7a9ce53c2287dfc48080f4b2b362fcc245a259b3a7201119dd" +dependencies = [ + "serde_derive", +] [[package]] name = "serde_derive" -version = "1.0.84" +version = "1.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b133a43a1ecd55d4086bd5b4dc6c1751c68b1bfbeba7a5040442022c7e7c02e" dependencies = [ - "proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.15.24 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.39", + "quote 1.0.2", + "syn 1.0.96", ] [[package]] name = "serde_json" -version = "1.0.34" +version = "1.0.41" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f72eb2a68a7dc3f9a691bfda9305a1c017a6215e5a4545c258500d2099a37c2" dependencies = [ - "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", - "ryu 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", + "itoa", + "ryu", + "serde", ] [[package]] name = "serde_urlencoded" -version = "0.5.4" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "642dd69105886af2efd227f75a520ec9b44a820d65bc133a9131f7d229fd165a" dependencies = [ - "dtoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", - "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "dtoa", + "itoa", + "serde", + "url 1.7.2", ] [[package]] -name = "siphasher" -version = "0.2.3" +name = "serde_urlencoded" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ec5d77e2d4c73717816afac02670d5c4f534ea95ed430442cad02e7a6e32c97" +dependencies = [ + "dtoa", + "itoa", + "serde", + "url 2.1.0", +] [[package]] name = "slab" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" + +[[package]] +name = "sluice" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a7d06dfb3e8743bc19e6de8a302277471d08077d68946b307280496dc5a3531" +dependencies = [ + "futures-channel-preview", + "futures-core-preview", + "futures-io-preview", +] [[package]] name = "smallvec" -version = "0.6.7" +version = "0.6.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97fcaeba89edba30f044a10c6a3cc39df9c3f17d7cd829dd1446cab35f890e0" +dependencies = [ + "maybe-uninit", +] + +[[package]] +name = "socket2" +version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "122e570113d28d773067fab24266b66753f6ea915758651696b6e35e49f88d6e" dependencies = [ - "unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 1.0.0", + "libc", + "winapi 0.3.8", ] [[package]] -name = "stable_deref_trait" -version = "1.1.1" +name = "sourcefile" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bf77cb82ba8453b42b6ae1d692e4cdc92f9a47beaf89a847c8be83f4e328ad3" [[package]] name = "string" -version = "0.1.3" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d24114bfcceb867ca7f71a0d3fe45d45619ec47a6fbfa98cb14e14250bfa5d6d" +dependencies = [ + "bytes", +] + +[[package]] +name = "surf" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "741a8008f8a833ef16f47df94a30754478fb2c2bf822b9c2e6f7f09203b97ace" +dependencies = [ + "futures-preview", + "http", + "isahc", + "js-sys", + "log", + "mime", + "mime_guess", + "serde", + "serde_json", + "serde_urlencoded 0.6.1", + "url 2.1.0", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "syn" +version = "0.15.44" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" +dependencies = [ + "proc-macro2 0.4.30", + "quote 0.6.13", + "unicode-xid", +] [[package]] name = "syn" -version = "0.15.24" +version = "1.0.96" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0748dd251e24453cb8717f0354206b91557e4ec8703673a4b30208f2abaf1ebf" +dependencies = [ + "proc-macro2 1.0.39", + "quote 1.0.2", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02353edf96d6e4dc81aea2d8490a7e9db177bf8acb0e951c24940bf866cb313f" dependencies = [ - "proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 0.4.30", + "quote 0.6.13", + "syn 0.15.44", + "unicode-xid", ] [[package]] name = "tempfile" -version = "3.0.5" +version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9" dependencies = [ - "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", - "redox_syscall 0.1.50 (registry+https://github.com/rust-lang/crates.io-index)", - "remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10", + "libc", + "rand 0.7.2", + "redox_syscall", + "remove_dir_all", + "winapi 0.3.8", +] + +[[package]] +name = "thread_local" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5516c27b78311c50bf42c071425c560ac799b11c30b31f87e3081965fe5e0180" +dependencies = [ + "once_cell", ] [[package]] name = "time" version = "0.1.42" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db8dcfca086c1143c9270ac42a2bbd8a7ee477b78ac8e45b19abfb0cbede4b6f" dependencies = [ - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "redox_syscall 0.1.50 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "libc", + "redox_syscall", + "winapi 0.3.8", ] [[package]] name = "tokio" -version = "0.1.14" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a09c0b5bb588872ab2f09afa13ee6e9dac11e10a0ec9e8e3ba39a5a5d530af6" +dependencies = [ + "bytes", + "futures 0.1.29", + "mio", + "num_cpus", + "tokio-current-thread", + "tokio-executor", + "tokio-io", + "tokio-reactor", + "tokio-tcp", + "tokio-threadpool", + "tokio-timer", +] + +[[package]] +name = "tokio-buf" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fb220f46c53859a4b7ec083e41dec9778ff0b1851c0942b211edb89e0ccdc46" dependencies = [ - "bytes 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", - "num_cpus 1.9.0 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-current-thread 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-reactor 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-threadpool 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-timer 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", + "bytes", + "either", + "futures 0.1.29", ] [[package]] name = "tokio-current-thread" -version = "0.1.4" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d16217cad7f1b840c5a97dfb3c43b0c871fef423a6e8d2118c604e843662a443" dependencies = [ - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.29", + "tokio-executor", ] [[package]] name = "tokio-executor" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f27ee0e6db01c5f0b2973824547ce7e637b2ed79b891a9677b0de9bd532b6ac" dependencies = [ - "crossbeam-utils 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.6.6", + "futures 0.1.29", ] [[package]] name = "tokio-io" -version = "0.1.11" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5090db468dad16e1a7a54c8c67280c5e4b544f3d3e018f0b913b400261f85926" dependencies = [ - "bytes 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", + "bytes", + "futures 0.1.29", + "log", ] [[package]] name = "tokio-reactor" -version = "0.1.8" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56391be9805bc80163151c0b9e5164ee64f4b0200962c346fea12773158f22d" +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", +] + +[[package]] +name = "tokio-sync" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2162248ff317e2bc713b261f242b69dbb838b85248ed20bb21df56d60ea4cae7" dependencies = [ - "crossbeam-utils 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", - "num_cpus 1.9.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "fnv", + "futures 0.1.29", ] [[package]] name = "tokio-tcp" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d14b10654be682ac43efee27401d792507e30fd8d26389e1da3b185de2e4119" dependencies = [ - "bytes 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-reactor 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "bytes", + "futures 0.1.29", + "iovec", + "mio", + "tokio-io", + "tokio-reactor", ] [[package]] name = "tokio-threadpool" -version = "0.1.10" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bd2c6a3885302581f4401c82af70d792bb9df1700e7437b0aeb4ada94d5388c" dependencies = [ - "crossbeam-channel 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-deque 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "num_cpus 1.9.0 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-deque", + "crossbeam-queue", + "crossbeam-utils 0.6.6", + "futures 0.1.29", + "lazy_static", + "log", + "num_cpus", + "slab", + "tokio-executor", ] [[package]] name = "tokio-timer" -version = "0.2.8" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2106812d500ed25a4f38235b9cae8f78a09edf43203e16e59c3b769a342a60e" dependencies = [ - "crossbeam-utils 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.6.6", + "futures 0.1.29", + "slab", + "tokio-executor", ] [[package]] name = "try-lock" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e604eb7b43c06650e854be16a2a03155743d3752dd1c943f6829e26b7a36e382" [[package]] -name = "unicase" -version = "1.4.2" +name = "try_from" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "283d3b89e1368717881a9d51dad843cc435380d8109c9e47d38780a324698d8b" dependencies = [ - "version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10", ] [[package]] name = "unicase" -version = "2.2.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e2e6bd1e59e56598518beb94fd6db628ded570326f0a98c679a304bd9f00150" dependencies = [ - "version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "version_check", ] [[package]] name = "unicode-bidi" version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5" dependencies = [ - "matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "matches", ] +[[package]] +name = "unicode-ident" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bd2fe26506023ed7b5e1e315add59d6f584c621d037f9368fea9cfb988f368c" + [[package]] name = "unicode-normalization" -version = "0.1.7" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "141339a08b982d942be2ca06ff8b076563cbe223d1befd5450716790d44e2426" +dependencies = [ + "smallvec", +] + +[[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 = "unreachable" -version = "1.0.0" +name = "url" +version = "1.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd4e7c0d531266369519a4aa4f399d748bd37043b00bde1e4ff1f60a120b355a" dependencies = [ - "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "idna 0.1.5", + "matches", + "percent-encoding 1.0.1", ] [[package]] name = "url" -version = "1.7.2" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b414f6c464c879d7f9babf951f23bc3743fb7313c081b2e6ca719067ea9d61" dependencies = [ - "idna 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "idna 0.2.0", + "matches", + "percent-encoding 2.1.0", ] [[package]] name = "uuid" -version = "0.7.1" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90dbc611eb48397705a6b0f6e917da23ae517e4d127123d2cf7674206627d32a" dependencies = [ - "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.6.5", ] [[package]] name = "vcpkg" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33dd455d0f96e90a75803cfeb7f948768c08d70a6de9a8d2362461935698bf95" [[package]] name = "version_check" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" [[package]] -name = "void" -version = "1.0.2" +name = "want" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6395efa4784b027708f7451087e647ec73cc74f5d9bc2e418404248d679a230" +dependencies = [ + "futures 0.1.29", + "log", + "try-lock", +] [[package]] -name = "want" -version = "0.0.6" +name = "wasi" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b89c3ce4ce14bdc6fb6beaf9ec7928ca331de5df7e5ea278375642a2f478570d" + +[[package]] +name = "wasm-bindgen" +version = "0.2.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5205e9afdf42282b192e2310a5b463a6d1c1d774e30dc3c791ac37ab42d2616c" +dependencies = [ + "cfg-if 0.1.10", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.58" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11cdb95816290b525b32587d76419facd99662a07e59d3cdb560488a819d9a45" dependencies = [ - "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "try-lock 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "bumpalo", + "lazy_static", + "log", + "proc-macro2 1.0.39", + "quote 1.0.2", + "syn 1.0.96", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83420b37346c311b9ed822af41ec2e82839bfe99867ec6c54e2da43b7538771c" +dependencies = [ + "cfg-if 0.1.10", + "futures 0.1.29", + "futures-channel-preview", + "futures-util-preview", + "js-sys", + "lazy_static", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "574094772ce6921576fb6f2e3f7497b8a76273b6db092be18fc48a082de09dc3" +dependencies = [ + "quote 1.0.2", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e85031354f25eaebe78bb7db1c3d86140312a911a106b2e29f9cc440ce3e7668" +dependencies = [ + "proc-macro2 1.0.39", + "quote 1.0.2", + "syn 1.0.96", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.58" +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", +] + +[[package]] +name = "web-sys" +version = "0.3.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf97caf6aa8c2b1dac90faf0db529d9d63c93846cca4911856f78a83cebf53b" +dependencies = [ + "anyhow", + "js-sys", + "sourcefile", + "wasm-bindgen", + "wasm-bindgen-webidl", +] + +[[package]] +name = "weedle" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bb43f70885151e629e2a19ce9e50bd730fd436cfd4b666894c9ce4de9141164" +dependencies = [ + "nom", ] [[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.6" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" dependencies = [ - "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "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" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "winreg" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2986deb581c4fe11b621998a5e53361efe6b48a151178d0cd9eeffa4dc6acc9" +dependencies = [ + "winapi 0.3.8", +] [[package]] name = "ws2_32-sys" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" dependencies = [ - "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[metadata] -"checksum MacTypes-sys 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7dbbe033994ae2198a18517c7132d952a29fb1db44249a1234779da7c50f4698" -"checksum adler32 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "7e522997b529f05601e05166c07ed17789691f562762c7f3b987263d2dedee5c" -"checksum arrayvec 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)" = "92c7fb76bc8826a8b33b4ee5bb07a247a81e76764ab4d55e8f73e3a4d8808c71" -"checksum autocfg 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4e5f34df7a019573fb8bdc7e24a2bfebe51a2a1d6bfdbaeccedb3c41fc574727" -"checksum base64 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "621fc7ecb8008f86d7fb9b95356cd692ce9514b80a86d85b397f32a22da7b9e2" -"checksum bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12" -"checksum byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "94f88df23a25417badc922ab0f5716cc1330e87f71ddd9203b3a3ccd9cedf75d" -"checksum bytes 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)" = "40ade3d27603c2cb345eb0912aec461a6dec7e06a4ae48589904e808335c7afa" -"checksum cc 1.0.28 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4a8b715cb4597106ea87c7c84b2f1d452c7492033765df7f32651e66fcf749" -"checksum cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "082bb9b28e00d3c9d39cc03e64ce4cea0f1bb9b3fde493f0cbc008472d22bdf4" -"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" -"checksum core-foundation 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "286e0b41c3a20da26536c6000a280585d519fd07b3956b43aed8a79e9edce980" -"checksum core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "716c271e8613ace48344f723b60b900a93150271e5be206212d052bbc0883efa" -"checksum crc32fast 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e91d5240c6975ef33aeb5f148f35275c25eda8e8a5f95abe421978b05b8bf192" -"checksum crossbeam-channel 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "137bc235f622ffaa0428e3854e24acb53291fc0b3ff6fb2cb75a8be6fb02f06b" -"checksum crossbeam-deque 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "05e44b8cf3e1a625844d1750e1f7820da46044ff6d28f4d43e455ba3e5bb2c13" -"checksum crossbeam-epoch 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f10a4f8f409aaac4b16a5474fb233624238fcdeefb9ba50d5ea059aab63ba31c" -"checksum crossbeam-utils 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "41ee4864f4797060e52044376f7d107429ce1fb43460021b126424b7180ee21a" -"checksum dtoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6d301140eb411af13d3115f9a562c85cc6b541ade9dfa314132244aaee7489dd" -"checksum encoding_rs 0.8.14 (registry+https://github.com/rust-lang/crates.io-index)" = "a69d152eaa438a291636c1971b0a370212165ca8a75759eb66818c5ce9b538f7" -"checksum fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3" -"checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -"checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" -"checksum fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" -"checksum fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" -"checksum futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)" = "49e7653e374fe0d0c12de4250f0bdb60680b8c80eed558c5c7538eec9c89e21b" -"checksum futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "ab90cde24b3319636588d0c35fe03b1333857621051837ed769faefb4c2162e4" -"checksum h2 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "1ac030ae20dee464c5d0f36544d8b914a6bc606da44a57e052d2b0f5dae129e0" -"checksum http 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "02096a6d2c55e63f7fcb800690e4f889a25f6ec342e3adb4594e293b625215ab" -"checksum httparse 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e8734b0cfd3bc3e101ec59100e101c2eecd19282202e87808b3037b442777a83" -"checksum hyper 0.12.20 (registry+https://github.com/rust-lang/crates.io-index)" = "80eeda66c9ef8e18f5122fff2c54604c053420b11dae951cfb74cf1dcba2e93f" -"checksum hyper-tls 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "32cd73f14ad370d3b4d4b7dce08f69b81536c82e39fcc89731930fe5788cd661" -"checksum idna 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e" -"checksum indexmap 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7e81a7c05f79578dbc15793d8b619db9ba32b4577003ef3af1a91c416798c58d" -"checksum iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dbe6e417e7d0975db6512b90796e8ce223145ac4e33c377e4a42882a0e88bb08" -"checksum itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b" -"checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" -"checksum lazy_static 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a374c89b9db55895453a74c1e38861d9deec0b01b405a82516e9d5de4820dea1" -"checksum lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f" -"checksum libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)" = "023a4cd09b2ff695f9734c1934145a315594b7986398496841c7031a5a1bbdbd" -"checksum libflate 0.1.19 (registry+https://github.com/rust-lang/crates.io-index)" = "bff3ac7d6f23730d3b533c35ed75eef638167634476a499feef16c428d74b57b" -"checksum lock_api 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "62ebf1391f6acad60e5c8b43706dde4582df75c06698ab44511d15016bc2442c" -"checksum log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c84ec4b527950aa83a329754b01dbe3f58361d1c5efacd1f6d68c494d08a17c6" -"checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" -"checksum memoffset 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0f9dc261e2b62d7a622bf416ea3c5245cdd5d9a7fcc428c0d06804dfce1775b3" -"checksum mime 0.3.13 (registry+https://github.com/rust-lang/crates.io-index)" = "3e27ca21f40a310bd06d9031785f4801710d566c184a6e15bad4f1d9b65f9425" -"checksum mime_guess 2.0.0-alpha.6 (registry+https://github.com/rust-lang/crates.io-index)" = "30de2e4613efcba1ec63d8133f344076952090c122992a903359be5a4f99c3ed" -"checksum mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)" = "71646331f2619b1026cc302f87a2b8b648d5c6dd6937846a16cc8ce0f347f432" -"checksum miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" -"checksum native-tls 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "ff8e08de0070bbf4c31f452ea2a70db092f36f6f2e4d897adf5674477d488fb2" -"checksum net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)" = "42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88" -"checksum nodrop 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "2f9667ddcc6cc8a43afc9b7917599d7216aa09c463919ea32c59ed6cac8bc945" -"checksum num_cpus 1.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5a69d464bdc213aaaff628444e99578ede64e9c854025aa43b9796530afa9238" -"checksum openssl 0.10.16 (registry+https://github.com/rust-lang/crates.io-index)" = "ec7bd7ca4cce6dbdc77e7c1230682740d307d1218a87fb0349a571272be749f9" -"checksum openssl-probe 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de" -"checksum openssl-sys 0.9.40 (registry+https://github.com/rust-lang/crates.io-index)" = "1bb974e77de925ef426b6bc82fce15fd45bdcbeb5728bffcfc7cdeeb7ce1c2d6" -"checksum owning_ref 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "49a4b8ea2179e6a2e27411d3bca09ca6dd630821cf6894c6c7c8467a8ee7ef13" -"checksum parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337" -"checksum parking_lot_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9" -"checksum percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831" -"checksum phf 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)" = "b3da44b85f8e8dfaec21adae67f95d93244b2ecf6ad2a692320598dcc8e6dd18" -"checksum phf_codegen 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)" = "b03e85129e324ad4166b06b2c7491ae27fe3ec353af72e72cd1654c7225d517e" -"checksum phf_generator 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)" = "09364cc93c159b8b06b1f4dd8a4398984503483891b0c26b867cf431fb132662" -"checksum phf_shared 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)" = "234f71a15de2288bcb7e3b6515828d22af7ec8598ee6d24c3b526fa0a80b67a0" -"checksum pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "676e8eb2b1b4c9043511a9b7bea0915320d7e502b0a079fb03f9635a5252b18c" -"checksum proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)" = "77619697826f31a02ae974457af0b29b723e5619e113e9397b8b82c6bd253f09" -"checksum quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)" = "53fa22a1994bd0f9372d7a816207d8a2677ad0325b073f5c5332760f0fb62b5c" -"checksum rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e464cd887e869cddcae8792a4ee31d23c7edd516700695608f5b98c67ee0131c" -"checksum rand 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "3906503e80ac6cbcacb2c2973fa8e473f24d7e2747c8c92bb230c2441cad96b5" -"checksum rand_chacha 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef" -"checksum rand_core 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1961a422c4d189dfb50ffa9320bf1f2a9bd54ecb92792fb9477f99a1045f3372" -"checksum rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0905b6b7079ec73b314d4c748701f6931eb79fd97c668caa3f1899b22b32c6db" -"checksum rand_hc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4" -"checksum rand_isaac 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" -"checksum rand_os 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f46fbd5550acf75b0c2730f5dd1873751daf9beb8f11b44027778fae50d7feca" -"checksum rand_pcg 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "086bd09a33c7044e56bb44d5bdde5a60e7f119a9e95b0775f545de759a32fe05" -"checksum rand_xorshift 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" -"checksum rdrand 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" -"checksum redox_syscall 0.1.50 (registry+https://github.com/rust-lang/crates.io-index)" = "52ee9a534dc1301776eff45b4fa92d2c39b1d8c3d3357e6eb593e0d795506fc2" -"checksum remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5" -"checksum reqwest 0.9.8 (registry+https://github.com/rust-lang/crates.io-index)" = "0e60f169af3915c294818d55dde549f00d2966cef36d6c5e7255d75df3f2b16f" -"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -"checksum ryu 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "eb9e9b8cde282a9fe6a42dd4681319bfb63f121b8a8ee9439c6f4107e58a46f7" -"checksum schannel 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "0e1a231dc10abf6749cfa5d7767f25888d484201accbd919b66ab5413c502d56" -"checksum scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "94258f53601af11e6a49f722422f6e3425c52b06245a5cf9bc09908b174f5e27" -"checksum security-framework 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "697d3f3c23a618272ead9e1fb259c1411102b31c6af8b93f1d64cca9c3b0e8e0" -"checksum security-framework-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "40d95f3d7da09612affe897f320d78264f0d2320f3e8eea27d12bd1bd94445e2" -"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" -"checksum serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)" = "0e732ed5a5592c17d961555e3b552985baf98d50ce418b7b655f31f6ba7eb1b7" -"checksum serde_derive 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)" = "b4d6115a3ca25c224e409185325afc16a0d5aaaabc15c42b09587d6f1ba39a5b" -"checksum serde_json 1.0.34 (registry+https://github.com/rust-lang/crates.io-index)" = "bdf540260cfee6da923831f4776ddc495ada940c30117977c70f1313a6130545" -"checksum serde_urlencoded 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)" = "d48f9f99cd749a2de71d29da5f948de7f2764cc5a9d7f3c97e3514d4ee6eabf2" -"checksum siphasher 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "0b8de496cf83d4ed58b6be86c3a275b8602f6ffe98d3024a869e124147a9a3ac" -"checksum slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" -"checksum smallvec 0.6.7 (registry+https://github.com/rust-lang/crates.io-index)" = "b73ea3738b47563803ef814925e69be00799a8c07420be8b996f8e98fb2336db" -"checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" -"checksum string 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "b639411d0b9c738748b5397d5ceba08e648f4f1992231aa859af1a017f31f60b" -"checksum syn 0.15.24 (registry+https://github.com/rust-lang/crates.io-index)" = "734ecc29cd36e8123850d9bf21dfd62ef8300aaa8f879aabaa899721808be37c" -"checksum tempfile 3.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "7e91405c14320e5c79b3d148e1c86f40749a36e490642202a31689cb1a3452b2" -"checksum time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "db8dcfca086c1143c9270ac42a2bbd8a7ee477b78ac8e45b19abfb0cbede4b6f" -"checksum tokio 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "4790d0be6f4ba6ae4f48190efa2ed7780c9e3567796abdb285003cf39840d9c5" -"checksum tokio-current-thread 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "331c8acc267855ec06eb0c94618dcbbfea45bed2d20b77252940095273fb58f6" -"checksum tokio-executor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "30c6dbf2d1ad1de300b393910e8a3aa272b724a400b6531da03eed99e329fbf0" -"checksum tokio-io 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "b53aeb9d3f5ccf2ebb29e19788f96987fa1355f8fe45ea193928eaaaf3ae820f" -"checksum tokio-reactor 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "afbcdb0f0d2a1e4c440af82d7bbf0bf91a8a8c0575bcd20c05d15be7e9d3a02f" -"checksum tokio-tcp 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1d14b10654be682ac43efee27401d792507e30fd8d26389e1da3b185de2e4119" -"checksum tokio-threadpool 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "17465013014410310f9f61fa10bf4724803c149ea1d51efece131c38efca93aa" -"checksum tokio-timer 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "4f37f0111d76cc5da132fe9bc0590b9b9cfd079bc7e75ac3846278430a299ff8" -"checksum try-lock 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e604eb7b43c06650e854be16a2a03155743d3752dd1c943f6829e26b7a36e382" -"checksum unicase 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7f4765f83163b74f957c797ad9253caf97f103fb064d3999aea9568d09fc8a33" -"checksum unicase 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9d3218ea14b4edcaccfa0df0a64a3792a2c32cc706f1b336e48867f9d3147f90" -"checksum unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5" -"checksum unicode-normalization 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "6a0180bc61fc5a987082bfa111f4cc95c4caff7f9799f3e46df09163a937aa25" -"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" -"checksum unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "382810877fe448991dfc7f0dd6e3ae5d58088fd0ea5e35189655f84e6814fa56" -"checksum url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dd4e7c0d531266369519a4aa4f399d748bd37043b00bde1e4ff1f60a120b355a" -"checksum uuid 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dab5c5526c5caa3d106653401a267fed923e7046f35895ffcb5ca42db64942e6" -"checksum vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "def296d3eb3b12371b2c7d0e83bfe1403e4db2d7a0bba324a12b21c4ee13143d" -"checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" -"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" -"checksum want 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "797464475f30ddb8830cc529aaaae648d581f99e2036a928877dfde027ddf6b3" -"checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" -"checksum winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0" -"checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" -"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" -"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -"checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" + "winapi 0.2.8", + "winapi-build", +] diff --git a/Cargo.toml b/Cargo.toml index f32b4fef..9fdbe995 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,10 @@ reqwest = "0.9.8" serde = "1.0" serde_json = "1.0" serde_derive = "1.0" +rand = "0.6.5" +regex = "1.3.4" +futures = { version = "0.3.3", features = ["thread-pool"] } +surf = "1.0.3" [lib] doctest = false diff --git a/src/problem.rs b/src/fetcher.rs similarity index 55% rename from src/problem.rs rename to src/fetcher.rs index bd920f45..c356dee8 100644 --- a/src/problem.rs +++ b/src/fetcher.rs @@ -1,7 +1,8 @@ -extern crate serde_json; extern crate reqwest; +extern crate serde_json; -use std::fmt::{Display, Formatter, Error}; +use serde_json::Value; +use std::fmt::{Display, Error, Formatter}; const PROBLEMS_URL: &str = "https://leetcode.com/api/problems/algorithms/"; const GRAPHQL_URL: &str = "https://leetcode.com/graphql"; @@ -17,29 +18,85 @@ query questionData($titleSlug: String!) { }"#; const QUESTION_QUERY_OPERATION: &str = "questionData"; -pub fn get_problem(id: u32) -> Option { +pub fn get_problem(frontend_question_id: u32) -> Option { let problems = get_problems().unwrap(); for problem in problems.stat_status_pairs.iter() { - if problem.stat.question_id == id { + if problem.stat.frontend_question_id == frontend_question_id { + if problem.paid_only { + return None; + } + let client = reqwest::Client::new(); - let resp: RawProblem = client.post(GRAPHQL_URL) - .json(&Query::question_query(problem.stat.question_title_slug.as_ref().unwrap())) - .send().unwrap() - .json().unwrap(); + let resp: RawProblem = client + .post(GRAPHQL_URL) + .json(&Query::question_query( + problem.stat.question_title_slug.as_ref().unwrap(), + )) + .send() + .unwrap() + .json() + .unwrap(); return Some(Problem { title: problem.stat.question_title.clone().unwrap(), title_slug: problem.stat.question_title_slug.clone().unwrap(), - code_definition: serde_json::from_str( & resp.data.question.code_definition).unwrap(), + code_definition: serde_json::from_str(&resp.data.question.code_definition).unwrap(), content: resp.data.question.content, sample_test_case: resp.data.question.sample_test_case, difficulty: problem.difficulty.to_string(), - }) + question_id: problem.stat.frontend_question_id, + return_type: { + let v: Value = serde_json::from_str(&resp.data.question.meta_data).unwrap(); + v["return"]["type"].to_string().replace("\"", "") + }, + }); } } None } -fn get_problems() -> Option { +pub async fn get_problem_async(problem_stat: StatWithStatus) -> Option { + if problem_stat.paid_only { + println!( + "Problem {} is paid-only", + &problem_stat.stat.frontend_question_id + ); + return None; + } + let resp = surf::post(GRAPHQL_URL).body_json(&Query::question_query( + problem_stat.stat.question_title_slug.as_ref().unwrap(), + )); + if resp.is_err() { + println!( + "Problem {} not initialized due to some error", + &problem_stat.stat.frontend_question_id + ); + return None; + } + let resp = resp.unwrap().recv_json().await; + if resp.is_err() { + println!( + "Problem {} not initialized due to some error", + &problem_stat.stat.frontend_question_id + ); + return None; + } + let resp: RawProblem = resp.unwrap(); + return Some(Problem { + title: problem_stat.stat.question_title.clone().unwrap(), + title_slug: problem_stat.stat.question_title_slug.clone().unwrap(), + code_definition: serde_json::from_str(&resp.data.question.code_definition).unwrap(), + content: resp.data.question.content, + sample_test_case: resp.data.question.sample_test_case, + difficulty: problem_stat.difficulty.to_string(), + question_id: problem_stat.stat.frontend_question_id, + return_type: { + let v: Value = serde_json::from_str(&resp.data.question.meta_data).unwrap(); + v["return"]["type"].to_string().replace("\"", "") + }, + }); +} + +pub fn get_problems() -> Option { reqwest::get(PROBLEMS_URL).unwrap().json().unwrap() } @@ -53,6 +110,8 @@ pub struct Problem { #[serde(rename = "sampleTestCase")] pub sample_test_case: String, pub difficulty: String, + pub question_id: u32, + pub return_type: String, } #[derive(Serialize, Deserialize)] @@ -63,7 +122,6 @@ pub struct CodeDefinition { pub default_code: String, } - #[derive(Debug, Serialize, Deserialize)] struct Query { #[serde(rename = "operationName")] @@ -76,7 +134,7 @@ impl Query { fn question_query(title_slug: &str) -> Query { Query { operation_name: QUESTION_QUERY_OPERATION.to_owned(), - variables: json!({"titleSlug": title_slug}), + variables: json!({ "titleSlug": title_slug }), query: QUESTION_QUERY_STRING.to_owned(), } } @@ -105,19 +163,19 @@ struct Question { } #[derive(Debug, Serialize, Deserialize)] -struct Problems { +pub struct Problems { user_name: String, num_solved: u32, num_total: u32, ac_easy: u32, ac_medium: u32, ac_hard: u32, - stat_status_pairs: Vec, + pub stat_status_pairs: Vec, } #[derive(Debug, Serialize, Deserialize)] -struct StatWithStatus { - stat: Stat, +pub struct StatWithStatus { + pub stat: Stat, difficulty: Difficulty, paid_only: bool, is_favor: bool, @@ -126,7 +184,7 @@ struct StatWithStatus { } #[derive(Debug, Serialize, Deserialize)] -struct Stat { +pub struct Stat { question_id: u32, #[serde(rename = "question__article__slug")] question_article_slug: Option, @@ -138,7 +196,7 @@ struct Stat { question_hide: bool, total_acs: u32, total_submitted: u32, - frontend_question_id: u32, + pub frontend_question_id: u32, is_new_question: bool, } diff --git a/src/lib.rs b/src/lib.rs index 75edd180..55b0298f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,220 +1,5 @@ #[macro_use] pub mod util; -mod n0001_two_sum; -mod n0002_add_two_numbers; -mod n0003_longest_substring; -mod n0004_median_of_two_sorted_arrays; -mod n0005_longest_palindromic_substring; -mod n0006_zigzag_conversion; -mod n0007_reverse_integer; -mod n0008_string_to_integer_atoi; -mod n0009_palindrome_number; -mod n0010_regular_expression_matching; -mod n0011_container_with_most_water; -mod n0012_integer_to_roman; -mod n0013_roman_to_integer; -mod n0014_longest_common_prefix; -mod n0015_3sum; -mod n0016_3sum_closest; -mod n0017_letter_combinations_of_a_phone_number; -mod n0018_4sum; -mod n0019_remove_nth_node_from_end_of_list; -mod n0020_valid_parentheses; -mod n0021_merge_two_sorted_lists; -mod n0022_generate_parentheses; -mod n0023_merge_k_sorted_lists; -mod n0024_swap_nodes_in_pairs; -mod n0025_reverse_nodes_in_k_group; -mod n0026_remove_duplicates_from_sorted_array; -mod n0027_remove_element; -mod n0028_implement_strstr; -mod n0029_divide_two_integers; -mod n0030_substring_with_concatenation_of_all_words; -mod n0031_next_permutation; -mod n0032_longest_valid_parentheses; -mod n0033_search_in_rotated_sorted_array; -mod n0034_find_first_and_last_position_of_element_in_sorted_array; -mod n0035_search_insert_position; -mod n0036_valid_sudoku; -mod n0037_sudoku_solver; -mod n0038_count_and_say; -mod n0039_combination_sum; -mod n0040_combination_sum_ii; -mod n0041_first_missing_positive; -mod n0042_trapping_rain_water; -mod n0043_multiply_strings; -mod n0044_wildcard_matching; -mod n0045_jump_game_ii; -mod n0046_permutations; -mod n0047_permutations_ii; -mod n0048_rotate_image; -mod n0049_group_anagrams; -mod n0050_powx_n; -mod n0051_n_queens; -mod n0052_n_queens_ii; -mod n0053_maximum_subarray; -mod n0054_spiral_matrix; -mod n0055_jump_game; -mod n0056_merge_intervals; -mod n0057_insert_interval; -mod n0058_length_of_last_word; -mod n0059_spiral_matrix_ii; -mod n0060_permutation_sequence; -mod n0061_rotate_list; -mod n0062_unique_paths; -mod n0063_unique_paths_ii; -mod n0064_minimum_path_sum; -mod n0065_valid_number; -mod n0066_plus_one; -mod n0067_add_binary; -mod n0068_text_justification; -mod n0069_sqrtx; -mod n0070_climbing_stairs; -mod n0071_simplify_path; -mod n0072_edit_distance; -mod n0073_set_matrix_zeroes; -mod n0074_search_a_2d_matrix; -mod n0075_sort_colors; -mod n0076_minimum_window_substring; -mod n0077_combinations; -mod n0078_subsets; -mod n0079_word_search; -mod n0080_remove_duplicates_from_sorted_array_ii; -mod n0081_search_in_rotated_sorted_array_ii; -mod n0082_remove_duplicates_from_sorted_list_ii; -mod n0083_remove_duplicates_from_sorted_list; -mod n0084_largest_rectangle_in_histogram; -mod n0085_maximal_rectangle; -mod n0086_partition_list; -mod n0087_scramble_string; -mod n0088_merge_sorted_array; -mod n0089_gray_code; -mod n0090_subsets_ii; -mod n0091_decode_ways; -mod n0092_reverse_linked_list_ii; -mod n0093_restore_ip_addresses; -mod n0094_binary_tree_inorder_traversal; -mod n0095_unique_binary_search_trees_ii; -mod n0096_unique_binary_search_trees; -mod n0097_interleaving_string; -mod n0098_validate_binary_search_tree; -mod n0099_recover_binary_search_tree; -mod n0100_same_tree; -mod n0101_symmetric_tree; -mod n0102_binary_tree_level_order_traversal; -mod n0103_binary_tree_zigzag_level_order_traversal; -mod n0104_maximum_depth_of_binary_tree; -mod n0105_construct_binary_tree_from_preorder_and_inorder_traversal; -mod n0106_construct_binary_tree_from_inorder_and_postorder_traversal; -mod n0107_binary_tree_level_order_traversal_ii; -mod n0108_convert_sorted_array_to_binary_search_tree; -mod n0109_convert_sorted_list_to_binary_search_tree; -mod n0110_balanced_binary_tree; -mod n0111_minimum_depth_of_binary_tree; -mod n0112_path_sum; -mod n0113_path_sum_ii; -mod n0114_flatten_binary_tree_to_linked_list; -mod n0115_distinct_subsequences; -mod n0118_pascals_triangle; -mod n0119_pascals_triangle_ii; -mod n0120_triangle; -mod n0121_best_time_to_buy_and_sell_stock; -mod n0122_best_time_to_buy_and_sell_stock_ii; -mod n0123_best_time_to_buy_and_sell_stock_iii; -mod n0124_binary_tree_maximum_path_sum; -mod n0125_valid_palindrome; -mod n0126_word_ladder_ii; -mod n0127_word_ladder; -mod n0128_longest_consecutive_sequence; -mod n0129_sum_root_to_leaf_numbers; -mod n0130_surrounded_regions; -mod n0131_palindrome_partitioning; -mod n0132_palindrome_partitioning_ii; -mod n0134_gas_station; -mod n0135_candy; -mod n0136_single_number; -mod n0137_single_number_ii; -mod n0139_word_break; -mod n0140_word_break_ii; -mod n0143_reorder_list; -mod n0144_binary_tree_preorder_traversal; -mod n0145_binary_tree_postorder_traversal; -mod n0146_lru_cache; -mod n0147_insertion_sort_list; -mod n0148_sort_list; -mod n0149_max_points_on_a_line; -mod n0150_evaluate_reverse_polish_notation; -mod n0151_reverse_words_in_a_string; -mod n0152_maximum_product_subarray; -mod n0153_find_minimum_in_rotated_sorted_array; -mod n0154_find_minimum_in_rotated_sorted_array_ii; -mod n0155_min_stack; -mod n0162_find_peak_element; -mod n0164_maximum_gap; -mod n0165_compare_version_numbers; -mod n0166_fraction_to_recurring_decimal; -mod n0167_two_sum_ii_input_array_is_sorted; -mod n0168_excel_sheet_column_title; -mod n0169_majority_element; -mod n0171_excel_sheet_column_number; -mod n0172_factorial_trailing_zeroes; -mod n0173_binary_search_tree_iterator; -mod n0174_dungeon_game; -mod n0179_largest_number; -mod n0187_repeated_dna_sequences; -mod n0188_best_time_to_buy_and_sell_stock_iv; -mod n0189_rotate_array; -mod n0198_house_robber; -mod n0199_binary_tree_right_side_view; -mod n0200_number_of_islands; -mod n0201_bitwise_and_of_numbers_range; -mod n0202_happy_number; -mod n0203_remove_linked_list_elements; -mod n0204_count_primes; -mod n0205_isomorphic_strings; -mod n0206_reverse_linked_list; -mod n0207_course_schedule; -mod n0208_implement_trie_prefix_tree; -mod n0209_minimum_size_subarray_sum; -mod n0210_course_schedule_ii; -mod n0211_add_and_search_word_data_structure_design; -mod n0212_word_search_ii; -mod n0213_house_robber_ii; -mod n0214_shortest_palindrome; -mod n0215_kth_largest_element_in_an_array; -mod n0216_combination_sum_iii; -mod n0217_contains_duplicate; -mod n0218_the_skyline_problem; -mod n0220_contains_duplicate_iii; -mod n0219_contains_duplicate_ii; -mod n0221_maximal_square; -mod n0223_rectangle_area; -mod n0222_count_complete_tree_nodes; -mod n0224_basic_calculator; -mod n0225_implement_stack_using_queues; -mod n0226_invert_binary_tree; -mod n0227_basic_calculator_ii; -mod n0228_summary_ranges; -mod n0229_majority_element_ii; -mod n0230_kth_smallest_element_in_a_bst; -mod n0231_power_of_two; -mod n0232_implement_queue_using_stacks; -mod n0233_number_of_digit_one; -mod n0238_product_of_array_except_self; -mod n0239_sliding_window_maximum; -mod n0241_different_ways_to_add_parentheses; -mod n0242_valid_anagram; -mod n0257_binary_tree_paths; -mod n0258_add_digits; -mod n0260_single_number_iii; -mod n0263_ugly_number; -mod n0264_ugly_number_ii; -mod n0268_missing_number; -mod n0273_integer_to_english_words; -mod n0274_h_index; -mod n0275_h_index_ii; -mod n0279_perfect_squares; -mod n0282_expression_add_operators; -mod n0283_move_zeroes; -mod n0287_find_the_duplicate_number; +pub mod solution; +pub mod problem; diff --git a/src/main.rs b/src/main.rs index 438c3edc..6fecf106 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,76 +3,244 @@ extern crate serde_derive; #[macro_use] extern crate serde_json; -mod problem; +mod fetcher; +use crate::fetcher::{CodeDefinition, Problem}; +use regex::Regex; use std::env; use std::fs; -use std::path::{Path}; -use std::io::Write; +use std::fs::File; +use std::io; +use std::io::{BufRead, Write}; +use std::path::Path; + +use futures::executor::block_on; +use futures::executor::ThreadPool; +use futures::future::join_all; +use futures::stream::StreamExt; +use futures::task::SpawnExt; +use std::sync::{Arc, Mutex}; /// main() helps to generate the submission template .rs fn main() { - let args: Vec = env::args().collect(); - if args.len() < 2 { - panic!("problem id must be provided"); - } - let id = &args[1]; - let id = id.parse::().expect(&format!("not a number: {}", id)); - - let problem = problem::get_problem(id) - .expect(&format!("problem #{} not found", id)); - let code = problem.code_definition.iter() - .filter(|&d| { d.value == "rust" }) - .next() - .expect("problem has no rust support yet"); - - let file_name = format!("n{:04}_{}", id, problem.title_slug.replace("-", "_")); - let file_path = Path::new("./src").join(format!("{}.rs", file_name)); - if file_path.exists() { - panic!("problem already initialized"); - } + println!("Welcome to leetcode-rust system.\n"); + let mut initialized_ids = get_initialized_ids(); + loop { + println!( + "Please enter a frontend problem id, \n\ + or \"random\" to generate a random one, \n\ + or \"solve $i\" to move problem to solution/, \n\ + or \"all\" to initialize all problems \n" + ); + let mut is_random = false; + let mut is_solving = false; + let mut id: u32 = 0; + let mut id_arg = String::new(); + io::stdin() + .read_line(&mut id_arg) + .expect("Failed to read line"); + let id_arg = id_arg.trim(); - let template = fs::read_to_string("./template.rs").unwrap(); - let source = template - .replace("__PROBLEM_TITLE__", &problem.title) - .replace("__PROBLEM_DESC__", &build_desc(&problem.content)) - .replace("__PROBLEM_DEFAULT_CODE__", &code.default_code) - .replace("__PROBLEM_ID__", &format!("{}", id)) - .replace("__EXTRA_USE__", &parse_extra_use(&code.default_code)); + let random_pattern = Regex::new(r"^random$").unwrap(); + let solving_pattern = Regex::new(r"^solve (\d+)$").unwrap(); + let all_pattern = Regex::new(r"^all$").unwrap(); - let mut file = fs::OpenOptions::new() - .write(true) - .create(true) - .truncate(true) - .open(&file_path) - .unwrap(); + if random_pattern.is_match(id_arg) { + println!("You select random mode."); + id = generate_random_id(&initialized_ids); + is_random = true; + println!("Generate random problem: {}", &id); + } else if solving_pattern.is_match(id_arg) { + // solve a problem + // move it from problem/ to solution/ + is_solving = true; + id = solving_pattern + .captures(id_arg) + .unwrap() + .get(1) + .unwrap() + .as_str() + .parse() + .unwrap(); + deal_solving(&id); + break; + } else if all_pattern.is_match(id_arg) { + // deal all problems + let pool = ThreadPool::new().unwrap(); + let mut tasks = vec![]; + let problems = fetcher::get_problems().unwrap(); + let mut mod_file_addon = Arc::new(Mutex::new(vec![])); + for problem_stat in problems.stat_status_pairs { + if initialized_ids.contains(&problem_stat.stat.frontend_question_id) { + continue; + } + let mod_file_addon = mod_file_addon.clone(); + tasks.push( + pool.spawn_with_handle(async move { + let problem = fetcher::get_problem_async(problem_stat).await; + if problem.is_none() { + return; + } + let problem = problem.unwrap(); + let code = problem + .code_definition + .iter() + .find(|&d| d.value == "rust".to_string()); + if code.is_none() { + println!("Problem {} has no rust version.", problem.question_id); + return; + } + // not sure this can be async + async { + mod_file_addon.lock().unwrap().push(format!( + "mod p{:04}_{};", + problem.question_id, + problem.title_slug.replace("-", "_") + )); + } + .await; + let code = code.unwrap(); + // not sure this can be async + // maybe should use async-std io + async { deal_problem(&problem, &code, false) }.await + }) + .unwrap(), + ); + } + block_on(join_all(tasks)); + let mut lib_file = fs::OpenOptions::new() + .write(true) + .append(true) + .open("./src/problem/mod.rs") + .unwrap(); + writeln!(lib_file, "{}", mod_file_addon.lock().unwrap().join("\n")); + break; + } else { + id = id_arg + .parse::() + .unwrap_or_else(|_| panic!("not a number: {}", id_arg)); + if initialized_ids.contains(&id) { + println!("The problem you chose has been initialized in problem/"); + continue; + } + } - file.write_all(source.as_bytes()).unwrap(); - drop(file); + let problem = fetcher::get_problem(id).unwrap_or_else(|| { + panic!( + "Error: failed to get problem #{} \ + (The problem may be paid-only or may not be exist).", + id + ) + }); + let code = problem + .code_definition + .iter() + .find(|&d| d.value == "rust".to_string()); + if code.is_none() { + println!("Problem {} has no rust version.", &id); + initialized_ids.push(problem.question_id); + continue; + } + let code = code.unwrap(); + deal_problem(&problem, &code, true); + break; + } +} - let mut lib_file = fs::OpenOptions::new() - .write(true) - .append(true) - .open("./src/lib.rs") - .unwrap(); - writeln!(lib_file, "mod {};", file_name); +fn generate_random_id(except_ids: &[u32]) -> u32 { + use rand::Rng; + use std::fs; + let mut rng = rand::thread_rng(); + loop { + let res: u32 = rng.gen_range(1, 1106); + if !except_ids.contains(&res) { + return res; + } + println!( + "Generate a random num ({}), but it is invalid (the problem may have been solved \ + or may have no rust version). Regenerate..", + res + ); + } +} + +fn get_initialized_ids() -> Vec { + let content = fs::read_to_string("./src/problem/mod.rs").unwrap(); + let id_pattern = Regex::new(r"p(\d{4})_").unwrap(); + id_pattern + .captures_iter(&content) + .map(|x| x.get(1).unwrap().as_str().parse().unwrap()) + .collect() } fn parse_extra_use(code: &str) -> String { let mut extra_use_line = String::new(); // a linked-list problem if code.contains("pub struct ListNode") { - extra_use_line.push_str("\nuse super::util::linked_list::{ListNode, to_list};") + extra_use_line.push_str("\nuse crate::util::linked_list::{ListNode, to_list};") } if code.contains("pub struct TreeNode") { - extra_use_line.push_str("\nuse super::util::tree::{TreeNode, to_tree};") + extra_use_line.push_str("\nuse crate::util::tree::{TreeNode, to_tree};") } if code.contains("pub struct Point") { - extra_use_line.push_str("\nuse super::util::point::Point;") + extra_use_line.push_str("\nuse crate::util::point::Point;") } extra_use_line } +fn parse_problem_link(problem: &Problem) -> String { + format!("https://leetcode.com/problems/{}/", problem.title_slug) +} + +fn parse_discuss_link(problem: &Problem) -> String { + format!( + "https://leetcode.com/problems/{}/discuss/?currentPage=1&orderBy=most_votes&query=", + problem.title_slug + ) +} + +fn insert_return_in_code(return_type: &str, code: &str) -> String { + let re = Regex::new(r"\{[ \n]+}").unwrap(); + match return_type { + "ListNode" => re + .replace(&code, "{\n Some(Box::new(ListNode::new(0)))\n }") + .to_string(), + "ListNode[]" => re.replace(&code, "{\n vec![]\n }").to_string(), + "TreeNode" => re + .replace( + &code, + "{\n Some(Rc::new(RefCell::new(TreeNode::new(0))))\n }", + ) + .to_string(), + "boolean" => re.replace(&code, "{\n false\n }").to_string(), + "character" => re.replace(&code, "{\n '0'\n }").to_string(), + "character[][]" => re.replace(&code, "{\n vec![]\n }").to_string(), + "double" => re.replace(&code, "{\n 0f64\n }").to_string(), + "double[]" => re.replace(&code, "{\n vec![]\n }").to_string(), + "int[]" => re.replace(&code, "{\n vec![]\n }").to_string(), + "integer" => re.replace(&code, "{\n 0\n }").to_string(), + "integer[]" => re.replace(&code, "{\n vec![]\n }").to_string(), + "integer[][]" => re.replace(&code, "{\n vec![]\n }").to_string(), + "list" => re.replace(&code, "{\n vec![]\n }").to_string(), + "list" => re.replace(&code, "{\n vec![]\n }").to_string(), + "list" => re.replace(&code, "{\n vec![]\n }").to_string(), + "list" => re.replace(&code, "{\n vec![]\n }").to_string(), + "list" => re.replace(&code, "{\n vec![]\n }").to_string(), + "list>" => re.replace(&code, "{\n vec![]\n }").to_string(), + "list>" => re.replace(&code, "{\n vec![]\n }").to_string(), + "list" => re.replace(&code, "{\n vec![]\n }").to_string(), + "null" => code.to_string(), + "string" => re + .replace(&code, "{\n String::new()\n }") + .to_string(), + "string[]" => re.replace(&code, "{\n vec![]\n }").to_string(), + "void" => code.to_string(), + "NestedInteger" => code.to_string(), + "Node" => code.to_string(), + _ => code.to_string(), + } +} + fn build_desc(content: &str) -> String { // TODO: fix this shit content @@ -107,3 +275,88 @@ fn build_desc(content: &str) -> String { .replace("\n\n", "\n") .replace("\n", "\n * ") } + +fn deal_solving(id: &u32) { + let problem = fetcher::get_problem(*id).unwrap(); + let file_name = format!( + "p{:04}_{}", + problem.question_id, + problem.title_slug.replace("-", "_") + ); + let file_path = Path::new("./src/problem").join(format!("{}.rs", file_name)); + // check problem/ existence + if !file_path.exists() { + panic!("problem does not exist"); + } + // check solution/ no existence + let solution_name = format!( + "s{:04}_{}", + problem.question_id, + problem.title_slug.replace("-", "_") + ); + let solution_path = Path::new("./src/solution").join(format!("{}.rs", solution_name)); + if solution_path.exists() { + panic!("solution exists"); + } + // rename/move file + fs::rename(file_path, solution_path).unwrap(); + // remove from problem/mod.rs + let mod_file = "./src/problem/mod.rs"; + let target_line = format!("mod {};", file_name); + let lines: Vec = io::BufReader::new(File::open(mod_file).unwrap()) + .lines() + .map(|x| x.unwrap()) + .filter(|x| *x != target_line) + .collect(); + fs::write(mod_file, lines.join("\n")); + // insert into solution/mod.rs + let mut lib_file = fs::OpenOptions::new() + .append(true) + .open("./src/solution/mod.rs") + .unwrap(); + writeln!(lib_file, "mod {};", solution_name); +} + +fn deal_problem(problem: &Problem, code: &CodeDefinition, write_mod_file: bool) { + let file_name = format!( + "p{:04}_{}", + problem.question_id, + problem.title_slug.replace("-", "_") + ); + let file_path = Path::new("./src/problem").join(format!("{}.rs", file_name)); + if file_path.exists() { + panic!("problem already initialized"); + } + + let template = fs::read_to_string("./template.rs").unwrap(); + let source = template + .replace("__PROBLEM_TITLE__", &problem.title) + .replace("__PROBLEM_DESC__", &build_desc(&problem.content)) + .replace( + "__PROBLEM_DEFAULT_CODE__", + &insert_return_in_code(&problem.return_type, &code.default_code), + ) + .replace("__PROBLEM_ID__", &format!("{}", problem.question_id)) + .replace("__EXTRA_USE__", &parse_extra_use(&code.default_code)) + .replace("__PROBLEM_LINK__", &parse_problem_link(problem)) + .replace("__DISCUSS_LINK__", &parse_discuss_link(problem)); + + let mut file = fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .open(&file_path) + .unwrap(); + + file.write_all(source.as_bytes()).unwrap(); + drop(file); + + if write_mod_file { + let mut lib_file = fs::OpenOptions::new() + .write(true) + .append(true) + .open("./src/problem/mod.rs") + .unwrap(); + writeln!(lib_file, "mod {};", file_name); + } +} diff --git a/src/n0002_add_two_numbers.rs b/src/n0002_add_two_numbers.rs deleted file mode 100644 index bb0b0da4..00000000 --- a/src/n0002_add_two_numbers.rs +++ /dev/null @@ -1,66 +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 super::util::linked_list::{ListNode, to_list}; - -// 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/n0015_3sum.rs b/src/n0015_3sum.rs deleted file mode 100644 index b62a1a21..00000000 --- a/src/n0015_3sum.rs +++ /dev/null @@ -1,96 +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 {} - -// 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/n0036_valid_sudoku.rs b/src/n0036_valid_sudoku.rs deleted file mode 100644 index 2f8e8284..00000000 --- a/src/n0036_valid_sudoku.rs +++ /dev/null @@ -1,143 +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 {} - -// 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/n0046_permutations.rs b/src/n0046_permutations.rs deleted file mode 100644 index 0a697d8f..00000000 --- a/src/n0046_permutations.rs +++ /dev/null @@ -1,58 +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 {} - -// 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/n0047_permutations_ii.rs b/src/n0047_permutations_ii.rs deleted file mode 100644 index 79ee81c4..00000000 --- a/src/n0047_permutations_ii.rs +++ /dev/null @@ -1,172 +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 {} - -// 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/n0054_spiral_matrix.rs b/src/n0054_spiral_matrix.rs deleted file mode 100644 index b59a9d96..00000000 --- a/src/n0054_spiral_matrix.rs +++ /dev/null @@ -1,87 +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 {} - -// 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/n0059_spiral_matrix_ii.rs b/src/n0059_spiral_matrix_ii.rs deleted file mode 100644 index a443fe47..00000000 --- a/src/n0059_spiral_matrix_ii.rs +++ /dev/null @@ -1,65 +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 {} - -// 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/n0079_word_search.rs b/src/n0079_word_search.rs deleted file mode 100644 index 5c11be33..00000000 --- a/src/n0079_word_search.rs +++ /dev/null @@ -1,106 +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 {} - -// 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/n0097_interleaving_string.rs b/src/n0097_interleaving_string.rs deleted file mode 100644 index 50616f20..00000000 --- a/src/n0097_interleaving_string.rs +++ /dev/null @@ -1,70 +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 {} - -// 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/n0101_symmetric_tree.rs b/src/n0101_symmetric_tree.rs deleted file mode 100644 index e4a3aadb..00000000 --- a/src/n0101_symmetric_tree.rs +++ /dev/null @@ -1,70 +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 super::util::tree::{TreeNode, to_tree}; - -// submission codes start here - -use std::rc::Rc; -use std::cell::RefCell; -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/n0115_distinct_subsequences.rs b/src/n0115_distinct_subsequences.rs deleted file mode 100644 index efac6293..00000000 --- a/src/n0115_distinct_subsequences.rs +++ /dev/null @@ -1,111 +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 {} - -// 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/n0123_best_time_to_buy_and_sell_stock_iii.rs b/src/n0123_best_time_to_buy_and_sell_stock_iii.rs deleted file mode 100644 index 949060d0..00000000 --- a/src/n0123_best_time_to_buy_and_sell_stock_iii.rs +++ /dev/null @@ -1,101 +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 {} - -// 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/n0124_binary_tree_maximum_path_sum.rs b/src/n0124_binary_tree_maximum_path_sum.rs deleted file mode 100644 index 7382e11e..00000000 --- a/src/n0124_binary_tree_maximum_path_sum.rs +++ /dev/null @@ -1,88 +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 super::util::tree::{TreeNode, to_tree}; - -// 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::rc::Rc; -use std::cell::RefCell; -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/n0126_word_ladder_ii.rs b/src/n0126_word_ladder_ii.rs deleted file mode 100644 index e1de6fec..00000000 --- a/src/n0126_word_ladder_ii.rs +++ /dev/null @@ -1,165 +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 {} - -// submission codes start here - -/* - 假如 A 经过一个字符的变换能得到 B, 则认为 A 与 B 之间有通路, 转化为一个 BFS 找无权图最短路径的问题 - - 实现时, 可以先把图构造出来, 复杂度 O(L*N^2) (L 是字符串长度), 也可以每次都回到数组里去找连通点, 时间复杂度不变 - - 由于要记录所有的路径, 因此我们需要把每个点的可能前置节点都记录下来, 最后用一个 DFS 或 BFS 找出所有路径 - - 暂时想不到更好的办法 - */ - -use std::collections::VecDeque; -use std::collections::HashSet; -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/n0128_longest_consecutive_sequence.rs b/src/n0128_longest_consecutive_sequence.rs deleted file mode 100644 index 737c4568..00000000 --- a/src/n0128_longest_consecutive_sequence.rs +++ /dev/null @@ -1,61 +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 {} - -// 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/n0130_surrounded_regions.rs b/src/n0130_surrounded_regions.rs deleted file mode 100644 index e4718d0a..00000000 --- a/src/n0130_surrounded_regions.rs +++ /dev/null @@ -1,170 +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 {} - -// 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/n0131_palindrome_partitioning.rs b/src/n0131_palindrome_partitioning.rs deleted file mode 100644 index 3c976271..00000000 --- a/src/n0131_palindrome_partitioning.rs +++ /dev/null @@ -1,105 +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 {} - -// 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/n0148_sort_list.rs b/src/n0148_sort_list.rs deleted file mode 100644 index 1ab84ac5..00000000 --- a/src/n0148_sort_list.rs +++ /dev/null @@ -1,107 +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 super::util::linked_list::{ListNode, to_list}; - -// 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/n0149_max_points_on_a_line.rs b/src/n0149_max_points_on_a_line.rs deleted file mode 100644 index 35b8e744..00000000 --- a/src/n0149_max_points_on_a_line.rs +++ /dev/null @@ -1,138 +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 super::util::point::Point; - -/* - 要回顾下高中数学:已知两点, 求解一般式: - - * 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::HashSet; -use std::collections::HashMap; -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/n0169_majority_element.rs b/src/n0169_majority_element.rs deleted file mode 100644 index dddaf659..00000000 --- a/src/n0169_majority_element.rs +++ /dev/null @@ -1,70 +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 {} - -// 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/n0179_largest_number.rs b/src/n0179_largest_number.rs deleted file mode 100644 index 4385d85e..00000000 --- a/src/n0179_largest_number.rs +++ /dev/null @@ -1,50 +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 {} - -// 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/n0188_best_time_to_buy_and_sell_stock_iv.rs b/src/n0188_best_time_to_buy_and_sell_stock_iv.rs deleted file mode 100644 index a70b1f02..00000000 --- a/src/n0188_best_time_to_buy_and_sell_stock_iv.rs +++ /dev/null @@ -1,98 +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 {} - -// 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/n0221_maximal_square.rs b/src/n0221_maximal_square.rs deleted file mode 100644 index 10226731..00000000 --- a/src/n0221_maximal_square.rs +++ /dev/null @@ -1,78 +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 {} - -// 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/problem/mod.rs b/src/problem/mod.rs new file mode 100644 index 00000000..e69de29b diff --git a/src/solution/mod.rs b/src/solution/mod.rs new file mode 100644 index 00000000..bc982de9 --- /dev/null +++ b/src/solution/mod.rs @@ -0,0 +1,237 @@ +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; diff --git a/src/n0001_two_sum.rs b/src/solution/s0001_two_sum.rs similarity index 75% rename from src/n0001_two_sum.rs rename to src/solution/s0001_two_sum.rs index 92e23909..4a44a732 100644 --- a/src/n0001_two_sum.rs +++ b/src/solution/s0001_two_sum.rs @@ -18,6 +18,9 @@ */ pub struct Solution {} +// problem: https://leetcode.com/problems/two-sum/ +// discuss: https://leetcode.com/problems/two-sum/discuss/?currentPage=1&orderBy=most_votes&query= + // submission codes start here use std::collections::HashMap; @@ -26,8 +29,10 @@ impl Solution { let mut map = HashMap::with_capacity(nums.len()); for (index, num) in nums.iter().enumerate() { match map.get(&(target - num)) { - None => { map.insert(num, index); }, - Some(sub_index) => { return vec![*sub_index as i32, index as i32] }, + None => { + map.insert(num, index); + } + Some(sub_index) => return vec![*sub_index as i32, index as i32], } } vec![] diff --git a/src/solution/s0002_add_two_numbers.rs b/src/solution/s0002_add_two_numbers.rs new file mode 100644 index 00000000..d8bfc2d8 --- /dev/null +++ b/src/solution/s0002_add_two_numbers.rs @@ -0,0 +1,98 @@ +/** + * [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/n0003_longest_substring.rs b/src/solution/s0003_longest_substring_without_repeating_characters.rs similarity index 63% rename from src/n0003_longest_substring.rs rename to src/solution/s0003_longest_substring_without_repeating_characters.rs index fc3366d1..0ad6903d 100644 --- a/src/n0003_longest_substring.rs +++ b/src/solution/s0003_longest_substring_without_repeating_characters.rs @@ -12,6 +12,9 @@ */ 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 { @@ -24,11 +27,13 @@ impl Solution { for idx in start..end { if seq[end] == seq[idx] { start = idx + 1; - break + break; } } let curr = end - start + 1; - if curr > max { max = curr } + if curr > max { + max = curr + } end += 1 } max as i32 @@ -43,8 +48,14 @@ mod tests { #[test] fn test_3() { - assert_eq!(Solution::length_of_longest_substring("abcabcbb".to_string()), 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); + assert_eq!( + Solution::length_of_longest_substring("pwwkew".to_string()), + 3 + ); } } diff --git a/src/n0004_median_of_two_sorted_arrays.rs b/src/solution/s0004_median_of_two_sorted_arrays.rs similarity index 62% rename from src/n0004_median_of_two_sorted_arrays.rs rename to src/solution/s0004_median_of_two_sorted_arrays.rs index 96d51619..e3c2d014 100644 --- a/src/n0004_median_of_two_sorted_arrays.rs +++ b/src/solution/s0004_median_of_two_sorted_arrays.rs @@ -2,32 +2,35 @@ * [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. - * + * * Example 1: - * + * * * nums1 = [1, 3] * nums2 = [2] - * + * * The median is 2.0 - * - * + * + * * Example 2: - * - * + * + * * nums1 = [1, 2] * nums2 = [3, 4] - * + * * The median is (2 + 3)/2 = 2.5 - * - * + * + * */ 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= + // submission codes start here // TODO: nth slice @@ -47,7 +50,13 @@ mod tests { #[test] #[ignore] fn test_4() { - 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); + 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/n0005_longest_palindromic_substring.rs b/src/solution/s0005_longest_palindromic_substring.rs similarity index 71% rename from src/n0005_longest_palindromic_substring.rs rename to src/solution/s0005_longest_palindromic_substring.rs index f48ebd86..675e1951 100644 --- a/src/n0005_longest_palindromic_substring.rs +++ b/src/solution/s0005_longest_palindromic_substring.rs @@ -2,18 +2,18 @@ * [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" * @@ -21,34 +21,46 @@ */ 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} + 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 }; + 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; + 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; + curr_len = max_len; + curr_start = i; + curr_end = j; } if max_len >= len - 1 { break; } } - s[curr_start..curr_end+1].to_owned() + s[curr_start..curr_end + 1].to_owned() } } diff --git a/src/n0006_zigzag_conversion.rs b/src/solution/s0006_zigzag_conversion.rs similarity index 77% rename from src/n0006_zigzag_conversion.rs rename to src/solution/s0006_zigzag_conversion.rs index 30d90490..51ed13a7 100644 --- a/src/n0006_zigzag_conversion.rs +++ b/src/solution/s0006_zigzag_conversion.rs @@ -2,42 +2,45 @@ * [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 { @@ -78,8 +81,14 @@ mod tests { #[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("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"); } diff --git a/src/n0007_reverse_integer.rs b/src/solution/s0007_reverse_integer.rs similarity index 85% rename from src/n0007_reverse_integer.rs rename to src/solution/s0007_reverse_integer.rs index 9810cf5a..ad89eebd 100644 --- a/src/n0007_reverse_integer.rs +++ b/src/solution/s0007_reverse_integer.rs @@ -2,34 +2,37 @@ * [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 { @@ -38,7 +41,7 @@ impl Solution { let mut digit: i64 = 0; let base: i64 = 2; let upper_bound: i64 = base.pow(31) - 1; - let lower_bound: i64 = - base.pow(31); + let lower_bound: i64 = -base.pow(31); while input != 0 { digit = input % 10; result = result * 10 + digit; diff --git a/src/n0008_string_to_integer_atoi.rs b/src/solution/s0008_string_to_integer_atoi.rs similarity index 75% rename from src/n0008_string_to_integer_atoi.rs rename to src/solution/s0008_string_to_integer_atoi.rs index cabb68bb..9c86e17b 100644 --- a/src/n0008_string_to_integer_atoi.rs +++ b/src/solution/s0008_string_to_integer_atoi.rs @@ -2,65 +2,68 @@ * [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 + * 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= + // submission codes start here impl Solution { @@ -73,28 +76,39 @@ impl Solution { for ch in input.chars().into_iter() { if !num_matched { match ch { - ' ' => {}, - '0'...'9' => { + ' ' => {} + '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 + } + '-' => { + num_matched = true; + minus = true; + } + '+' => { + num_matched = true; + } + _ => return 0, } } else { match ch { - '0'...'9' => { + '0'..='9' => { result = result * 10 + ch.to_digit(10).unwrap() as i64; - if result > i32_max { break } - }, - _ => break + 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; } + if result > i32_max { + return i32_max as i32; + } + if result < i32_min { + return i32_min as i32; + } return result as i32; } } diff --git a/src/n0009_palindrome_number.rs b/src/solution/s0009_palindrome_number.rs similarity index 76% rename from src/n0009_palindrome_number.rs rename to src/solution/s0009_palindrome_number.rs index 7f85c1e6..255eeed1 100644 --- a/src/n0009_palindrome_number.rs +++ b/src/solution/s0009_palindrome_number.rs @@ -2,43 +2,48 @@ * [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 } + if x < 0 { + return false; + } let mut digits: Vec = Vec::new(); let mut input = x; while input != 0 { @@ -47,13 +52,17 @@ impl Solution { } let len = digits.len(); // handle one digit - if len < 2 { return true } + if len < 2 { + return true; + } // handle end with 0 - if digits[0] == 0 { return false } + if digits[0] == 0 { + return false; + } let mut i = 0; while i < len / 2 { if digits[i] != digits[len - 1 - i] { - return false + return false; } i += 1; } diff --git a/src/n0010_regular_expression_matching.rs b/src/solution/s0010_regular_expression_matching.rs similarity index 78% rename from src/n0010_regular_expression_matching.rs rename to src/solution/s0010_regular_expression_matching.rs index 15607125..13e15cb7 100644 --- a/src/n0010_regular_expression_matching.rs +++ b/src/solution/s0010_regular_expression_matching.rs @@ -2,73 +2,76 @@ * [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 @@ -85,6 +88,5 @@ mod tests { use super::*; #[test] - fn test_10() { - } + fn test_10() {} } diff --git a/src/n0011_container_with_most_water.rs b/src/solution/s0011_container_with_most_water.rs similarity index 76% rename from src/n0011_container_with_most_water.rs rename to src/solution/s0011_container_with_most_water.rs index 8f7177dd..ae818bac 100644 --- a/src/n0011_container_with_most_water.rs +++ b/src/solution/s0011_container_with_most_water.rs @@ -2,26 +2,29 @@ * [11] 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. - * + * * Note: You may not slant the container and n is at least 2. - * + * * - * + * * - * + * * The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. - * + * * - * + * * Example: - * - * + * + * * Input: [1,8,6,2,5,4,8,3,7] * Output: 49 - * + * */ 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) @@ -36,20 +39,30 @@ impl Solution { // move the lower one if height[start] < height[end] { start += 1; - if height[start] < height[start - 1] { continue } + if height[start] < height[start - 1] { + continue; + } } else { end -= 1; - if height[end] < height[end + 1] { continue } + if height[end] < height[end + 1] { + continue; + } } curr_area = (end - start) as i32 * Solution::min(height[start], height[end]); - if curr_area > max { max = curr_area } + if curr_area > max { + max = curr_area + } } max } #[inline(always)] fn min(i: i32, j: i32) -> i32 { - if i > j { j } else { i } + if i > j { + j + } else { + i + } } } diff --git a/src/n0012_integer_to_roman.rs b/src/solution/s0012_integer_to_roman.rs similarity index 85% rename from src/n0012_integer_to_roman.rs rename to src/solution/s0012_integer_to_roman.rs index 2c39e5b6..b32592c7 100644 --- a/src/n0012_integer_to_roman.rs +++ b/src/solution/s0012_integer_to_roman.rs @@ -2,8 +2,8 @@ * [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 @@ -12,59 +12,61 @@ * 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. + * + * + * 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= + // submission codes start here impl Solution { - pub fn int_to_roman(num: i32) -> String { let table: Vec<(i32, &'static str)> = vec![ (1000, "M"), @@ -79,7 +81,7 @@ impl Solution { (9, "IX"), (5, "V"), (4, "IV"), - (1, "I") + (1, "I"), ]; let mut num = num; diff --git a/src/n0013_roman_to_integer.rs b/src/solution/s0013_roman_to_integer.rs similarity index 82% rename from src/n0013_roman_to_integer.rs rename to src/solution/s0013_roman_to_integer.rs index 8566d1a9..4f3f0ae4 100644 --- a/src/n0013_roman_to_integer.rs +++ b/src/solution/s0013_roman_to_integer.rs @@ -2,8 +2,8 @@ * [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 @@ -12,55 +12,58 @@ * 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. + * + * + * 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 { @@ -78,16 +81,16 @@ impl Solution { (9, "IX"), (5, "V"), (4, "IV"), - (1, "I") + (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()] { + 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 + return sum; } } } diff --git a/src/n0014_longest_common_prefix.rs b/src/solution/s0014_longest_common_prefix.rs similarity index 60% rename from src/n0014_longest_common_prefix.rs rename to src/solution/s0014_longest_common_prefix.rs index 2cdd344f..1c5fd985 100644 --- a/src/n0014_longest_common_prefix.rs +++ b/src/solution/s0014_longest_common_prefix.rs @@ -1,54 +1,58 @@ - /** * [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 iters: Vec = strs.iter().map(|s| s.chars()).collect(); let mut curr_char: Option = None; - if strs.len() < 1 { return prefix } + 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 + return prefix; } match curr_char { None => curr_char = ch.take(), Some(curr) => { if curr != ch.unwrap() { - return prefix + return prefix; } } } @@ -65,12 +69,22 @@ mod tests { #[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![ + "".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 new file mode 100644 index 00000000..9feb3cd0 --- /dev/null +++ b/src/solution/s0015_3sum.rs @@ -0,0 +1,143 @@ +/** + * [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/n0016_3sum_closest.rs b/src/solution/s0016_3sum_closest.rs similarity index 69% rename from src/n0016_3sum_closest.rs rename to src/solution/s0016_3sum_closest.rs index f4f34dd7..01cf442d 100644 --- a/src/n0016_3sum_closest.rs +++ b/src/solution/s0016_3sum_closest.rs @@ -2,18 +2,21 @@ * [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 { @@ -23,10 +26,12 @@ impl Solution { 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]); + 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 } + if min_distance == 0 { + break; + } } i += 1; } @@ -38,9 +43,13 @@ impl Solution { 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 { + j -= 1; + } else if sum < target { + i += 1; + } else { + return 0; + } if (sum - target).abs() < local_min.abs() { local_min = sum - target } @@ -59,6 +68,9 @@ mod tests { 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); + assert_eq!( + Solution::three_sum_closest(vec![1, 2, 4, 8, 16, 32, 64, 128], 82), + 82 + ); } } diff --git a/src/n0017_letter_combinations_of_a_phone_number.rs b/src/solution/s0017_letter_combinations_of_a_phone_number.rs similarity index 69% rename from src/n0017_letter_combinations_of_a_phone_number.rs rename to src/solution/s0017_letter_combinations_of_a_phone_number.rs index b0dd49b5..7d3245f4 100644 --- a/src/n0017_letter_combinations_of_a_phone_number.rs +++ b/src/solution/s0017_letter_combinations_of_a_phone_number.rs @@ -2,25 +2,28 @@ * [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 { @@ -28,11 +31,19 @@ impl Solution { // '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']) + ('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![] } + 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; @@ -62,6 +73,9 @@ mod tests { #[test] fn test_17() { - assert_eq!(Solution::letter_combinations("23".to_string()), ["cf", "af", "bf", "cd", "ce", "ad", "ae", "bd", "be"]); + assert_eq!( + Solution::letter_combinations("23".to_string()), + ["cf", "af", "bf", "cd", "ce", "ad", "ae", "bd", "be"] + ); } } diff --git a/src/n0018_4sum.rs b/src/solution/s0018_4sum.rs similarity index 67% rename from src/n0018_4sum.rs rename to src/solution/s0018_4sum.rs index ac6561fe..d832aef1 100644 --- a/src/n0018_4sum.rs +++ b/src/solution/s0018_4sum.rs @@ -2,27 +2,30 @@ * [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 @@ -32,19 +35,25 @@ 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![] } + 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)); + 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; } + if sum > target / 2 { + break; + } match map.get(&(target - sum)) { None => continue, // 2-sum + 2-sum == target, then all the possible combination @@ -52,10 +61,15 @@ impl Solution { 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 + 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]]; + let mut vec = + vec![nums[pair.0], nums[pair.1], nums[sub.0], nums[sub.1]]; vec.sort(); set.insert(vec); } @@ -77,10 +91,9 @@ mod tests { #[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] - ]); + 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/n0019_remove_nth_node_from_end_of_list.rs b/src/solution/s0019_remove_nth_node_from_end_of_list.rs similarity index 73% rename from src/n0019_remove_nth_node_from_end_of_list.rs rename to src/solution/s0019_remove_nth_node_from_end_of_list.rs index e064852f..c3f53a32 100644 --- a/src/n0019_remove_nth_node_from_end_of_list.rs +++ b/src/solution/s0019_remove_nth_node_from_end_of_list.rs @@ -1,28 +1,30 @@ - /** * [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 super::util::linked_list::{ListNode, to_list}; +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 @@ -30,9 +32,7 @@ use super::util::linked_list::{ListNode, to_list}; // 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 dummy_head = Some(Box::new(ListNode { val: 0, next: head })); let mut len = 0; { let mut p = dummy_head.as_ref(); @@ -62,9 +62,10 @@ mod tests { #[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); + 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/n0020_valid_parentheses.rs b/src/solution/s0020_valid_parentheses.rs similarity index 71% rename from src/n0020_valid_parentheses.rs rename to src/solution/s0020_valid_parentheses.rs index 69b28393..3c0940b9 100644 --- a/src/n0020_valid_parentheses.rs +++ b/src/solution/s0020_valid_parentheses.rs @@ -2,54 +2,57 @@ * [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 { @@ -57,13 +60,13 @@ impl Solution { let mut stack: Vec = Vec::new(); for ch in s.chars().into_iter() { match stack.last() { - None => {}, + None => {} Some(&last) => { if Solution::pair(last, ch) { stack.pop(); - continue + continue; } - }, + } } stack.push(ch); } @@ -72,9 +75,9 @@ impl Solution { #[inline(always)] fn pair(open: char, close: char) -> bool { - (open == '{' && close == '}') || - (open == '(' && close == ')') || - (open == '[' && close == ']') + (open == '{' && close == '}') + || (open == '(' && close == ')') + || (open == '[' && close == ']') } } diff --git a/src/n0021_merge_two_sorted_lists.rs b/src/solution/s0021_merge_two_sorted_lists.rs similarity index 60% rename from src/n0021_merge_two_sorted_lists.rs rename to src/solution/s0021_merge_two_sorted_lists.rs index b8d26180..54d7f256 100644 --- a/src/n0021_merge_two_sorted_lists.rs +++ b/src/solution/s0021_merge_two_sorted_lists.rs @@ -2,39 +2,47 @@ * [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 super::util::linked_list::{ListNode, to_list}; +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, - })); + 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; + head.as_mut().unwrap().next = l2; + break; } else if l2.is_none() { - head.as_mut().unwrap().next = l1; break; + 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 + l1 = origin; + next } else { let (origin, next) = Solution::take_head(l2); - l2 = origin; next + l2 = origin; + next }; head.as_mut().unwrap().next = next; head = &mut head.as_mut().unwrap().next; @@ -59,6 +67,9 @@ mod tests { #[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])); + 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/n0022_generate_parentheses.rs b/src/solution/s0022_generate_parentheses.rs similarity index 75% rename from src/n0022_generate_parentheses.rs rename to src/solution/s0022_generate_parentheses.rs index d8fefa65..9e0e33df 100644 --- a/src/n0022_generate_parentheses.rs +++ b/src/solution/s0022_generate_parentheses.rs @@ -1,14 +1,14 @@ /** * [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: - * - * + * + * * [ * "((()))", * "(()())", @@ -16,16 +16,21 @@ * "()(())", * "()()()" * ] - * + * */ 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![] } + if n < 1 { + return vec![]; + } let mut result = Vec::new(); Solution::dfs(n, 0, 0, &mut result, String::new()); result @@ -57,14 +62,11 @@ mod tests { #[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![ - "((()))", - "(()())", - "(())()", - "()(())", - "()()()" - ] ); + 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/n0023_merge_k_sorted_lists.rs b/src/solution/s0023_merge_k_sorted_lists.rs similarity index 62% rename from src/n0023_merge_k_sorted_lists.rs rename to src/solution/s0023_merge_k_sorted_lists.rs index 8c292094..eeaf3695 100644 --- a/src/n0023_merge_k_sorted_lists.rs +++ b/src/solution/s0023_merge_k_sorted_lists.rs @@ -2,10 +2,10 @@ * [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, @@ -13,15 +13,18 @@ * 2->6 * ] * Output: 1->1->2->3->4->4->5->6 - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +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::collections::BinaryHeap; use std::cmp::Ordering; +use std::collections::BinaryHeap; // head value and the index struct Node(i32, usize); @@ -48,17 +51,22 @@ 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)))); + 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> { + 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)))); + next.as_ref() + .and_then(|n| Some(heap.push(Node(n.val, node.1)))); lists[node.1] = next; - Box::new(ListNode{ + Box::new(ListNode { val: node.0, next: Solution::next(lists, heap), }) @@ -74,16 +82,14 @@ mod tests { #[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]), + 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 + to_list(vec![1, 1, 2, 3, 4, 4, 5, 6]) ); + assert_eq!(Solution::merge_k_lists(vec![]), None); } } diff --git a/src/n0024_swap_nodes_in_pairs.rs b/src/solution/s0024_swap_nodes_in_pairs.rs similarity index 70% rename from src/n0024_swap_nodes_in_pairs.rs rename to src/solution/s0024_swap_nodes_in_pairs.rs index c9401bd5..4a6deb3e 100644 --- a/src/n0024_swap_nodes_in_pairs.rs +++ b/src/solution/s0024_swap_nodes_in_pairs.rs @@ -2,32 +2,37 @@ * [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 super::util::linked_list::{ListNode, to_list}; +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 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 } + 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() { @@ -54,9 +59,15 @@ mod tests { #[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![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, 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/n0025_reverse_nodes_in_k_group.rs b/src/solution/s0025_reverse_nodes_in_k_group.rs similarity index 63% rename from src/n0025_reverse_nodes_in_k_group.rs rename to src/solution/s0025_reverse_nodes_in_k_group.rs index 6e8c21f0..5d39cd1e 100644 --- a/src/n0025_reverse_nodes_in_k_group.rs +++ b/src/solution/s0025_reverse_nodes_in_k_group.rs @@ -2,46 +2,51 @@ * [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 super::util::linked_list::{ListNode, to_list}; +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 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 } + if start.is_none() { + break 'outer; + } let mut end = start.as_mut(); - for _ in 0..(k-1) { + for _ in 0..(k - 1) { end = end.unwrap().next.as_mut(); if end.is_none() { head.as_mut().unwrap().next = start; - break 'outer + break 'outer; } } let mut tail = end.as_mut().unwrap().next.take(); @@ -57,7 +62,10 @@ impl Solution { } #[inline(always)] - fn reverse(mut head: Option>, tail: Option>) -> Option> { + fn reverse( + mut head: Option>, + tail: Option>, + ) -> Option> { let mut prev = tail; let mut current = head; while let Some(mut current_node_inner) = current { @@ -78,13 +86,21 @@ mod tests { #[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])); + 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/n0026_remove_duplicates_from_sorted_array.rs b/src/solution/s0026_remove_duplicates_from_sorted_array.rs similarity index 80% rename from src/n0026_remove_duplicates_from_sorted_array.rs rename to src/solution/s0026_remove_duplicates_from_sorted_array.rs index c5794fac..286b7c54 100644 --- a/src/n0026_remove_duplicates_from_sorted_array.rs +++ b/src/solution/s0026_remove_duplicates_from_sorted_array.rs @@ -2,49 +2,52 @@ * [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 { @@ -60,6 +63,7 @@ impl Solution { nums[slow] = nums[fast]; } } + nums.truncate(slow + 1); (slow + 1) as i32 } } @@ -73,11 +77,11 @@ mod tests { #[test] fn test_26() { assert_eq!(Solution::remove_duplicates(&mut vec![]), 0); - let mut vec1 = vec![1,1,1,1,3]; + 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!(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]); + assert_eq!(vec2, vec![1, 2]); } } diff --git a/src/n0027_remove_element.rs b/src/solution/s0027_remove_element.rs similarity index 73% rename from src/n0027_remove_element.rs rename to src/solution/s0027_remove_element.rs index a5668734..7144d3e9 100644 --- a/src/n0027_remove_element.rs +++ b/src/solution/s0027_remove_element.rs @@ -2,62 +2,67 @@ * [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); + 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]; + nums[start] = nums[end - 1]; end -= 1; } else { start += 1; @@ -75,12 +80,18 @@ mod tests { #[test] fn test_27() { - let mut vec1 = vec![0,1,2,2,3,0,4,2]; + 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!(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, 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/n0028_implement_strstr.rs b/src/solution/s0028_implement_strstr.rs similarity index 82% rename from src/n0028_implement_strstr.rs rename to src/solution/s0028_implement_strstr.rs index 62000791..e0d944ee 100644 --- a/src/n0028_implement_strstr.rs +++ b/src/solution/s0028_implement_strstr.rs @@ -2,37 +2,42 @@ * [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 } + if needle.is_empty() { + return 0; + } haystack.find(&needle).map_or(-1_i32, |v| v as i32) } } diff --git a/src/n0029_divide_two_integers.rs b/src/solution/s0029_divide_two_integers.rs similarity index 80% rename from src/n0029_divide_two_integers.rs rename to src/solution/s0029_divide_two_integers.rs index 2e1c9699..e8f13435 100644 --- a/src/n0029_divide_two_integers.rs +++ b/src/solution/s0029_divide_two_integers.rs @@ -2,34 +2,37 @@ * [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 { @@ -45,6 +48,5 @@ mod tests { use super::*; #[test] - fn test_29() { - } + fn test_29() {} } diff --git a/src/n0030_substring_with_concatenation_of_all_words.rs b/src/solution/s0030_substring_with_concatenation_of_all_words.rs similarity index 58% rename from src/n0030_substring_with_concatenation_of_all_words.rs rename to src/solution/s0030_substring_with_concatenation_of_all_words.rs index 81dd6e5f..002ae9a3 100644 --- a/src/n0030_substring_with_concatenation_of_all_words.rs +++ b/src/solution/s0030_substring_with_concatenation_of_all_words.rs @@ -2,30 +2,33 @@ * [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, @@ -33,7 +36,7 @@ struct Term { } impl Term { fn new(expect: i32, count: i32) -> Self { - Term{expect, count} + Term { expect, count } } fn inc_expect(&mut self) { self.expect += 1; @@ -52,14 +55,18 @@ impl Term { } } -use std::collections::HashMap; 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![] } + if words.len() < 1 { + return vec![]; + } let word_len = words[0].len(); - if word_len < 1 { return vec![] } + 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() { @@ -72,16 +79,18 @@ impl Solution { 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]) { + 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]; + 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 } + if term == &s[j..j + word_len] { + break; + } } j += word_len; } else { @@ -91,16 +100,18 @@ impl Solution { // 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; + 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; - }, + j += word_len; + i = j; + } } } map.iter_mut().for_each(|(_, v)| v.reset()) @@ -117,16 +128,48 @@ mod tests { #[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]); + 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/n0031_next_permutation.rs b/src/solution/s0031_next_permutation.rs similarity index 83% rename from src/n0031_next_permutation.rs rename to src/solution/s0031_next_permutation.rs index 39e615d9..b448dfa1 100644 --- a/src/n0031_next_permutation.rs +++ b/src/solution/s0031_next_permutation.rs @@ -2,20 +2,23 @@ * [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 { @@ -43,7 +46,7 @@ impl Solution { j -= 1; } } - let slice = &mut nums[((i+1) as usize)..len]; + let slice = &mut nums[((i + 1) as usize)..len]; slice.reverse(); } } @@ -75,12 +78,12 @@ mod tests { #[test] fn test_31() { - let mut vec1 = vec![1,2,3,4,5]; + let mut vec1 = vec![1, 2, 3, 4, 5]; Solution::next_permutation(&mut vec1); - assert_eq!(vec1, vec![1,2,3,5,4]); + assert_eq!(vec1, vec![1, 2, 3, 5, 4]); - let mut vec2 = vec![5,4,3,2,1]; + let mut vec2 = vec![5, 4, 3, 2, 1]; Solution::next_permutation(&mut vec2); - assert_eq!(vec2, vec![1,2,3,4,5]); + assert_eq!(vec2, vec![1, 2, 3, 4, 5]); } } diff --git a/src/n0032_longest_valid_parentheses.rs b/src/solution/s0032_longest_valid_parentheses.rs similarity index 74% rename from src/n0032_longest_valid_parentheses.rs rename to src/solution/s0032_longest_valid_parentheses.rs index c098bfba..d970de2b 100644 --- a/src/n0032_longest_valid_parentheses.rs +++ b/src/solution/s0032_longest_valid_parentheses.rs @@ -2,26 +2,29 @@ * [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) @@ -69,12 +72,24 @@ mod tests { 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()), + 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()), + 10 + ); + assert_eq!( + Solution::longest_valid_parentheses("(()(((()".to_string()), + 2 + ); assert_eq!(Solution::longest_valid_parentheses("".to_string()), 0); } } diff --git a/src/n0033_search_in_rotated_sorted_array.rs b/src/solution/s0033_search_in_rotated_sorted_array.rs similarity index 92% rename from src/n0033_search_in_rotated_sorted_array.rs rename to src/solution/s0033_search_in_rotated_sorted_array.rs index 968199f5..ab5c13d3 100644 --- a/src/n0033_search_in_rotated_sorted_array.rs +++ b/src/solution/s0033_search_in_rotated_sorted_array.rs @@ -37,6 +37,9 @@ pub struct Solution {} 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 { diff --git a/src/n0034_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 similarity index 71% rename from src/n0034_find_first_and_last_position_of_element_in_sorted_array.rs rename to src/solution/s0034_find_first_and_last_position_of_element_in_sorted_array.rs index 2b1a5ba2..eba1c01c 100644 --- a/src/n0034_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 @@ -2,26 +2,29 @@ * [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 @@ -38,6 +41,5 @@ mod tests { use super::*; #[test] - fn test_34() { - } + fn test_34() {} } diff --git a/src/n0035_search_insert_position.rs b/src/solution/s0035_search_insert_position.rs similarity index 68% rename from src/n0035_search_insert_position.rs rename to src/solution/s0035_search_insert_position.rs index 7eba236a..31c1c38b 100644 --- a/src/n0035_search_insert_position.rs +++ b/src/solution/s0035_search_insert_position.rs @@ -2,40 +2,43 @@ * [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 @@ -52,6 +55,5 @@ mod tests { use super::*; #[test] - fn test_35() { - } + fn test_35() {} } diff --git a/src/solution/s0036_valid_sudoku.rs b/src/solution/s0036_valid_sudoku.rs new file mode 100644 index 00000000..5a595774 --- /dev/null +++ b/src/solution/s0036_valid_sudoku.rs @@ -0,0 +1,172 @@ +/** + * [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/n0037_sudoku_solver.rs b/src/solution/s0037_sudoku_solver.rs similarity index 80% rename from src/n0037_sudoku_solver.rs rename to src/solution/s0037_sudoku_solver.rs index 245050a3..d0187582 100644 --- a/src/n0037_sudoku_solver.rs +++ b/src/solution/s0037_sudoku_solver.rs @@ -2,41 +2,42 @@ * [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>) { - - } + pub fn solve_sudoku(board: &mut Vec>) {} } // submission codes end @@ -46,6 +47,5 @@ mod tests { use super::*; #[test] - fn test_37() { - } + fn test_37() {} } diff --git a/src/n0038_count_and_say.rs b/src/solution/s0038_count_and_say.rs similarity index 83% rename from src/n0038_count_and_say.rs rename to src/solution/s0038_count_and_say.rs index 08e48633..6305b2a5 100644 --- a/src/n0038_count_and_say.rs +++ b/src/solution/s0038_count_and_say.rs @@ -2,48 +2,51 @@ * [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 { + for _ in 0..n - 1 { let mut temp = Vec::new(); let mut i = 0_usize; while i < res.len() { diff --git a/src/n0039_combination_sum.rs b/src/solution/s0039_combination_sum.rs similarity index 58% rename from src/n0039_combination_sum.rs rename to src/solution/s0039_combination_sum.rs index 94c10dd3..b31e397e 100644 --- a/src/n0039_combination_sum.rs +++ b/src/solution/s0039_combination_sum.rs @@ -2,30 +2,30 @@ * [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: * [ @@ -33,32 +33,43 @@ * [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) }); + 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) { + 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 } + if target - item < 0 { + continue; + } let mut new_vec = curr.clone(); new_vec.push(item); if target == item { result.push(new_vec); - } else { + } else { Solution::backtrack(seq, target - item, new_vec, result, i); } } @@ -73,17 +84,17 @@ mod tests { #[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], - ]); + 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/n0040_combination_sum_ii.rs b/src/solution/s0040_combination_sum_ii.rs similarity index 89% rename from src/n0040_combination_sum_ii.rs rename to src/solution/s0040_combination_sum_ii.rs index a4a63011..0445bfb9 100644 --- a/src/n0040_combination_sum_ii.rs +++ b/src/solution/s0040_combination_sum_ii.rs @@ -39,6 +39,9 @@ */ 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 { diff --git a/src/n0041_first_missing_positive.rs b/src/solution/s0041_first_missing_positive.rs similarity index 52% rename from src/n0041_first_missing_positive.rs rename to src/solution/s0041_first_missing_positive.rs index 210d8b9c..80cd8d8e 100644 --- a/src/n0041_first_missing_positive.rs +++ b/src/solution/s0041_first_missing_positive.rs @@ -2,35 +2,38 @@ * [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 { @@ -53,10 +56,10 @@ impl Solution { println!("{}", c); for (i, &num) in nums.iter().enumerate() { if num != ((i + 1) as i32) { - return (i+1) as i32 + return (i + 1) as i32; } } - return (len + 1) as i32 + return (len + 1) as i32; } } @@ -68,12 +71,21 @@ mod tests { #[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); + 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/n0042_trapping_rain_water.rs b/src/solution/s0042_trapping_rain_water.rs similarity index 79% rename from src/n0042_trapping_rain_water.rs rename to src/solution/s0042_trapping_rain_water.rs index 02fce508..9d961994 100644 --- a/src/n0042_trapping_rain_water.rs +++ b/src/solution/s0042_trapping_rain_water.rs @@ -2,19 +2,22 @@ * [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 @@ -31,6 +34,5 @@ mod tests { use super::*; #[test] - fn test_42() { - } + fn test_42() {} } diff --git a/src/n0043_multiply_strings.rs b/src/solution/s0043_multiply_strings.rs similarity index 78% rename from src/n0043_multiply_strings.rs rename to src/solution/s0043_multiply_strings.rs index 93c6e636..8c487b8e 100644 --- a/src/n0043_multiply_strings.rs +++ b/src/solution/s0043_multiply_strings.rs @@ -2,37 +2,40 @@ * [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::collections::VecDeque; 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(); @@ -43,10 +46,10 @@ impl Solution { 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() { - } + 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() @@ -60,6 +63,5 @@ mod tests { use super::*; #[test] - fn test_43() { - } + fn test_43() {} } diff --git a/src/n0044_wildcard_matching.rs b/src/solution/s0044_wildcard_matching.rs similarity index 79% rename from src/n0044_wildcard_matching.rs rename to src/solution/s0044_wildcard_matching.rs index 26fba8f1..e875131a 100644 --- a/src/n0044_wildcard_matching.rs +++ b/src/solution/s0044_wildcard_matching.rs @@ -2,73 +2,76 @@ * [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 { @@ -84,6 +87,5 @@ mod tests { use super::*; #[test] - fn test_44() { - } + fn test_44() {} } diff --git a/src/n0045_jump_game_ii.rs b/src/solution/s0045_jump_game_ii.rs similarity index 79% rename from src/n0045_jump_game_ii.rs rename to src/solution/s0045_jump_game_ii.rs index 822d1b41..3922e20b 100644 --- a/src/n0045_jump_game_ii.rs +++ b/src/solution/s0045_jump_game_ii.rs @@ -2,26 +2,29 @@ * [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 @@ -38,6 +41,5 @@ mod tests { use super::*; #[test] - fn test_45() { - } + fn test_45() {} } diff --git a/src/solution/s0046_permutations.rs b/src/solution/s0046_permutations.rs new file mode 100644 index 00000000..ef9354c8 --- /dev/null +++ b/src/solution/s0046_permutations.rs @@ -0,0 +1,70 @@ +/** + * [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 new file mode 100644 index 00000000..7dceb55b --- /dev/null +++ b/src/solution/s0047_permutations_ii.rs @@ -0,0 +1,179 @@ +/** + * [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/n0048_rotate_image.rs b/src/solution/s0048_rotate_image.rs similarity index 62% rename from src/n0048_rotate_image.rs rename to src/solution/s0048_rotate_image.rs index e2c9be0a..6f6fdffa 100644 --- a/src/n0048_rotate_image.rs +++ b/src/solution/s0048_rotate_image.rs @@ -2,42 +2,42 @@ * [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 = + * + * + * 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], @@ -45,11 +45,14 @@ * [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: @@ -78,14 +81,14 @@ pub struct Solution {} 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 (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; + 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; } } } @@ -99,19 +102,21 @@ mod tests { #[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]]; + 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] - ]); + 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/n0049_group_anagrams.rs b/src/solution/s0049_group_anagrams.rs similarity index 68% rename from src/n0049_group_anagrams.rs rename to src/solution/s0049_group_anagrams.rs index adf27bb1..64200ea3 100644 --- a/src/n0049_group_anagrams.rs +++ b/src/solution/s0049_group_anagrams.rs @@ -2,10 +2,10 @@ * [49] Group Anagrams * * Given an array of strings, group anagrams together. - * + * * Example: - * - * + * + * * Input: ["eat", "tea", "tan", "ate", "nat", "bat"], * Output: * [ @@ -13,17 +13,20 @@ * ["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; @@ -52,11 +55,13 @@ mod tests { #[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"], - ]); + 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/n0050_powx_n.rs b/src/solution/s0050_powx_n.rs similarity index 80% rename from src/n0050_powx_n.rs rename to src/solution/s0050_powx_n.rs index 97b7c582..3e2e9b3e 100644 --- a/src/n0050_powx_n.rs +++ b/src/solution/s0050_powx_n.rs @@ -2,39 +2,42 @@ * [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 { diff --git a/src/n0051_n_queens.rs b/src/solution/s0051_n_queens.rs similarity index 71% rename from src/n0051_n_queens.rs rename to src/solution/s0051_n_queens.rs index 7871c86c..d78435a9 100644 --- a/src/n0051_n_queens.rs +++ b/src/solution/s0051_n_queens.rs @@ -2,34 +2,37 @@ * [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 { @@ -40,16 +43,19 @@ impl Solution { solution } - fn schedule_queens(board: &mut Vec>, - solution: &mut Vec>, - len: usize, row: usize) { + 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); + Solution::schedule_queens(board, solution, len, row + 1); } board[row][col] = '.'; } @@ -59,17 +65,25 @@ impl Solution { #[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 } + 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; + 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; + if board[i as usize][j as usize] == 'Q' { + return true; + } + i -= 1; + j += 1; } false } @@ -86,20 +100,10 @@ mod tests { assert_eq!( Solution::solve_n_queens(4), vec![ - vec![".Q..", - "...Q", - "Q...", - "..Q."], - - vec!["..Q.", - "Q...", - "...Q", - ".Q.."] + vec![".Q..", "...Q", "Q...", "..Q."], + vec!["..Q.", "Q...", "...Q", ".Q.."] ] ); - assert_eq!( - Solution::solve_n_queens(8).len(), - 92 - ); + assert_eq!(Solution::solve_n_queens(8).len(), 92); } } diff --git a/src/n0052_n_queens_ii.rs b/src/solution/s0052_n_queens_ii.rs similarity index 78% rename from src/n0052_n_queens_ii.rs rename to src/solution/s0052_n_queens_ii.rs index 27c29044..7c9b1987 100644 --- a/src/n0052_n_queens_ii.rs +++ b/src/solution/s0052_n_queens_ii.rs @@ -2,14 +2,14 @@ * [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. @@ -18,17 +18,20 @@ * "...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 { @@ -39,16 +42,14 @@ impl Solution { num } - fn schedule_queens(board: &mut Vec>, - num: &mut i32, - len: usize, row: usize) { + 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); + Solution::schedule_queens(board, num, len, row + 1); } board[row][col] = '.'; } @@ -58,17 +59,23 @@ impl Solution { #[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 } + 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 } + 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 } + if board[i as usize][j as usize] == 'Q' { + return true; + } i -= 1; j += 1; } diff --git a/src/n0053_maximum_subarray.rs b/src/solution/s0053_maximum_subarray.rs similarity index 75% rename from src/n0053_maximum_subarray.rs rename to src/solution/s0053_maximum_subarray.rs index e3d25782..7967fb00 100644 --- a/src/n0053_maximum_subarray.rs +++ b/src/solution/s0053_maximum_subarray.rs @@ -2,22 +2,25 @@ * [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 { @@ -28,7 +31,7 @@ impl Solution { for j in 0..nums.len() { curr += nums[j]; max = i32::max(max, curr); - if curr <=0 { + if curr <= 0 { curr = 0; } } @@ -44,7 +47,10 @@ mod tests { #[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![-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 new file mode 100644 index 00000000..ac90b769 --- /dev/null +++ b/src/solution/s0054_spiral_matrix.rs @@ -0,0 +1,101 @@ +/** + * [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/n0055_jump_game.rs b/src/solution/s0055_jump_game.rs similarity index 63% rename from src/n0055_jump_game.rs rename to src/solution/s0055_jump_game.rs index 234624f6..8dc35842 100644 --- a/src/n0055_jump_game.rs +++ b/src/solution/s0055_jump_game.rs @@ -2,31 +2,34 @@ * [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 { @@ -49,12 +52,15 @@ mod tests { #[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![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); + 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/n0056_merge_intervals.rs b/src/solution/s0056_merge_intervals.rs similarity index 57% rename from src/n0056_merge_intervals.rs rename to src/solution/s0056_merge_intervals.rs index 0e667d60..108c043b 100644 --- a/src/n0056_merge_intervals.rs +++ b/src/solution/s0056_merge_intervals.rs @@ -2,56 +2,56 @@ * [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, - } +#[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 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 }); + 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 + continue; } - }, + } None => {} } result.push(interval); @@ -69,8 +69,17 @@ mod tests { #[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)] + 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/n0057_insert_interval.rs b/src/solution/s0057_insert_interval.rs similarity index 52% rename from src/n0057_insert_interval.rs rename to src/solution/s0057_insert_interval.rs index e74be393..0afe62b4 100644 --- a/src/n0057_insert_interval.rs +++ b/src/solution/s0057_insert_interval.rs @@ -2,12 +2,12 @@ * [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]] * @@ -22,24 +22,24 @@ */ 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, - } +// 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 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(); @@ -56,7 +56,8 @@ impl Solution { 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; + inserting = false; + inserted = true; } } if !inserting { @@ -79,28 +80,47 @@ mod tests { #[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)] + 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)] + 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)] + 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)] + 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)] + 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)] + Solution::insert( + vec![Interval::new(1, 2), Interval::new(3, 4)], + Interval::new(0, 6) + ), + vec![Interval::new(0, 6)] ); } } diff --git a/src/n0058_length_of_last_word.rs b/src/solution/s0058_length_of_last_word.rs similarity index 86% rename from src/n0058_length_of_last_word.rs rename to src/solution/s0058_length_of_last_word.rs index a8a768b7..4889c739 100644 --- a/src/n0058_length_of_last_word.rs +++ b/src/solution/s0058_length_of_last_word.rs @@ -2,20 +2,23 @@ * [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 { diff --git a/src/solution/s0059_spiral_matrix_ii.rs b/src/solution/s0059_spiral_matrix_ii.rs new file mode 100644 index 00000000..d54f57b4 --- /dev/null +++ b/src/solution/s0059_spiral_matrix_ii.rs @@ -0,0 +1,87 @@ +/** + * [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/n0060_permutation_sequence.rs b/src/solution/s0060_permutation_sequence.rs similarity index 77% rename from src/n0060_permutation_sequence.rs rename to src/solution/s0060_permutation_sequence.rs index 52c9fc65..0136a0b4 100644 --- a/src/n0060_permutation_sequence.rs +++ b/src/solution/s0060_permutation_sequence.rs @@ -2,9 +2,9 @@ * [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" @@ -13,33 +13,36 @@ * "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! + ... @@ -53,9 +56,7 @@ impl Solution { while i > 0 { if k > factorials[i as usize] { let round = k / factorials[i as usize]; - if round >= n { - - } + if round >= n {} } else { i -= 1; } @@ -71,6 +72,5 @@ mod tests { use super::*; #[test] - fn test_60() { - } + fn test_60() {} } diff --git a/src/n0061_rotate_list.rs b/src/solution/s0061_rotate_list.rs similarity index 77% rename from src/n0061_rotate_list.rs rename to src/solution/s0061_rotate_list.rs index cf6967b1..bbfb059f 100644 --- a/src/n0061_rotate_list.rs +++ b/src/solution/s0061_rotate_list.rs @@ -2,20 +2,20 @@ * [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: @@ -23,10 +23,13 @@ * 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 super::util::linked_list::{ListNode, to_list}; +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 @@ -43,6 +46,5 @@ mod tests { use super::*; #[test] - fn test_61() { - } + fn test_61() {} } diff --git a/src/n0062_unique_paths.rs b/src/solution/s0062_unique_paths.rs similarity index 80% rename from src/n0062_unique_paths.rs rename to src/solution/s0062_unique_paths.rs index 23c19bd0..3a158326 100644 --- a/src/n0062_unique_paths.rs +++ b/src/solution/s0062_unique_paths.rs @@ -2,19 +2,19 @@ * [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: @@ -22,17 +22,20 @@ * 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? @@ -41,12 +44,15 @@ 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 + (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!() } + if start > end { + unreachable!() + } let mut res = 1; while end > start { println!("{}", end); diff --git a/src/n0063_unique_paths_ii.rs b/src/solution/s0063_unique_paths_ii.rs similarity index 58% rename from src/n0063_unique_paths_ii.rs rename to src/solution/s0063_unique_paths_ii.rs index 9702c0d5..04d84911 100644 --- a/src/n0063_unique_paths_ii.rs +++ b/src/solution/s0063_unique_paths_ii.rs @@ -2,20 +2,20 @@ * [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], @@ -28,11 +28,14 @@ * 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 @@ -47,17 +50,19 @@ impl Solution { 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 x >= height || y >= width || obstacle_grid[x][y] == 1 { + continue; + } if y >= 1 { - paths[x][y] = paths[x][y] + paths[x][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]; + paths[x][y] = paths[x][y] + paths[x - 1][y]; } } step += 1; } - paths[height-1][width-1] + paths[height - 1][width - 1] } } @@ -71,47 +76,36 @@ mod tests { 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); + 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); + 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); + 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); + 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); + 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/n0064_minimum_path_sum.rs b/src/solution/s0064_minimum_path_sum.rs similarity index 58% rename from src/n0064_minimum_path_sum.rs rename to src/solution/s0064_minimum_path_sum.rs index b4457450..d6340d50 100644 --- a/src/n0064_minimum_path_sum.rs +++ b/src/solution/s0064_minimum_path_sum.rs @@ -2,12 +2,12 @@ * [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], @@ -16,11 +16,14 @@ * ] * 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 { @@ -29,20 +32,22 @@ impl Solution { let mut grid = grid; let mut step = 1; while step <= height + width - 2 { - for x in 0..(step+1) { + for x in 0..(step + 1) { let y = step - x; - if x >= height || y >= width { continue } + if x >= height || y >= width { + continue; + } if x < 1 { - grid[x][y] += grid[x][y-1]; + grid[x][y] += grid[x][y - 1]; } else if y < 1 { - grid[x][y] += grid[x-1][y]; + grid[x][y] += grid[x - 1][y]; } else { - grid[x][y] += i32::min(grid[x][y-1], grid[x-1][y]); + grid[x][y] += i32::min(grid[x][y - 1], grid[x - 1][y]); } } step += 1; } - grid[height-1][width-1] + grid[height - 1][width - 1] } } @@ -54,25 +59,11 @@ mod tests { #[test] fn test_64() { + assert_eq!(Solution::min_path_sum(vec![vec![2]]), 2); 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], - ]), + 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 - ); + assert_eq!(Solution::min_path_sum(vec![vec![1, 3, 1],]), 5); } } diff --git a/src/n0065_valid_number.rs b/src/solution/s0065_valid_number.rs similarity index 83% rename from src/n0065_valid_number.rs rename to src/solution/s0065_valid_number.rs index fa07c43a..11c5753d 100644 --- a/src/n0065_valid_number.rs +++ b/src/solution/s0065_valid_number.rs @@ -2,7 +2,7 @@ * [65] Valid Number * * Validate if a given string can be interpreted as a decimal number. - * + * * Some examples:
* "0" => true
* " 0.1 " => true
@@ -18,24 +18,27 @@ * " --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... @@ -53,6 +56,5 @@ mod tests { use super::*; #[test] - fn test_65() { - } + fn test_65() {} } diff --git a/src/n0066_plus_one.rs b/src/solution/s0066_plus_one.rs similarity index 73% rename from src/n0066_plus_one.rs rename to src/solution/s0066_plus_one.rs index d41f0b6a..fb1ea045 100644 --- a/src/n0066_plus_one.rs +++ b/src/solution/s0066_plus_one.rs @@ -2,30 +2,33 @@ * [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 { @@ -40,7 +43,9 @@ impl Solution { carry = 0; digits[i] + 1 }; - if carry == 0 { break } + if carry == 0 { + break; + } } if carry > 0 { digits.insert(0, 1); @@ -58,7 +63,10 @@ mod tests { #[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]); + 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/n0067_add_binary.rs b/src/solution/s0067_add_binary.rs similarity index 62% rename from src/n0067_add_binary.rs rename to src/solution/s0067_add_binary.rs index 7cc2093c..8c9951cc 100644 --- a/src/n0067_add_binary.rs +++ b/src/solution/s0067_add_binary.rs @@ -2,36 +2,40 @@ * [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 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; + + b.pop().map_or(0, |ch| ch.to_digit(10).unwrap()) + + carry; if sum > 1 { sum -= 2; carry = 1; @@ -55,9 +59,21 @@ mod tests { #[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()); + 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/n0068_text_justification.rs b/src/solution/s0068_text_justification.rs similarity index 73% rename from src/n0068_text_justification.rs rename to src/solution/s0068_text_justification.rs index 9b7a08f2..827fa4f8 100644 --- a/src/n0068_text_justification.rs +++ b/src/solution/s0068_text_justification.rs @@ -2,24 +2,24 @@ * [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 @@ -29,11 +29,11 @@ * "example of text", * "justification. " * ] - * - * + * + * * Example 2: - * - * + * + * * Input: * words = ["What","must","be","acknowledgment","shall","be"] * maxWidth = 16 @@ -46,11 +46,11 @@ * 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"] @@ -64,11 +64,14 @@ * "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 { @@ -79,9 +82,11 @@ impl Solution { let mut row_len = 0; let mut buf = Vec::new(); while i < words.len() { - if words[i].len() > max_width { unreachable!() } + if words[i].len() > max_width { + unreachable!() + } let old_len = row_len; - row_len += words[i].len() + if row_len > 0 { 1 } else { 0 }; + 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(); @@ -136,32 +141,50 @@ mod tests { fn test_68() { assert_eq!( Solution::full_justify( - vec_string!["This", "is", "an", "example", "of", "text", "justification."], + vec_string![ + "This", + "is", + "an", + "example", + "of", + "text", + "justification." + ], 16 ), - vec_string![ - "This is an", - "example of text", - "justification. " - ] + vec_string!["This is an", "example of text", "justification. "] ); assert_eq!( Solution::full_justify( - vec_string!["What","must","be","acknowledgment","shall","be"], + vec_string!["What", "must", "be", "acknowledgment", "shall", "be"], 16 ), - vec_string![ - "What must be", - "acknowledgment ", - "shall be " - ] + 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"], + vec_string![ + "Science", + "is", + "what", + "we", + "understand", + "well", + "enough", + "to", + "explain", + "to", + "a", + "computer.", + "Art", + "is", + "everything", + "else", + "we", + "do" + ], 20 ), vec_string![ diff --git a/src/n0069_sqrtx.rs b/src/solution/s0069_sqrtx.rs similarity index 86% rename from src/n0069_sqrtx.rs rename to src/solution/s0069_sqrtx.rs index 7925061a..256f88be 100644 --- a/src/n0069_sqrtx.rs +++ b/src/solution/s0069_sqrtx.rs @@ -2,30 +2,33 @@ * [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 + * 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 diff --git a/src/n0070_climbing_stairs.rs b/src/solution/s0070_climbing_stairs.rs similarity index 75% rename from src/n0070_climbing_stairs.rs rename to src/solution/s0070_climbing_stairs.rs index ab90ce83..2ef4153b 100644 --- a/src/n0070_climbing_stairs.rs +++ b/src/solution/s0070_climbing_stairs.rs @@ -2,43 +2,50 @@ * [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} + 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; diff --git a/src/n0071_simplify_path.rs b/src/solution/s0071_simplify_path.rs similarity index 74% rename from src/n0071_simplify_path.rs rename to src/solution/s0071_simplify_path.rs index e020208a..4b61f7be 100644 --- a/src/n0071_simplify_path.rs +++ b/src/solution/s0071_simplify_path.rs @@ -2,61 +2,64 @@ * [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 { @@ -64,11 +67,13 @@ impl Solution { let mut stack = Vec::new(); for s in path.split('/') { match s { - "." => {}, - "/" => {}, - "" => {}, - ".." => { stack.pop(); }, - _ => stack.push(s) + "." => {} + "/" => {} + "" => {} + ".." => { + stack.pop(); + } + _ => stack.push(s), } } let mut res = String::new(); @@ -76,7 +81,11 @@ impl Solution { res.push('/'); res.push_str(s); } - if res.len() > 0 { res } else { "/".to_owned() } + if res.len() > 0 { + res + } else { + "/".to_owned() + } } } @@ -91,7 +100,13 @@ mod tests { 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"); + 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/n0072_edit_distance.rs b/src/solution/s0072_edit_distance.rs similarity index 76% rename from src/n0072_edit_distance.rs rename to src/solution/s0072_edit_distance.rs index 8dc9fc09..d50d9fa3 100644 --- a/src/n0072_edit_distance.rs +++ b/src/solution/s0072_edit_distance.rs @@ -2,42 +2,45 @@ * [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: + * 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: + * 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 { @@ -53,6 +56,5 @@ mod tests { use super::*; #[test] - fn test_72() { - } + fn test_72() {} } diff --git a/src/n0073_set_matrix_zeroes.rs b/src/solution/s0073_set_matrix_zeroes.rs similarity index 71% rename from src/n0073_set_matrix_zeroes.rs rename to src/solution/s0073_set_matrix_zeroes.rs index 17202e5a..8d8cdab8 100644 --- a/src/n0073_set_matrix_zeroes.rs +++ b/src/solution/s0073_set_matrix_zeroes.rs @@ -1,59 +1,60 @@ /** * [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? - * - * + * 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>) { - - } + pub fn set_zeroes(matrix: &mut Vec>) {} } // submission codes end @@ -63,6 +64,5 @@ mod tests { use super::*; #[test] - fn test_73() { - } + fn test_73() {} } diff --git a/src/n0074_search_a_2d_matrix.rs b/src/solution/s0074_search_a_2d_matrix.rs similarity index 59% rename from src/n0074_search_a_2d_matrix.rs rename to src/solution/s0074_search_a_2d_matrix.rs index b58dcb11..90975918 100644 --- a/src/n0074_search_a_2d_matrix.rs +++ b/src/solution/s0074_search_a_2d_matrix.rs @@ -2,15 +2,15 @@ * [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], @@ -19,11 +19,11 @@ * ] * target = 3 * Output: true - * - * + * + * * Example 2: - * - * + * + * * Input: * matrix = [ * [1, 3, 5, 7], @@ -32,28 +32,37 @@ * ] * 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 } + if matrix.is_empty() { + return false; + } let (height, width) = (matrix.len(), matrix[0].len()); - if height < 1 || width < 1 { return false } + 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]) { + 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] + target == matrix[base / width][base % width] } } @@ -67,21 +76,15 @@ mod tests { 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 + 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 + vec![vec![1, 3, 5, 7], vec![10, 11, 16, 20], vec![23, 30, 34, 50]], + 13 ), false ); diff --git a/src/n0075_sort_colors.rs b/src/solution/s0075_sort_colors.rs similarity index 71% rename from src/n0075_sort_colors.rs rename to src/solution/s0075_sort_colors.rs index fda4f61c..6b72ac88 100644 --- a/src/n0075_sort_colors.rs +++ b/src/solution/s0075_sort_colors.rs @@ -2,44 +2,52 @@ * [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); + 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; + i += 1; + lower_idx += 1; } else if nums[i] > 1 { nums.swap(upper_idx, i); - if upper_idx < 1 { break } + if upper_idx < 1 { + break; + } upper_idx -= 1; } else { i += 1; @@ -56,16 +64,21 @@ mod tests { #[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]; + 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]); + 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]; + let mut vec = vec![2, 2, 2]; Solution::sort_colors(&mut vec); - assert_eq!(vec, vec![2,2,2]); + assert_eq!(vec, vec![2, 2, 2]); } } diff --git a/src/n0076_minimum_window_substring.rs b/src/solution/s0076_minimum_window_substring.rs similarity index 76% rename from src/n0076_minimum_window_substring.rs rename to src/solution/s0076_minimum_window_substring.rs index 5ec5e7c5..9d190533 100644 --- a/src/n0076_minimum_window_substring.rs +++ b/src/solution/s0076_minimum_window_substring.rs @@ -2,36 +2,37 @@ * [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() + return "".to_owned(); } let (mut start, mut end) = (0_usize, 0_usize); - let mut result = (0_usize,0_usize); - loop { - - } + let mut result = (0_usize, 0_usize); + loop {} s[result.0..result.1].to_owned() } @@ -51,6 +52,5 @@ mod tests { use super::*; #[test] - fn test_76() { - } + fn test_76() {} } diff --git a/src/n0077_combinations.rs b/src/solution/s0077_combinations.rs similarity index 60% rename from src/n0077_combinations.rs rename to src/solution/s0077_combinations.rs index 0a9d2d1a..6bb10d6b 100644 --- a/src/n0077_combinations.rs +++ b/src/solution/s0077_combinations.rs @@ -2,10 +2,10 @@ * [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: * [ @@ -16,11 +16,14 @@ * [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 { @@ -33,16 +36,16 @@ impl Solution { fn backtrack(start: i32, end: i32, k: i32, curr: Vec, result: &mut Vec>) { if k < 1 { result.push(curr); - return + return; } if end - start + 1 < k { // elements is not enough, return quickly - return + return; } - for i in start..end+1 { + for i in start..end + 1 { let mut vec = curr.clone(); vec.push(i); - Solution::backtrack(i+1, end, k-1, vec, result); + Solution::backtrack(i + 1, end, k - 1, vec, result); } } } @@ -57,20 +60,18 @@ mod tests { 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]] + 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]] - ); + assert_eq!(Solution::combine(0, 1), empty); + assert_eq!(Solution::combine(2, 1), vec![vec![1], vec![2]]); } } diff --git a/src/n0078_subsets.rs b/src/solution/s0078_subsets.rs similarity index 64% rename from src/n0078_subsets.rs rename to src/solution/s0078_subsets.rs index d2077a9e..2db34925 100644 --- a/src/n0078_subsets.rs +++ b/src/solution/s0078_subsets.rs @@ -2,12 +2,12 @@ * [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: * [ @@ -20,10 +20,13 @@ * [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 { @@ -36,13 +39,13 @@ impl Solution { fn backtrack(start: usize, mut curr: Vec, nums: &Vec, result: &mut Vec>) { if start >= nums.len() { result.push(curr); - return + return; } // current element dropped - Solution::backtrack(start+1, curr.clone(), nums, result); + Solution::backtrack(start + 1, curr.clone(), nums, result); // current element picked curr.push(nums[start]); - Solution::backtrack(start+1, curr, nums, result); + Solution::backtrack(start + 1, curr, nums, result); } } @@ -54,18 +57,11 @@ mod tests { #[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![]), - vec![vec![]] + Solution::subsets(vec![1, 2]), + vec![vec![], vec![2], vec![1], vec![1, 2]] ); - 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 new file mode 100644 index 00000000..07c4a705 --- /dev/null +++ b/src/solution/s0079_word_search.rs @@ -0,0 +1,133 @@ +/** + * [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/n0080_remove_duplicates_from_sorted_array_ii.rs b/src/solution/s0080_remove_duplicates_from_sorted_array_ii.rs similarity index 83% rename from src/n0080_remove_duplicates_from_sorted_array_ii.rs rename to src/solution/s0080_remove_duplicates_from_sorted_array_ii.rs index 81258613..70b3cf82 100644 --- a/src/n0080_remove_duplicates_from_sorted_array_ii.rs +++ b/src/solution/s0080_remove_duplicates_from_sorted_array_ii.rs @@ -2,50 +2,53 @@ * [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 { @@ -61,6 +64,5 @@ mod tests { use super::*; #[test] - fn test_80() { - } + fn test_80() {} } diff --git a/src/n0081_search_in_rotated_sorted_array_ii.rs b/src/solution/s0081_search_in_rotated_sorted_array_ii.rs similarity index 78% rename from src/n0081_search_in_rotated_sorted_array_ii.rs rename to src/solution/s0081_search_in_rotated_sorted_array_ii.rs index b1824900..7972a16f 100644 --- a/src/n0081_search_in_rotated_sorted_array_ii.rs +++ b/src/solution/s0081_search_in_rotated_sorted_array_ii.rs @@ -2,34 +2,37 @@ * [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 { @@ -45,6 +48,5 @@ mod tests { use super::*; #[test] - fn test_81() { - } + fn test_81() {} } diff --git a/src/n0082_remove_duplicates_from_sorted_list_ii.rs b/src/solution/s0082_remove_duplicates_from_sorted_list_ii.rs similarity index 73% rename from src/n0082_remove_duplicates_from_sorted_list_ii.rs rename to src/solution/s0082_remove_duplicates_from_sorted_list_ii.rs index 7f26a25b..067d0c79 100644 --- a/src/n0082_remove_duplicates_from_sorted_list_ii.rs +++ b/src/solution/s0082_remove_duplicates_from_sorted_list_ii.rs @@ -2,24 +2,27 @@ * [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 super::util::linked_list::{ListNode, to_list}; +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 @@ -29,7 +32,7 @@ use super::util::linked_list::{ListNode, to_list}; // pub val: i32, // pub next: Option> // } -// +// // impl ListNode { // #[inline] // fn new(val: i32) -> Self { @@ -52,6 +55,5 @@ mod tests { use super::*; #[test] - fn test_82() { - } + fn test_82() {} } diff --git a/src/n0083_remove_duplicates_from_sorted_list.rs b/src/solution/s0083_remove_duplicates_from_sorted_list.rs similarity index 72% rename from src/n0083_remove_duplicates_from_sorted_list.rs rename to src/solution/s0083_remove_duplicates_from_sorted_list.rs index 6030c791..5c9552cc 100644 --- a/src/n0083_remove_duplicates_from_sorted_list.rs +++ b/src/solution/s0083_remove_duplicates_from_sorted_list.rs @@ -2,24 +2,27 @@ * [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 super::util::linked_list::{ListNode, to_list}; +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 @@ -29,7 +32,7 @@ use super::util::linked_list::{ListNode, to_list}; // pub val: i32, // pub next: Option> // } -// +// // impl ListNode { // #[inline] // fn new(val: i32) -> Self { @@ -52,6 +55,5 @@ mod tests { use super::*; #[test] - fn test_83() { - } + fn test_83() {} } diff --git a/src/n0084_largest_rectangle_in_histogram.rs b/src/solution/s0084_largest_rectangle_in_histogram.rs similarity index 56% rename from src/n0084_largest_rectangle_in_histogram.rs rename to src/solution/s0084_largest_rectangle_in_histogram.rs index 0440e557..d33b9bda 100644 --- a/src/n0084_largest_rectangle_in_histogram.rs +++ b/src/solution/s0084_largest_rectangle_in_histogram.rs @@ -2,29 +2,32 @@ * [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 @@ -37,16 +40,26 @@ impl Solution { 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)); + 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); } + 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)); + max_area = i32::max( + max_area, + hs.last().unwrap() * ((len - positions.last().unwrap()) as i32), + ); positions.pop(); hs.pop(); } @@ -62,11 +75,17 @@ mod tests { #[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); + 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/n0085_maximal_rectangle.rs b/src/solution/s0085_maximal_rectangle.rs similarity index 73% rename from src/n0085_maximal_rectangle.rs rename to src/solution/s0085_maximal_rectangle.rs index 921e69d7..6dbf2951 100644 --- a/src/n0085_maximal_rectangle.rs +++ b/src/solution/s0085_maximal_rectangle.rs @@ -2,10 +2,10 @@ * [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"], @@ -14,17 +14,20 @@ * ["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 } } @@ -36,6 +39,5 @@ mod tests { use super::*; #[test] - fn test_85() { - } + fn test_85() {} } diff --git a/src/n0086_partition_list.rs b/src/solution/s0086_partition_list.rs similarity index 72% rename from src/n0086_partition_list.rs rename to src/solution/s0086_partition_list.rs index a4c847b2..1f4952dd 100644 --- a/src/n0086_partition_list.rs +++ b/src/solution/s0086_partition_list.rs @@ -2,19 +2,24 @@ * [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 super::util::linked_list::{ListNode, to_list}; +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> { @@ -48,16 +53,13 @@ mod tests { #[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] + Solution::partition(linked![1, 4, 3, 2, 5, 2], 3), + linked![1, 2, 2, 4, 3, 5] ); assert_eq!( - Solution::partition(linked![], 0), - linked![] + 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/n0087_scramble_string.rs b/src/solution/s0087_scramble_string.rs similarity index 80% rename from src/n0087_scramble_string.rs rename to src/solution/s0087_scramble_string.rs index c2601ade..19b47dc0 100644 --- a/src/n0087_scramble_string.rs +++ b/src/solution/s0087_scramble_string.rs @@ -2,10 +2,10 @@ * [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 @@ -13,13 +13,13 @@ * 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 @@ -27,13 +27,13 @@ * 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 @@ -41,28 +41,31 @@ * 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 { @@ -78,6 +81,5 @@ mod tests { use super::*; #[test] - fn test_87() { - } + fn test_87() {} } diff --git a/src/n0088_merge_sorted_array.rs b/src/solution/s0088_merge_sorted_array.rs similarity index 71% rename from src/n0088_merge_sorted_array.rs rename to src/solution/s0088_merge_sorted_array.rs index e9266f6a..bdcc2a1a 100644 --- a/src/n0088_merge_sorted_array.rs +++ b/src/solution/s0088_merge_sorted_array.rs @@ -2,27 +2,30 @@ * [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 { @@ -51,28 +54,19 @@ mod tests { #[test] fn test_88() { - let mut vec1 = vec![1,2,3,0,0,0]; - let mut vec2 = vec![2,5,6]; + 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] - ); + assert_eq!(vec1, vec![1, 2, 2, 3, 5, 6]); - let mut vec1 = vec![1,2,3]; + 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] - ); + assert_eq!(vec1, vec![1, 2, 3]); - let mut vec1 = vec![0,0,0]; - let mut vec2 = 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] - ); + assert_eq!(vec1, vec![1, 2, 3]); } } diff --git a/src/n0089_gray_code.rs b/src/solution/s0089_gray_code.rs similarity index 77% rename from src/n0089_gray_code.rs rename to src/solution/s0089_gray_code.rs index eb4515f4..039283eb 100644 --- a/src/n0089_gray_code.rs +++ b/src/solution/s0089_gray_code.rs @@ -2,12 +2,12 @@ * [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: @@ -15,29 +15,32 @@ * 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 /* @@ -71,9 +74,9 @@ mod tests { #[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(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]); + assert_eq!(Solution::gray_code(3), vec![0, 1, 3, 2, 6, 7, 5, 4]); } } diff --git a/src/n0090_subsets_ii.rs b/src/solution/s0090_subsets_ii.rs similarity index 50% rename from src/n0090_subsets_ii.rs rename to src/solution/s0090_subsets_ii.rs index 4b74ecc9..e859e2d1 100644 --- a/src/n0090_subsets_ii.rs +++ b/src/solution/s0090_subsets_ii.rs @@ -2,12 +2,12 @@ * [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: * [ @@ -18,42 +18,54 @@ * [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 +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) - */ +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() + let nums = nums + .into_iter() .fold(BTreeMap::new(), |mut map, v| { - *map.entry(v).or_insert(0) += 1; map - }).into_iter().collect::>(); + *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>) { + fn backtrack( + start: usize, + mut curr: Vec, + nums: &Vec<(i32, i32)>, + result: &mut Vec>, + ) { if start >= nums.len() { result.push(curr); - return + return; } - for repeat in 0..nums[start].1+1 { + 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); + Solution::backtrack(start + 1, inner, nums, result); } } } @@ -67,28 +79,17 @@ mod tests { #[test] fn test_90() { assert_eq!( - Solution::subsets_with_dup(vec![1,2,2]), + Solution::subsets_with_dup(vec![1, 2, 2]), vec![ vec![], vec![2], - vec![2,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![], + 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/n0091_decode_ways.rs b/src/solution/s0091_decode_ways.rs similarity index 77% rename from src/n0091_decode_ways.rs rename to src/solution/s0091_decode_ways.rs index b10aaf8e..bbecc932 100644 --- a/src/n0091_decode_ways.rs +++ b/src/solution/s0091_decode_ways.rs @@ -2,34 +2,37 @@ * [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 { @@ -45,6 +48,5 @@ mod tests { use super::*; #[test] - fn test_91() { - } + fn test_91() {} } diff --git a/src/n0092_reverse_linked_list_ii.rs b/src/solution/s0092_reverse_linked_list_ii.rs similarity index 74% rename from src/n0092_reverse_linked_list_ii.rs rename to src/solution/s0092_reverse_linked_list_ii.rs index 09f10862..318c0d15 100644 --- a/src/n0092_reverse_linked_list_ii.rs +++ b/src/solution/s0092_reverse_linked_list_ii.rs @@ -2,19 +2,22 @@ * [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 super::util::linked_list::{ListNode, to_list}; +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 @@ -24,7 +27,7 @@ use super::util::linked_list::{ListNode, to_list}; // pub val: i32, // pub next: Option> // } -// +// // impl ListNode { // #[inline] // fn new(val: i32) -> Self { @@ -47,6 +50,5 @@ mod tests { use super::*; #[test] - fn test_92() { - } + fn test_92() {} } diff --git a/src/n0093_restore_ip_addresses.rs b/src/solution/s0093_restore_ip_addresses.rs similarity index 69% rename from src/n0093_restore_ip_addresses.rs rename to src/solution/s0093_restore_ip_addresses.rs index 38f602bb..5c2706b4 100644 --- a/src/n0093_restore_ip_addresses.rs +++ b/src/solution/s0093_restore_ip_addresses.rs @@ -2,17 +2,20 @@ * [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 { @@ -28,6 +31,5 @@ mod tests { use super::*; #[test] - fn test_93() { - } + fn test_93() {} } diff --git a/src/n0094_binary_tree_inorder_traversal.rs b/src/solution/s0094_binary_tree_inorder_traversal.rs similarity index 67% rename from src/n0094_binary_tree_inorder_traversal.rs rename to src/solution/s0094_binary_tree_inorder_traversal.rs index 42e55545..01afb57a 100644 --- a/src/n0094_binary_tree_inorder_traversal.rs +++ b/src/solution/s0094_binary_tree_inorder_traversal.rs @@ -2,33 +2,36 @@ * [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 super::util::tree::{TreeNode, to_tree}; -use std::rc::Rc; +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)})); + Solution::inorder_traverse(root.as_ref(), &mut (|v| res.push(v))); res } @@ -50,12 +53,12 @@ mod tests { #[test] fn test_94() { assert_eq!( - Solution::inorder_traversal(tree![1,null,2,3]), - vec![1,3,2] + 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] + Solution::inorder_traversal(tree![1, 2, 3, 4, 5, 6, 7]), + vec![4, 2, 5, 1, 6, 3, 7] ); } } diff --git a/src/n0095_unique_binary_search_trees_ii.rs b/src/solution/s0095_unique_binary_search_trees_ii.rs similarity index 79% rename from src/n0095_unique_binary_search_trees_ii.rs rename to src/solution/s0095_unique_binary_search_trees_ii.rs index 1a60cd60..1f75639d 100644 --- a/src/n0095_unique_binary_search_trees_ii.rs +++ b/src/solution/s0095_unique_binary_search_trees_ii.rs @@ -2,10 +2,10 @@ * [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: * [ @@ -17,7 +17,7 @@ * ] * Explanation: * The above output corresponds to the 5 unique BST's shown below: - * + * * 1 3 3 2 1 * \ / / / \ \ * 3 2 1 1 3 2 @@ -27,6 +27,9 @@ */ 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 /* @@ -48,19 +51,23 @@ pub struct Solution {} / \ 2 4 */ -use super::util::tree::{TreeNode, to_tree}; -use std::rc::Rc; +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 { + 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 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 @@ -78,6 +85,5 @@ mod tests { use super::*; #[test] - fn test_95() { - } + fn test_95() {} } diff --git a/src/n0096_unique_binary_search_trees.rs b/src/solution/s0096_unique_binary_search_trees.rs similarity index 74% rename from src/n0096_unique_binary_search_trees.rs rename to src/solution/s0096_unique_binary_search_trees.rs index f8cbe805..4f64c26c 100644 --- a/src/n0096_unique_binary_search_trees.rs +++ b/src/solution/s0096_unique_binary_search_trees.rs @@ -2,25 +2,28 @@ * [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 { @@ -36,6 +39,5 @@ mod tests { use super::*; #[test] - fn test_96() { - } + fn test_96() {} } diff --git a/src/solution/s0097_interleaving_string.rs b/src/solution/s0097_interleaving_string.rs new file mode 100644 index 00000000..8d69d851 --- /dev/null +++ b/src/solution/s0097_interleaving_string.rs @@ -0,0 +1,115 @@ +/** + * [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/n0098_validate_binary_search_tree.rs b/src/solution/s0098_validate_binary_search_tree.rs similarity index 61% rename from src/n0098_validate_binary_search_tree.rs rename to src/solution/s0098_validate_binary_search_tree.rs index 89f691f0..09098c18 100644 --- a/src/n0098_validate_binary_search_tree.rs +++ b/src/solution/s0098_validate_binary_search_tree.rs @@ -2,28 +2,28 @@ * [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 @@ -32,38 +32,44 @@ * 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 super::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; -use std::rc::Rc; 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 { + 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 + 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) + Solution::preorder_traverse(node.borrow().left.as_ref(), formers) + && Solution::preorder_traverse(node.borrow().right.as_ref(), &mut to_right) } else { true } @@ -78,8 +84,14 @@ mod tests { #[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); + 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/n0099_recover_binary_search_tree.rs b/src/solution/s0099_recover_binary_search_tree.rs similarity index 67% rename from src/n0099_recover_binary_search_tree.rs rename to src/solution/s0099_recover_binary_search_tree.rs index cec4ec60..2401231a 100644 --- a/src/n0099_recover_binary_search_tree.rs +++ b/src/solution/s0099_recover_binary_search_tree.rs @@ -2,61 +2,64 @@ * [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 super::util::tree::{TreeNode, to_tree}; +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 /* @@ -81,15 +84,20 @@ use super::util::tree::{TreeNode, to_tree}; 这个办法时间复杂度 O(N), 空间 O(1). 题解就用 Bottom-up 来写. */ -use std::rc::Rc; 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) { + 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()); @@ -103,17 +111,32 @@ impl Solution { // 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); + 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) + 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) + ( + 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) } @@ -128,12 +151,12 @@ mod tests { #[test] fn test_99() { - let mut tree = tree![3,1,4,null,null,2]; + 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]); + assert_eq!(tree, tree![2, 1, 4, null, null, 3]); - let mut tree = tree![2,6,5,null,null,3,1,null,4]; + 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]); + assert_eq!(tree, tree![2, 1, 5, null, null, 3, 6, null, 4]); } } diff --git a/src/n0100_same_tree.rs b/src/solution/s0100_same_tree.rs similarity index 63% rename from src/n0100_same_tree.rs rename to src/solution/s0100_same_tree.rs index f5f0136c..c7dc1372 100644 --- a/src/n0100_same_tree.rs +++ b/src/solution/s0100_same_tree.rs @@ -2,54 +2,60 @@ * [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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { - pub fn is_same_tree(p: Option>>, q: Option>>) -> bool { + pub fn is_same_tree( + p: Option>>, + q: Option>>, + ) -> bool { p == q } } @@ -62,6 +68,9 @@ mod tests { #[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) + 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 new file mode 100644 index 00000000..41f44bc8 --- /dev/null +++ b/src/solution/s0101_symmetric_tree.rs @@ -0,0 +1,87 @@ +/** + * [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/n0102_binary_tree_level_order_traversal.rs b/src/solution/s0102_binary_tree_level_order_traversal.rs similarity index 66% rename from src/n0102_binary_tree_level_order_traversal.rs rename to src/solution/s0102_binary_tree_level_order_traversal.rs index 603cb870..a5a3fd13 100644 --- a/src/n0102_binary_tree_level_order_traversal.rs +++ b/src/solution/s0102_binary_tree_level_order_traversal.rs @@ -2,49 +2,54 @@ * [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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; 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 } + 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())); + 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(); @@ -53,7 +58,9 @@ impl Solution { vec.push(node.borrow().val); } } - if !vec.is_empty() { res.push(vec) } + if !vec.is_empty() { + res.push(vec) + } res } } @@ -67,12 +74,8 @@ mod tests { #[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] - ] + Solution::level_order(tree![3, 9, 20, null, null, 15, 7]), + vec![vec![3], vec![9, 20], vec![15, 7]] ); } } diff --git a/src/n0103_binary_tree_zigzag_level_order_traversal.rs b/src/solution/s0103_binary_tree_zigzag_level_order_traversal.rs similarity index 78% rename from src/n0103_binary_tree_zigzag_level_order_traversal.rs rename to src/solution/s0103_binary_tree_zigzag_level_order_traversal.rs index c9d449ef..78aa7b5e 100644 --- a/src/n0103_binary_tree_zigzag_level_order_traversal.rs +++ b/src/solution/s0103_binary_tree_zigzag_level_order_traversal.rs @@ -2,42 +2,47 @@ * [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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; 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 } + if root.is_none() { + return res; + } let mut deq = VecDeque::new(); deq.push_back((0, root.clone())); let mut vec = Vec::new(); @@ -75,12 +80,8 @@ mod tests { #[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] - ] + 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/n0104_maximum_depth_of_binary_tree.rs b/src/solution/s0104_maximum_depth_of_binary_tree.rs similarity index 77% rename from src/n0104_maximum_depth_of_binary_tree.rs rename to src/solution/s0104_maximum_depth_of_binary_tree.rs index f880b095..2b2a51d4 100644 --- a/src/n0104_maximum_depth_of_binary_tree.rs +++ b/src/solution/s0104_maximum_depth_of_binary_tree.rs @@ -2,32 +2,35 @@ * [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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn max_depth(root: Option>>) -> i32 { let mut max = 0; @@ -53,6 +56,6 @@ mod tests { #[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); + assert_eq!(Solution::max_depth(tree![3, 9, 20, null, null, 15, 7]), 3); } } diff --git a/src/n0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs b/src/solution/s0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs similarity index 60% rename from src/n0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs rename to src/solution/s0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs index 71521287..809ae654 100644 --- a/src/n0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs +++ b/src/solution/s0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs @@ -2,45 +2,50 @@ * [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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; 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 } + if preorder.is_empty() { + return None; + } let root_idx = inorder.iter().position(|&v| v == preorder[0]).unwrap(); - Some(Rc::new(RefCell::new(TreeNode{ + 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..]), + 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..]), }))) } } @@ -53,8 +58,14 @@ mod tests { #[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![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/n0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs b/src/solution/s0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs similarity index 86% rename from src/n0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs rename to src/solution/s0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs index 7d3e820c..df215bbc 100644 --- a/src/n0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs +++ b/src/solution/s0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs @@ -24,7 +24,10 @@ * */ pub struct Solution {} -use super::util::tree::{to_tree, TreeNode}; +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 diff --git a/src/n0107_binary_tree_level_order_traversal_ii.rs b/src/solution/s0107_binary_tree_level_order_traversal_ii.rs similarity index 66% rename from src/n0107_binary_tree_level_order_traversal_ii.rs rename to src/solution/s0107_binary_tree_level_order_traversal_ii.rs index be2f6fc1..4b74e0d7 100644 --- a/src/n0107_binary_tree_level_order_traversal_ii.rs +++ b/src/solution/s0107_binary_tree_level_order_traversal_ii.rs @@ -2,49 +2,54 @@ * [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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; 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 } + 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())); + 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(); @@ -53,7 +58,9 @@ impl Solution { vec.push(node.borrow().val); } } - if !vec.is_empty() { res.push(vec) } + if !vec.is_empty() { + res.push(vec) + } res.reverse(); res } @@ -68,12 +75,8 @@ mod tests { #[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], - ] + 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/n0108_convert_sorted_array_to_binary_search_tree.rs b/src/solution/s0108_convert_sorted_array_to_binary_search_tree.rs similarity index 61% rename from src/n0108_convert_sorted_array_to_binary_search_tree.rs rename to src/solution/s0108_convert_sorted_array_to_binary_search_tree.rs index 0a6d6dc7..2cefab5c 100644 --- a/src/n0108_convert_sorted_array_to_binary_search_tree.rs +++ b/src/solution/s0108_convert_sorted_array_to_binary_search_tree.rs @@ -2,42 +2,47 @@ * [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. - * + * * 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 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 - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn sorted_array_to_bst(nums: Vec) -> Option>> { Solution::bst_helper(&nums[..]) } fn bst_helper(nums: &[i32]) -> Option>> { - if nums.is_empty() { return None } - Some(Rc::new(RefCell::new(TreeNode{ + 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)..]), + left: Solution::bst_helper(&nums[0..(nums.len() / 2)]), + right: Solution::bst_helper(&nums[(nums.len() / 2 + 1)..]), }))) } } @@ -50,7 +55,10 @@ mod tests { #[test] fn test_108() { - assert_eq!(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![-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/n0109_convert_sorted_list_to_binary_search_tree.rs b/src/solution/s0109_convert_sorted_list_to_binary_search_tree.rs similarity index 62% rename from src/n0109_convert_sorted_list_to_binary_search_tree.rs rename to src/solution/s0109_convert_sorted_list_to_binary_search_tree.rs index 59d3233e..e2070965 100644 --- a/src/n0109_convert_sorted_list_to_binary_search_tree.rs +++ b/src/solution/s0109_convert_sorted_list_to_binary_search_tree.rs @@ -2,32 +2,35 @@ * [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 super::util::linked_list::{ListNode, to_list}; -use super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn sorted_list_to_bst(head: Option>) -> Option>> { let mut arr = Vec::new(); @@ -40,11 +43,13 @@ impl Solution { } fn bst_helper(nums: &[i32]) -> Option>> { - if nums.is_empty() { return None } - Some(Rc::new(RefCell::new(TreeNode{ + 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)..]), + left: Solution::bst_helper(&nums[0..(nums.len() / 2)]), + right: Solution::bst_helper(&nums[(nums.len() / 2 + 1)..]), }))) } } @@ -57,6 +62,9 @@ mod tests { #[test] fn test_109() { - assert_eq!(Solution::sorted_list_to_bst(linked![-10,-3,0,5,9]), tree![0,-3,9,-10,null,5]); + assert_eq!( + Solution::sorted_list_to_bst(linked![-10, -3, 0, 5, 9]), + tree![0, -3, 9, -10, null, 5] + ); } } diff --git a/src/n0110_balanced_binary_tree.rs b/src/solution/s0110_balanced_binary_tree.rs similarity index 64% rename from src/n0110_balanced_binary_tree.rs rename to src/solution/s0110_balanced_binary_tree.rs index 8a1b8582..c3171126 100644 --- a/src/n0110_balanced_binary_tree.rs +++ b/src/solution/s0110_balanced_binary_tree.rs @@ -2,31 +2,31 @@ * [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 @@ -34,18 +34,21 @@ * 3 3 * / \ * 4 4 - * - * + * + * * Return false. - * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; 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() @@ -53,13 +56,16 @@ impl Solution { 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())); + 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; } } _ => return None, @@ -79,7 +85,13 @@ mod tests { #[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); + 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/n0111_minimum_depth_of_binary_tree.rs b/src/solution/s0111_minimum_depth_of_binary_tree.rs similarity index 64% rename from src/n0111_minimum_depth_of_binary_tree.rs rename to src/solution/s0111_minimum_depth_of_binary_tree.rs index 4ce67d40..a73e49f0 100644 --- a/src/n0111_minimum_depth_of_binary_tree.rs +++ b/src/solution/s0111_minimum_depth_of_binary_tree.rs @@ -2,45 +2,50 @@ * [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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; 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 } + 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 + return level; } - deq.push_back((level+1, node.borrow().left.clone())); - deq.push_back((level+1, node.borrow().right.clone())); + deq.push_back((level + 1, node.borrow().left.clone())); + deq.push_back((level + 1, node.borrow().right.clone())); } } 0 @@ -55,6 +60,6 @@ mod tests { #[test] fn test_111() { - assert_eq!(Solution::min_depth(tree![3,9,20,null,null,15,7]), 2); + assert_eq!(Solution::min_depth(tree![3, 9, 20, null, null, 15, 7]), 2); } } diff --git a/src/n0112_path_sum.rs b/src/solution/s0112_path_sum.rs similarity index 56% rename from src/n0112_path_sum.rs rename to src/solution/s0112_path_sum.rs index f8430c87..e2e0a235 100644 --- a/src/n0112_path_sum.rs +++ b/src/solution/s0112_path_sum.rs @@ -2,14 +2,14 @@ * [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 @@ -17,32 +17,43 @@ * 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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; 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 } + 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 } + 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())) }; + 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())) + }; } } } @@ -58,6 +69,12 @@ mod tests { #[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); + 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/n0113_path_sum_ii.rs b/src/solution/s0113_path_sum_ii.rs similarity index 63% rename from src/n0113_path_sum_ii.rs rename to src/solution/s0113_path_sum_ii.rs index f4660555..106d1921 100644 --- a/src/n0113_path_sum_ii.rs +++ b/src/solution/s0113_path_sum_ii.rs @@ -2,14 +2,14 @@ * [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 @@ -17,30 +17,35 @@ * 11 13 4 * / \ / \ * 7 2 5 1 - * - * + * + * * Return: - * - * + * + * * [ * [5,4,11,2], * [5,8,4,5] * ] - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; 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 } + if root.is_none() { + return res; + } let mut deq = VecDeque::new(); deq.push_back((0, Vec::new(), root.clone())); while !deq.is_empty() { @@ -52,8 +57,12 @@ impl Solution { 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())); } + 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())); + } } } } @@ -70,11 +79,8 @@ mod tests { #[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] - ] + 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/n0114_flatten_binary_tree_to_linked_list.rs b/src/solution/s0114_flatten_binary_tree_to_linked_list.rs similarity index 72% rename from src/n0114_flatten_binary_tree_to_linked_list.rs rename to src/solution/s0114_flatten_binary_tree_to_linked_list.rs index 385c89a1..63668c47 100644 --- a/src/n0114_flatten_binary_tree_to_linked_list.rs +++ b/src/solution/s0114_flatten_binary_tree_to_linked_list.rs @@ -2,20 +2,20 @@ * [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 @@ -27,16 +27,19 @@ * 5 * \ * 6 - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn flatten(root: &mut Option>>) { Solution::flatten_helper(root.clone()); @@ -72,16 +75,16 @@ mod tests { #[test] fn test_114() { - let mut tree = tree![1,2,5,3,4,null,6]; + 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]); + assert_eq!(tree, tree![1, null, 2, null, 3, null, 4, null, 5, null, 6]); - let mut tree = tree![1,2,null,3]; + let mut tree = tree![1, 2, null, 3]; Solution::flatten(&mut tree); - assert_eq!(tree, tree![1,null,2,null,3]); + assert_eq!(tree, tree![1, null, 2, null, 3]); - let mut tree = tree![1,null,2,3]; + let mut tree = tree![1, null, 2, 3]; Solution::flatten(&mut tree); - assert_eq!(tree, tree![1,null,2,null,3]); + 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 new file mode 100644 index 00000000..7af3d08b --- /dev/null +++ b/src/solution/s0115_distinct_subsequences.rs @@ -0,0 +1,122 @@ +/** + * [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/n0118_pascals_triangle.rs b/src/solution/s0118_pascals_triangle.rs similarity index 68% rename from src/n0118_pascals_triangle.rs rename to src/solution/s0118_pascals_triangle.rs index f6d7c124..d593242d 100644 --- a/src/n0118_pascals_triangle.rs +++ b/src/solution/s0118_pascals_triangle.rs @@ -2,13 +2,13 @@ * [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: * [ @@ -18,22 +18,27 @@ * [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 } + if num_rows < 1 { + return res; + } let mut curr = vec![1]; for _ in 0..num_rows { - let mut next = vec![1; curr.len()+1]; + let mut next = vec![1; curr.len() + 1]; for i in 1..curr.len() { - next[i] = curr[i-1] + curr[i]; + next[i] = curr[i - 1] + curr[i]; } res.push(curr); curr = next; @@ -55,10 +60,11 @@ mod tests { Solution::generate(5), vec![ vec![1], - vec![1,1], - vec![1,2,1], - vec![1,3,3,1], - vec![1,4,6,4,1] - ]); + vec![1, 1], + vec![1, 2, 1], + vec![1, 3, 3, 1], + vec![1, 4, 6, 4, 1] + ] + ); } } diff --git a/src/n0119_pascals_triangle_ii.rs b/src/solution/s0119_pascals_triangle_ii.rs similarity index 71% rename from src/n0119_pascals_triangle_ii.rs rename to src/solution/s0119_pascals_triangle_ii.rs index 5d2b1dcb..588a9835 100644 --- a/src/n0119_pascals_triangle_ii.rs +++ b/src/solution/s0119_pascals_triangle_ii.rs @@ -2,40 +2,43 @@ * [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 +in-place algorithm - 1 1 1 1 1 - 1 2 1 1 1 - 1 3 3 1 1 - 1 4 6 4 1 - */ +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 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]; @@ -56,9 +59,6 @@ mod tests { #[test] fn test_119() { assert_eq!(Solution::get_row(0), vec![1]); - assert_eq!( - Solution::get_row(4), - vec![1,4,6,4,1] - ) + assert_eq!(Solution::get_row(4), vec![1, 4, 6, 4, 1]) } } diff --git a/src/n0120_triangle.rs b/src/solution/s0120_triangle.rs similarity index 77% rename from src/n0120_triangle.rs rename to src/solution/s0120_triangle.rs index 609182ce..93c38d33 100644 --- a/src/n0120_triangle.rs +++ b/src/solution/s0120_triangle.rs @@ -2,10 +2,10 @@ * [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], @@ -13,16 +13,19 @@ * [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 { @@ -42,7 +45,9 @@ impl Solution { prev = temp; } } - cache.into_iter().fold(i32::max_value(), |min, x| i32::min(min, x)) + cache + .into_iter() + .fold(i32::max_value(), |min, x| i32::min(min, x)) } } @@ -55,14 +60,7 @@ mod tests { #[test] fn test_120() { assert_eq!( - Solution::minimum_total( - vec![ - vec![2], - vec![3,4], - vec![6,5,7], - vec![4,1,8,3] - ] - ), + Solution::minimum_total(vec![vec![2], vec![3, 4], vec![6, 5, 7], vec![4, 1, 8, 3]]), 11 ) } diff --git a/src/n0121_best_time_to_buy_and_sell_stock.rs b/src/solution/s0121_best_time_to_buy_and_sell_stock.rs similarity index 73% rename from src/n0121_best_time_to_buy_and_sell_stock.rs rename to src/solution/s0121_best_time_to_buy_and_sell_stock.rs index 51548dec..d5d3746d 100644 --- a/src/n0121_best_time_to_buy_and_sell_stock.rs +++ b/src/solution/s0121_best_time_to_buy_and_sell_stock.rs @@ -2,31 +2,34 @@ * [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 { @@ -34,7 +37,7 @@ impl Solution { let mut max = 0; let mut curr = 0; for i in 1..prices.len() { - curr = curr + prices[i] - prices[i-1]; + curr = curr + prices[i] - prices[i - 1]; if curr <= 0 { curr = 0; } else { @@ -53,7 +56,7 @@ mod tests { #[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); + 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/n0122_best_time_to_buy_and_sell_stock_ii.rs b/src/solution/s0122_best_time_to_buy_and_sell_stock_ii.rs similarity index 73% rename from src/n0122_best_time_to_buy_and_sell_stock_ii.rs rename to src/solution/s0122_best_time_to_buy_and_sell_stock_ii.rs index 828de554..803c71b6 100644 --- a/src/n0122_best_time_to_buy_and_sell_stock_ii.rs +++ b/src/solution/s0122_best_time_to_buy_and_sell_stock_ii.rs @@ -2,48 +2,51 @@ * [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]; + if prices[i] > prices[i - 1] { + max += prices[i] - prices[i - 1]; } } max @@ -58,7 +61,7 @@ mod tests { #[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); + 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 new file mode 100644 index 00000000..bb068273 --- /dev/null +++ b/src/solution/s0123_best_time_to_buy_and_sell_stock_iii.rs @@ -0,0 +1,106 @@ +/** + * [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 new file mode 100644 index 00000000..e7c57b49 --- /dev/null +++ b/src/solution/s0124_binary_tree_maximum_path_sum.rs @@ -0,0 +1,100 @@ +/** + * [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/n0125_valid_palindrome.rs b/src/solution/s0125_valid_palindrome.rs similarity index 61% rename from src/n0125_valid_palindrome.rs rename to src/solution/s0125_valid_palindrome.rs index 146b6f3f..2f090b72 100644 --- a/src/n0125_valid_palindrome.rs +++ b/src/solution/s0125_valid_palindrome.rs @@ -2,41 +2,53 @@ * [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 } + 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 } + 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 + return false; } - i += 1; j -= 1; + i += 1; + j -= 1; } true } @@ -50,7 +62,10 @@ mod tests { #[test] fn test_125() { - assert_eq!(Solution::is_palindrome("A man, a plan, a canal: Panama".to_owned()), true); + 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 new file mode 100644 index 00000000..32169865 --- /dev/null +++ b/src/solution/s0126_word_ladder_ii.rs @@ -0,0 +1,258 @@ +/** + * [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/n0127_word_ladder.rs b/src/solution/s0127_word_ladder.rs similarity index 74% rename from src/n0127_word_ladder.rs rename to src/solution/s0127_word_ladder.rs index 183efe93..a67465fa 100644 --- a/src/n0127_word_ladder.rs +++ b/src/solution/s0127_word_ladder.rs @@ -2,60 +2,65 @@ * [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::VecDeque; 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 } + if target.is_none() { + return 0; + } let target = target.unwrap(); let mut deq = VecDeque::new(); let mut distance = vec![0; len]; @@ -81,14 +86,18 @@ impl Solution { #[inline(always)] fn connect(s1: &str, s2: &str) -> bool { - if s1.len() != s2.len() { return false } + 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 } + if diff >= 2 { + return false; + } } } true @@ -104,13 +113,19 @@ mod tests { #[test] fn test_127() { assert_eq!( - Solution::ladder_length("hit".to_owned(), "cog".to_owned(), - vec_string!["hot","dot","dog","lot","log","cog"]), + 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"]), + 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 new file mode 100644 index 00000000..f0e0806f --- /dev/null +++ b/src/solution/s0128_longest_consecutive_sequence.rs @@ -0,0 +1,65 @@ +/** + * [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/n0129_sum_root_to_leaf_numbers.rs b/src/solution/s0129_sum_root_to_leaf_numbers.rs similarity index 77% rename from src/n0129_sum_root_to_leaf_numbers.rs rename to src/solution/s0129_sum_root_to_leaf_numbers.rs index b29dc36b..1e44fb68 100644 --- a/src/n0129_sum_root_to_leaf_numbers.rs +++ b/src/solution/s0129_sum_root_to_leaf_numbers.rs @@ -2,16 +2,16 @@ * [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 * / \ @@ -21,10 +21,10 @@ * 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 * / \ @@ -37,24 +37,29 @@ * 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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; 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 } + 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 { + 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; @@ -76,7 +81,7 @@ mod tests { #[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); + 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 new file mode 100644 index 00000000..411286b4 --- /dev/null +++ b/src/solution/s0130_surrounded_regions.rs @@ -0,0 +1,221 @@ +/** + * [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 new file mode 100644 index 00000000..22a92dfd --- /dev/null +++ b/src/solution/s0131_palindrome_partitioning.rs @@ -0,0 +1,120 @@ +/** + * [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/n0132_palindrome_partitioning_ii.rs b/src/solution/s0132_palindrome_partitioning_ii.rs similarity index 55% rename from src/n0132_palindrome_partitioning_ii.rs rename to src/solution/s0132_palindrome_partitioning_ii.rs index ce4149b3..81b75cf6 100644 --- a/src/n0132_palindrome_partitioning_ii.rs +++ b/src/solution/s0132_palindrome_partitioning_ii.rs @@ -2,46 +2,51 @@ * [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): +为了方便讨论, 我们记 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(n) = min(f(n-i) + 1) { i in [0..n] and s[i..n] is palindrome } - 显然, f(1) 为 1, f(0) 为 0 +显然, f(1) 为 1, f(0) 为 0 - 判断 is_palindrome 也需要优化, 使用一个备忘录, 将判断回文的操作优化到 O(1): +判断 is_palindrome 也需要优化, 使用一个备忘录, 将判断回文的操作优化到 O(1): - is_palindrome(s[i..n]) = s[i] == s[n] && is_palindrome(s[i+1..n-1]) +is_palindrome(s[i..n]) = s[i] == s[n] && is_palindrome(s[i+1..n-1]) - 最后的复杂度: 时间 O(N^2), 空间 O(N^2) - */ +最后的复杂度: 时间 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 } + 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); + 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 { + 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); } @@ -51,12 +56,20 @@ impl Solution { min[s.len()] - 1 } - fn is_palindrome(cache: &mut Vec>>, s: &Vec, i: usize, j: usize) -> bool { - if j <= i { return true } + 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)); + 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 } diff --git a/src/n0134_gas_station.rs b/src/solution/s0134_gas_station.rs similarity index 85% rename from src/n0134_gas_station.rs rename to src/solution/s0134_gas_station.rs index d8651433..352990f9 100644 --- a/src/n0134_gas_station.rs +++ b/src/solution/s0134_gas_station.rs @@ -2,28 +2,28 @@ * [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: + * + * + * 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 @@ -32,17 +32,17 @@ * 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: + * + * + * 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 @@ -50,11 +50,14 @@ * 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 { @@ -70,6 +73,5 @@ mod tests { use super::*; #[test] - fn test_134() { - } + fn test_134() {} } diff --git a/src/n0135_candy.rs b/src/solution/s0135_candy.rs similarity index 68% rename from src/n0135_candy.rs rename to src/solution/s0135_candy.rs index 10813843..debb29d0 100644 --- a/src/n0135_candy.rs +++ b/src/solution/s0135_candy.rs @@ -2,36 +2,39 @@ * [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 { @@ -41,11 +44,11 @@ impl Solution { let mut last = 1; let mut ascending = false; for i in 1..ratings.len() { - if ratings[i] == ratings[i-1] { + if ratings[i] == ratings[i - 1] { n += 1; from = i; ascending = false; - } else if ratings[i] >= ratings[i-1] { + } else if ratings[i] >= ratings[i - 1] { from = i; ascending = true; last += 1; @@ -71,11 +74,11 @@ mod tests { #[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); + 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/n0136_single_number.rs b/src/solution/s0136_single_number.rs similarity index 83% rename from src/n0136_single_number.rs rename to src/solution/s0136_single_number.rs index 5d14631b..580d1213 100644 --- a/src/n0136_single_number.rs +++ b/src/solution/s0136_single_number.rs @@ -24,6 +24,9 @@ */ pub struct Solution {} +// problem: https://leetcode.com/problems/single-number/ +// discuss: https://leetcode.com/problems/single-number/discuss/?currentPage=1&orderBy=most_votes&query= + // submission codes start here impl Solution { pub fn single_number(nums: Vec) -> i32 { diff --git a/src/n0137_single_number_ii.rs b/src/solution/s0137_single_number_ii.rs similarity index 93% rename from src/n0137_single_number_ii.rs rename to src/solution/s0137_single_number_ii.rs index e4a928a2..5e99cd84 100644 --- a/src/n0137_single_number_ii.rs +++ b/src/solution/s0137_single_number_ii.rs @@ -23,6 +23,9 @@ */ 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 /* diff --git a/src/n0139_word_break.rs b/src/solution/s0139_word_break.rs similarity index 62% rename from src/n0139_word_break.rs rename to src/solution/s0139_word_break.rs index d8d495f9..ce9e2684 100644 --- a/src/n0139_word_break.rs +++ b/src/solution/s0139_word_break.rs @@ -2,61 +2,64 @@ * [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] 表示从 0 开始长度为 n 的 substring 是否可以被组成,那么: - f[n] = f[k] && (s[k..n] in dict) - f[0] = true +f[n] = f[k] && (s[k..n] in dict) +f[0] = true - DP 向上递推即可 +DP 向上递推即可 - BFS 也是可以的 - */ +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]; + let mut dp = vec![false; s.len() + 1]; dp[0] = true; - for i in 1..s.len()+1 { + 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; @@ -75,7 +78,16 @@ mod tests { #[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); + 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/n0140_word_break_ii.rs b/src/solution/s0140_word_break_ii.rs similarity index 80% rename from src/n0140_word_break_ii.rs rename to src/solution/s0140_word_break_ii.rs index de1a76ce..68c1319e 100644 --- a/src/n0140_word_break_ii.rs +++ b/src/solution/s0140_word_break_ii.rs @@ -2,17 +2,17 @@ * [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"] @@ -21,11 +21,11 @@ * "cats and dog", * "cat sand dog" * ] - * - * + * + * * Example 2: - * - * + * + * * Input: * s = "pineapplepenapple" * wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] @@ -36,20 +36,23 @@ * "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 { @@ -65,6 +68,5 @@ mod tests { use super::*; #[test] - fn test_140() { - } + fn test_140() {} } diff --git a/src/n0143_reorder_list.rs b/src/solution/s0143_reorder_list.rs similarity index 68% rename from src/n0143_reorder_list.rs rename to src/solution/s0143_reorder_list.rs index 59b113ec..1a7854cc 100644 --- a/src/n0143_reorder_list.rs +++ b/src/solution/s0143_reorder_list.rs @@ -3,33 +3,36 @@ * * 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 super::util::linked_list::{ListNode, to_list}; +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->2->3<-4<-5 + 1->2->3<-4<-5 - 1->5->2->4->3 - */ + 1->5->2->4->3 +*/ impl Solution { pub fn reorder_list(head: &mut Option>) { // TODO @@ -43,6 +46,5 @@ mod tests { use super::*; #[test] - fn test_143() { - } + fn test_143() {} } diff --git a/src/n0144_binary_tree_preorder_traversal.rs b/src/solution/s0144_binary_tree_preorder_traversal.rs similarity index 72% rename from src/n0144_binary_tree_preorder_traversal.rs rename to src/solution/s0144_binary_tree_preorder_traversal.rs index 444b4ca1..3d823976 100644 --- a/src/n0144_binary_tree_preorder_traversal.rs +++ b/src/solution/s0144_binary_tree_preorder_traversal.rs @@ -2,30 +2,33 @@ * [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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn preorder_traversal(root: Option>>) -> Vec { let mut res = Vec::new(); @@ -50,6 +53,9 @@ mod tests { #[test] fn test_144() { - assert_eq!(Solution::preorder_traversal(tree![1,null,2,3]), vec![1,2,3]); + assert_eq!( + Solution::preorder_traversal(tree![1, null, 2, 3]), + vec![1, 2, 3] + ); } } diff --git a/src/n0145_binary_tree_postorder_traversal.rs b/src/solution/s0145_binary_tree_postorder_traversal.rs similarity index 72% rename from src/n0145_binary_tree_postorder_traversal.rs rename to src/solution/s0145_binary_tree_postorder_traversal.rs index 681229c1..63197e88 100644 --- a/src/n0145_binary_tree_postorder_traversal.rs +++ b/src/solution/s0145_binary_tree_postorder_traversal.rs @@ -2,30 +2,33 @@ * [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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn postorder_traversal(root: Option>>) -> Vec { let mut res = Vec::new(); @@ -50,6 +53,9 @@ mod tests { #[test] fn test_145() { - assert_eq!(Solution::postorder_traversal(tree![1,null,2,3]), vec![3,2,1]); + assert_eq!( + Solution::postorder_traversal(tree![1, null, 2, 3]), + vec![3, 2, 1] + ); } } diff --git a/src/n0146_lru_cache.rs b/src/solution/s0146_lru_cache.rs similarity index 82% rename from src/n0146_lru_cache.rs rename to src/solution/s0146_lru_cache.rs index 84445af1..226cbf77 100644 --- a/src/n0146_lru_cache.rs +++ b/src/solution/s0146_lru_cache.rs @@ -1,22 +1,22 @@ /** * [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 @@ -26,22 +26,24 @@ * 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 +Least Recently Used, 最近最少使用, 关键在于追踪每一个 entry 的 age, 每次淘汰最小的那一个 key - 假如淘汰逻辑要做到 O(1) 复杂度, 我们可以引入一个链表, 每次 touch 一个值时, 就删掉它重新 push_back, 而当达到容量要驱逐时, 则 pop_front +假如淘汰逻辑要做到 O(1) 复杂度, 我们可以引入一个链表, 每次 touch 一个值时, 就删掉它重新 push_back, 而当达到容量要驱逐时, 则 pop_front - Rust 的链表不支持根据引用删除任意元素,也没有 LinkedHashMap,需要自己实现一个 - */ +Rust 的链表不支持根据引用删除任意元素,也没有 LinkedHashMap,需要自己实现一个 +*/ use std::collections::HashMap; -use std::ptr; use std::mem; +use std::ptr; // Entry is either a map entry and a link-list node pub struct LRUEntry { @@ -53,7 +55,7 @@ pub struct LRUEntry { impl LRUEntry { pub fn new(key: i32, val: i32) -> Self { - LRUEntry{ + LRUEntry { key: key, val: val, prev: ptr::null_mut(), @@ -75,7 +77,7 @@ impl LRUCache { pub fn new(capacity: i32) -> Self { let capacity = capacity as usize; let map = HashMap::with_capacity(capacity); - let cache = LRUCache{ + let cache = LRUCache { map: map, cap: capacity, head: unsafe { Box::into_raw(Box::new(mem::uninitialized::())) }, @@ -88,7 +90,7 @@ impl LRUCache { cache } - + pub fn get(&mut self, key: i32) -> i32 { let (ptr, val) = match self.map.get_mut(&key) { None => (None, None), @@ -104,7 +106,7 @@ impl LRUCache { } 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; @@ -141,7 +143,7 @@ impl LRUCache { unsafe { next = (*self.head).next } // list is empty if next == self.tail { - return None + return None; } let key = unsafe { (*next).key }; let mut old_entry = self.map.remove(&key).unwrap(); @@ -180,20 +182,19 @@ mod tests { #[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 + assert_eq!(lru_cache.get(1), 1); // returns 1 println!("evict key 2"); - lru_cache.put(3, 3); // evicts 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 + 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/n0147_insertion_sort_list.rs b/src/solution/s0147_insertion_sort_list.rs similarity index 81% rename from src/n0147_insertion_sort_list.rs rename to src/solution/s0147_insertion_sort_list.rs index 76617241..09aff82b 100644 --- a/src/n0147_insertion_sort_list.rs +++ b/src/solution/s0147_insertion_sort_list.rs @@ -2,44 +2,47 @@ * [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 super::util::linked_list::{ListNode, to_list}; +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 @@ -57,6 +60,5 @@ mod tests { use super::*; #[test] - fn test_147() { - } + fn test_147() {} } diff --git a/src/solution/s0148_sort_list.rs b/src/solution/s0148_sort_list.rs new file mode 100644 index 00000000..78b7f08c --- /dev/null +++ b/src/solution/s0148_sort_list.rs @@ -0,0 +1,125 @@ +/** + * [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 new file mode 100644 index 00000000..31ea4c62 --- /dev/null +++ b/src/solution/s0149_max_points_on_a_line.rs @@ -0,0 +1,178 @@ +/** + * [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/n0150_evaluate_reverse_polish_notation.rs b/src/solution/s0150_evaluate_reverse_polish_notation.rs similarity index 69% rename from src/n0150_evaluate_reverse_polish_notation.rs rename to src/solution/s0150_evaluate_reverse_polish_notation.rs index 4ceb55eb..048824dd 100644 --- a/src/n0150_evaluate_reverse_polish_notation.rs +++ b/src/solution/s0150_evaluate_reverse_polish_notation.rs @@ -2,38 +2,38 @@ * [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: + * Explanation: * ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 * = ((10 * (6 / (12 * -11))) + 17) + 5 * = ((10 * (6 / -132)) + 17) + 5 @@ -41,11 +41,14 @@ * = (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 { @@ -58,11 +61,11 @@ impl Solution { 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.push(left * right), + "+" => stack.push(left + right), + "/" => stack.push(left / right), + "-" => stack.push(left - right), + _ => unreachable!(), } } } @@ -79,7 +82,9 @@ mod tests { #[test] fn test_150() { assert_eq!( - Solution::eval_rpn(vec_string!["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]), + Solution::eval_rpn(vec_string![ + "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" + ]), 22 ); } diff --git a/src/n0151_reverse_words_in_a_string.rs b/src/solution/s0151_reverse_words_in_a_string.rs similarity index 73% rename from src/n0151_reverse_words_in_a_string.rs rename to src/solution/s0151_reverse_words_in_a_string.rs index 1c8292d8..627f0dd6 100644 --- a/src/n0151_reverse_words_in_a_string.rs +++ b/src/solution/s0151_reverse_words_in_a_string.rs @@ -2,50 +2,53 @@ * [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 { @@ -78,7 +81,13 @@ mod tests { #[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()); + 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/n0152_maximum_product_subarray.rs b/src/solution/s0152_maximum_product_subarray.rs similarity index 53% rename from src/n0152_maximum_product_subarray.rs rename to src/solution/s0152_maximum_product_subarray.rs index 6aa2299c..b85b5ecb 100644 --- a/src/n0152_maximum_product_subarray.rs +++ b/src/solution/s0152_maximum_product_subarray.rs @@ -2,40 +2,43 @@ * [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 +f[i], g[i] means the max positive value and max negative value for the sub-seq end with index i - then we have: +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] - } - */ +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 { @@ -44,13 +47,16 @@ impl Solution { let mut pos_max = 0; for num in nums.into_iter() { if num == 0 { - neg_max = 0; pos_max = 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; + 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); + pos_max = neg_max * num; + neg_max = i32::min(pos_pre * num, num); } if pos_max != 0 { max = i32::max(max, pos_max); @@ -68,8 +74,8 @@ mod tests { #[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); + 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/n0153_find_minimum_in_rotated_sorted_array.rs b/src/solution/s0153_find_minimum_in_rotated_sorted_array.rs similarity index 67% rename from src/n0153_find_minimum_in_rotated_sorted_array.rs rename to src/solution/s0153_find_minimum_in_rotated_sorted_array.rs index 0b4fc49f..03b7e7f1 100644 --- a/src/n0153_find_minimum_in_rotated_sorted_array.rs +++ b/src/solution/s0153_find_minimum_in_rotated_sorted_array.rs @@ -2,36 +2,41 @@ * [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] + * + * + * 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 } + if size == 0 { + return -1; + } let mut base = 0_usize; while size > 1 { let half = size / 2; @@ -53,7 +58,7 @@ mod tests { #[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); + 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/n0154_find_minimum_in_rotated_sorted_array_ii.rs b/src/solution/s0154_find_minimum_in_rotated_sorted_array_ii.rs similarity index 53% rename from src/n0154_find_minimum_in_rotated_sorted_array_ii.rs rename to src/solution/s0154_find_minimum_in_rotated_sorted_array_ii.rs index e134d927..cdb23ac3 100644 --- a/src/n0154_find_minimum_in_rotated_sorted_array_ii.rs +++ b/src/solution/s0154_find_minimum_in_rotated_sorted_array_ii.rs @@ -2,46 +2,49 @@ * [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] 那么转折点一定在右侧, 否则在左侧 - 但假如有重复, 就可能有 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) +可以考虑一个数组, [1,1,1,1,1,1,1,0,1,1,1,1,1,1] 这个数组无论怎么去找 0, 时间复杂度无法低于 O(N) - 但假如不是这种极端情况, 那么二分搜索还是能优化的, 在 153 的基础上, 碰到相等就跳过即可 - */ +但假如不是这种极端情况, 那么二分搜索还是能优化的, 在 153 的基础上, 碰到相等就跳过即可 +*/ impl Solution { pub fn find_min(nums: Vec) -> i32 { let mut lo = 0; @@ -57,7 +60,7 @@ impl Solution { hi -= 1; } } - return nums[lo] + return nums[lo]; } } @@ -69,8 +72,8 @@ mod tests { #[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); + 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/n0155_min_stack.rs b/src/solution/s0155_min_stack.rs similarity index 65% rename from src/n0155_min_stack.rs rename to src/solution/s0155_min_stack.rs index c2e1fe61..99a96698 100644 --- a/src/n0155_min_stack.rs +++ b/src/solution/s0155_min_stack.rs @@ -1,26 +1,26 @@ /** * [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); @@ -29,39 +29,41 @@ * 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 啊 +这题居然是 easy... 我怀疑人生了, getMin() 怎么能做到常数时间? Heap 也是 LogN 啊 - 看了最高票解之后...........天哪, 我可太菜了 +看了最高票解之后...........天哪, 我可太菜了 - 核心思想是保证每次 pop 时都能以常数时间更新最小值, 这就需要在空间上以某种方式记录下来 +核心思想是保证每次 pop 时都能以常数时间更新最小值, 这就需要在空间上以某种方式记录下来 - 那一种做法就是存储每个元素和最小值之间的差值, 这样 pop 的时候就能不断还原出原始值 +那一种做法就是存储每个元素和最小值之间的差值, 这样 pop 的时候就能不断还原出原始值 - 另一种更直观的做法就是每次入栈 min 时, 都把前一个 min (当前第二小的数字) 放在它前面, 作为记录 - */ +另一种更直观的做法就是每次入栈 min 时, 都把前一个 min (当前第二小的数字) 放在它前面, 作为记录 +*/ struct MinStack { vec: Vec, min: i32, } impl MinStack { - /** initialize your data structure here. */ pub fn new() -> Self { - MinStack{ + MinStack { vec: Vec::new(), min: i32::max_value(), } } - + pub fn push(&mut self, x: i32) { if x <= self.min { self.vec.push(self.min); @@ -75,11 +77,11 @@ impl MinStack { self.min = self.vec.pop().unwrap(); } } - + pub fn top(&self) -> i32 { *self.vec.last().unwrap() } - + pub fn get_min(&self) -> i32 { self.min } @@ -106,9 +108,9 @@ mod tests { min_stack.push(-2); min_stack.push(0); min_stack.push(-3); - assert_eq!(min_stack.get_min(), -3); // --> Returns -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.[] + assert_eq!(min_stack.top(), 0); // --> Returns 0. + assert_eq!(min_stack.get_min(), -2); // --> Returns -2.[] } } diff --git a/src/n0162_find_peak_element.rs b/src/solution/s0162_find_peak_element.rs similarity index 70% rename from src/n0162_find_peak_element.rs rename to src/solution/s0162_find_peak_element.rs index c82ae410..3888b998 100644 --- a/src/n0162_find_peak_element.rs +++ b/src/solution/s0162_find_peak_element.rs @@ -2,36 +2,39 @@ * [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, + * 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 { @@ -40,7 +43,7 @@ impl Solution { let mut mid = 0; while lo < hi { mid = (hi - lo) / 2 + lo; - if mid + 1 < nums.len() && nums[mid] < nums[mid+1]{ + if mid + 1 < nums.len() && nums[mid] < nums[mid + 1] { lo = mid + 1; } else { hi = mid; @@ -58,7 +61,7 @@ mod tests { #[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); + 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/n0164_maximum_gap.rs b/src/solution/s0164_maximum_gap.rs similarity index 62% rename from src/n0164_maximum_gap.rs rename to src/solution/s0164_maximum_gap.rs index f8661f96..bd961db7 100644 --- a/src/n0164_maximum_gap.rs +++ b/src/solution/s0164_maximum_gap.rs @@ -2,49 +2,52 @@ * [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, 我就 ??? 了... +想不出来, 一看解析居然是 Radix Sort 或 Bucket Sort, 我就 ??? 了... - 最佳算法是 Bucket Sort 吗? (桶大小取 max - min / len 那种), 看时间复杂度好像是这样 +最佳算法是 Bucket Sort 吗? (桶大小取 max - min / len 那种), 看时间复杂度好像是这样 - 但假如整体排布非常稠密, 那么这个聪明的算法也就退化成了桶大小为 1 的桶排序 - */ +但假如整体排布非常稠密, 那么这个聪明的算法也就退化成了桶大小为 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 = i32::max(nums[i] - nums[i - 1], gap); } gap } @@ -58,6 +61,6 @@ mod tests { #[test] fn test_164() { - assert_eq!(Solution::maximum_gap(vec![3,6,9,1]), 3); + assert_eq!(Solution::maximum_gap(vec![3, 6, 9, 1]), 3); } } diff --git a/src/n0165_compare_version_numbers.rs b/src/solution/s0165_compare_version_numbers.rs similarity index 72% rename from src/n0165_compare_version_numbers.rs rename to src/solution/s0165_compare_version_numbers.rs index c3a323e8..b53f1bbb 100644 --- a/src/n0165_compare_version_numbers.rs +++ b/src/solution/s0165_compare_version_numbers.rs @@ -3,51 +3,54 @@ * * 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 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 { @@ -56,12 +59,12 @@ impl Solution { 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 left = v1[i].parse::().unwrap(); let right = v2[i].parse::().unwrap(); if left > right { return 1; } else if left < right { - return - 1; + return -1; } i += 1; } @@ -77,7 +80,7 @@ impl Solution { } i += 1; } - return 0 + return 0; } } @@ -89,9 +92,21 @@ mod tests { #[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); + 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/n0166_fraction_to_recurring_decimal.rs b/src/solution/s0166_fraction_to_recurring_decimal.rs similarity index 74% rename from src/n0166_fraction_to_recurring_decimal.rs rename to src/solution/s0166_fraction_to_recurring_decimal.rs index f2117358..4585738f 100644 --- a/src/n0166_fraction_to_recurring_decimal.rs +++ b/src/solution/s0166_fraction_to_recurring_decimal.rs @@ -2,32 +2,35 @@ * [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. - * + * * 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)" - * - * + * + * */ pub struct Solution {} +// problem: https://leetcode.com/problems/fraction-to-recurring-decimal/ +// discuss: https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/?currentPage=1&orderBy=most_votes&query= + // submission codes start here // TODO @@ -44,6 +47,5 @@ mod tests { use super::*; #[test] - fn test_166() { - } + fn test_166() {} } diff --git a/src/n0167_two_sum_ii_input_array_is_sorted.rs b/src/solution/s0167_two_sum_ii_input_array_is_sorted.rs similarity index 78% rename from src/n0167_two_sum_ii_input_array_is_sorted.rs rename to src/solution/s0167_two_sum_ii_input_array_is_sorted.rs index f4f90864..58de2e86 100644 --- a/src/n0167_two_sum_ii_input_array_is_sorted.rs +++ b/src/solution/s0167_two_sum_ii_input_array_is_sorted.rs @@ -2,26 +2,29 @@ * [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 { @@ -38,7 +41,7 @@ impl Solution { break; } } - return vec![i as i32 + 1, j as i32 + 1] + return vec![i as i32 + 1, j as i32 + 1]; } } @@ -50,6 +53,6 @@ mod tests { #[test] fn test_167() { - assert_eq!(Solution::two_sum(vec![2,7,11,15], 9), vec![1,2]); + assert_eq!(Solution::two_sum(vec![2, 7, 11, 15], 9), vec![1, 2]); } } diff --git a/src/n0168_excel_sheet_column_title.rs b/src/solution/s0168_excel_sheet_column_title.rs similarity index 72% rename from src/n0168_excel_sheet_column_title.rs rename to src/solution/s0168_excel_sheet_column_title.rs index 0d2ca35f..5a9dc585 100644 --- a/src/n0168_excel_sheet_column_title.rs +++ b/src/solution/s0168_excel_sheet_column_title.rs @@ -2,43 +2,46 @@ * [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 + * 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 { @@ -49,7 +52,10 @@ impl Solution { while n > 0 { let mut code = (n % base) as u8; n = n / base; - if code == 0 { n -= 1; code = base as u8; }; + if code == 0 { + n -= 1; + code = base as u8; + }; let alphabetic = (('A' as u8) + (code - 1_u8)) as char; res.push(alphabetic); } diff --git a/src/solution/s0169_majority_element.rs b/src/solution/s0169_majority_element.rs new file mode 100644 index 00000000..be59bea6 --- /dev/null +++ b/src/solution/s0169_majority_element.rs @@ -0,0 +1,73 @@ +/** + * [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/n0171_excel_sheet_column_number.rs b/src/solution/s0171_excel_sheet_column_number.rs similarity index 65% rename from src/n0171_excel_sheet_column_number.rs rename to src/solution/s0171_excel_sheet_column_number.rs index c0e83b88..1b2f611f 100644 --- a/src/n0171_excel_sheet_column_number.rs +++ b/src/solution/s0171_excel_sheet_column_number.rs @@ -2,43 +2,46 @@ * [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 + * 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 @@ -55,6 +58,5 @@ mod tests { use super::*; #[test] - fn test_171() { - } + fn test_171() {} } diff --git a/src/n0172_factorial_trailing_zeroes.rs b/src/solution/s0172_factorial_trailing_zeroes.rs similarity index 82% rename from src/n0172_factorial_trailing_zeroes.rs rename to src/solution/s0172_factorial_trailing_zeroes.rs index db8bcf97..9a54916d 100644 --- a/src/n0172_factorial_trailing_zeroes.rs +++ b/src/solution/s0172_factorial_trailing_zeroes.rs @@ -2,26 +2,29 @@ * [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 { diff --git a/src/n0173_binary_search_tree_iterator.rs b/src/solution/s0173_binary_search_tree_iterator.rs similarity index 76% rename from src/n0173_binary_search_tree_iterator.rs rename to src/solution/s0173_binary_search_tree_iterator.rs index 638382ea..b350600d 100644 --- a/src/n0173_binary_search_tree_iterator.rs +++ b/src/solution/s0173_binary_search_tree_iterator.rs @@ -2,19 +2,19 @@ * [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 @@ -25,39 +25,40 @@ * 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 super::util::tree::{TreeNode, to_tree}; -use std::rc::Rc; +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(); @@ -65,11 +66,9 @@ impl BSTIterator { stack.push(inner.clone()); node = node.unwrap().borrow().left.clone(); } - BSTIterator{ - stack: stack, - } + BSTIterator { stack: stack } } - + /** @return the next smallest number */ pub fn next(&mut self) -> i32 { let node = self.stack.pop().unwrap(); @@ -81,7 +80,7 @@ impl BSTIterator { } res } - + /** @return whether we have a next smallest number */ pub fn has_next(&self) -> bool { !self.stack.is_empty() @@ -103,15 +102,15 @@ mod tests { #[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 + 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.next(), 9); // return 9 assert_eq!(iterator.has_next(), true); // return true - assert_eq!(iterator.next(), 15); // return 15 + 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.next(), 20); // return 20 assert_eq!(iterator.has_next(), false); // return false } } diff --git a/src/n0174_dungeon_game.rs b/src/solution/s0174_dungeon_game.rs similarity index 64% rename from src/n0174_dungeon_game.rs rename to src/solution/s0174_dungeon_game.rs index 5e4a4864..23be4d97 100644 --- a/src/n0174_dungeon_game.rs +++ b/src/solution/s0174_dungeon_game.rs @@ -4,7 +4,7 @@ * * 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. - * + * * * * @@ -44,44 +44,47 @@ * * *
- * + * * - * + * * 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] +DP, 即从每个格子出发到达终点所需的最小生命值为 hp[i][j] - 则显然, hp[M-1][N-1] = min(dungeon[M-1][N-1], 0) + 1; +则显然, 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[i][j] = min(min(hp[i+1][j], hp[i][j+1]) - dungeon[i][j], 1); - 倒推到 hp[0][0] 即可 +倒推到 hp[0][0] 即可 - 这里倒推很重要, 因为正推很难 dp(有后效性) +这里倒推很重要, 因为正推很难 dp(有后效性) - 其实可以优化成 O(M+N) 空间复杂度, 从斜对角线往后推就只需要保存一个小数组, 但是下面这样更简明 - */ +其实可以优化成 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; + 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[i][j] = i32::max(i32::min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j], 1); } } hp[0][0] @@ -97,18 +100,16 @@ mod tests { #[test] fn test_174() { assert_eq!( - Solution::calculate_minimum_hp( - vec![ - vec![-2,-3,3], - vec![-5,-10,1], - vec![10,30,-5], - ]), - 7); + 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); + 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 new file mode 100644 index 00000000..65348165 --- /dev/null +++ b/src/solution/s0179_largest_number.rs @@ -0,0 +1,60 @@ +/** + * [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/n0187_repeated_dna_sequences.rs b/src/solution/s0187_repeated_dna_sequences.rs similarity index 56% rename from src/n0187_repeated_dna_sequences.rs rename to src/solution/s0187_repeated_dna_sequences.rs index 3bc412f0..9ceb86cb 100644 --- a/src/n0187_repeated_dna_sequences.rs +++ b/src/solution/s0187_repeated_dna_sequences.rs @@ -2,31 +2,34 @@ * [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 +首先想到直接长度为 10 的 sliding window 滑过去加一个 HashSet - 但这种方法在空间上和每次操作的耗时上都比较差, 可以转化为四进制或者二进制编码来考虑 +但这种方法在空间上和每次操作的耗时上都比较差, 可以转化为四进制或者二进制编码来考虑 - A,C,G,T <-> [00, 01, 10, 11] +A,C,G,T <-> [00, 01, 10, 11] - 那就简单很多了, 往后滑动一格不再需要调整整个 substring, 只需要移位, HashSet 也就存个 u32 即可 - */ +那就简单很多了, 往后滑动一格不再需要调整整个 substring, 只需要移位, HashSet 也就存个 u32 即可 +*/ use std::collections::HashSet; impl Solution { pub fn find_repeated_dna_sequences(s: String) -> Vec { @@ -45,7 +48,8 @@ impl Solution { } // skip first 9 chars if count < 9 { - count += 1; continue; + count += 1; + continue; } // mask high 12-bits seq_code &= 0b0000_0000_0000_1111_1111_1111_1111_1111; @@ -54,22 +58,25 @@ impl Solution { } } // 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() + 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() } } 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 new file mode 100644 index 00000000..e9c23319 --- /dev/null +++ b/src/solution/s0188_best_time_to_buy_and_sell_stock_iv.rs @@ -0,0 +1,103 @@ +/** + * [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/n0189_rotate_array.rs b/src/solution/s0189_rotate_array.rs similarity index 75% rename from src/n0189_rotate_array.rs rename to src/solution/s0189_rotate_array.rs index 8fb93958..1a4d2ab8 100644 --- a/src/n0189_rotate_array.rs +++ b/src/solution/s0189_rotate_array.rs @@ -2,37 +2,40 @@ * [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: + * 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 { @@ -66,11 +69,11 @@ mod tests { #[test] fn test_189() { - let mut nums = vec![1,2,3,4,5,6,7]; + 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]; + 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]); + assert_eq!(nums, vec![5, 6, 1, 2, 3, 4]); } } diff --git a/src/n0198_house_robber.rs b/src/solution/s0198_house_robber.rs similarity index 66% rename from src/n0198_house_robber.rs rename to src/solution/s0198_house_robber.rs index e4183b5d..446e63f1 100644 --- a/src/n0198_house_robber.rs +++ b/src/solution/s0198_house_robber.rs @@ -2,41 +2,44 @@ * [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], 则: - i 有两种情况, 抢或不抢, 抢的话则最大收益是 F[i-2] + nums[i], - 不抢则保持和前一次结束的收益一致, 等于 F[i-1], 于是: +i 有两种情况, 抢或不抢, 抢的话则最大收益是 F[i-2] + nums[i], +不抢则保持和前一次结束的收益一致, 等于 F[i-1], 于是: - F[i] = i32::max(nums[i] + F[i-2], F[i-1]) +F[i] = i32::max(nums[i] + F[i-2], F[i-1]) - 观察到 F[i] 只依赖 F[i-1] 和 F[i-2], 可以用常数空间复杂度完成 - */ +观察到 F[i] 只依赖 F[i-1] 和 F[i-2], 可以用常数空间复杂度完成 +*/ impl Solution { pub fn rob(nums: Vec) -> i32 { let mut former_max = 0; @@ -58,8 +61,8 @@ mod tests { #[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); + 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/n0199_binary_tree_right_side_view.rs b/src/solution/s0199_binary_tree_right_side_view.rs similarity index 67% rename from src/n0199_binary_tree_right_side_view.rs rename to src/solution/s0199_binary_tree_right_side_view.rs index 94f210d1..e07dc998 100644 --- a/src/n0199_binary_tree_right_side_view.rs +++ b/src/solution/s0199_binary_tree_right_side_view.rs @@ -2,42 +2,46 @@ * [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 super::util::tree::{TreeNode, to_tree}; +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::rc::Rc; 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 } + 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())); + 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; @@ -56,6 +60,9 @@ mod tests { #[test] fn test_199() { - assert_eq!(Solution::right_side_view(tree![1,2,3,null,5,null,4]), vec![1,3,4]); + assert_eq!( + Solution::right_side_view(tree![1, 2, 3, null, 5, null, 4]), + vec![1, 3, 4] + ); } } diff --git a/src/n0200_number_of_islands.rs b/src/solution/s0200_number_of_islands.rs similarity index 66% rename from src/n0200_number_of_islands.rs rename to src/solution/s0200_number_of_islands.rs index 86081f5c..262f0315 100644 --- a/src/n0200_number_of_islands.rs +++ b/src/solution/s0200_number_of_islands.rs @@ -2,39 +2,44 @@ * [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 } + 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 { @@ -43,15 +48,15 @@ impl Solution { continue; } parent[i][j] = (i, j); - if i > 0 && grid[i-1][j] == '1' { - Solution::union(&mut parent, (i, j), (i-1, 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)); + if j > 0 && grid[i][j - 1] == '1' { + Solution::union(&mut parent, (i, j), (i, j - 1)); } } } - let mut cnt= 0; + let mut cnt = 0; for i in 0..height { for j in 0..width { if parent[i][j] == (i, j) { @@ -81,7 +86,7 @@ impl Solution { let p1 = Solution::get_parent(parent, p1); let p2 = Solution::get_parent(parent, p2); if p1 == p2 { - return + return; } parent[p1.0][p1.1] = p2 } @@ -96,25 +101,21 @@ mod tests { #[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',], - ] - ), + 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',], - ] - ), + 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/n0201_bitwise_and_of_numbers_range.rs b/src/solution/s0201_bitwise_and_of_numbers_range.rs similarity index 77% rename from src/n0201_bitwise_and_of_numbers_range.rs rename to src/solution/s0201_bitwise_and_of_numbers_range.rs index d292a442..6c46e74f 100644 --- a/src/n0201_bitwise_and_of_numbers_range.rs +++ b/src/solution/s0201_bitwise_and_of_numbers_range.rs @@ -2,22 +2,25 @@ * [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 @@ -26,13 +29,13 @@ impl Solution { let mut m = m; let mut n = n; if m == 0 { - return 0 + return 0; } let mut step = 1; while m != n { // shortcut if m == 0 { - return 0 + return 0; } m >>= 1; n >>= 1; diff --git a/src/n0202_happy_number.rs b/src/solution/s0202_happy_number.rs similarity index 82% rename from src/n0202_happy_number.rs rename to src/solution/s0202_happy_number.rs index fe62294c..076f2736 100644 --- a/src/n0202_happy_number.rs +++ b/src/solution/s0202_happy_number.rs @@ -2,23 +2,26 @@ * [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: - * - * + * + * Example: + * + * * Input: 19 * Output: true - * Explanation: + * 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; @@ -30,14 +33,14 @@ impl Solution { set.insert(n); let temp = Solution::next(n); if temp == 1 { - return true + return true; } if !set.insert(temp) { - return false + return false; } n = temp } - return false + return false; } fn next(n: i32) -> i32 { diff --git a/src/n0203_remove_linked_list_elements.rs b/src/solution/s0203_remove_linked_list_elements.rs similarity index 68% rename from src/n0203_remove_linked_list_elements.rs rename to src/solution/s0203_remove_linked_list_elements.rs index f7611261..3e48d811 100644 --- a/src/n0203_remove_linked_list_elements.rs +++ b/src/solution/s0203_remove_linked_list_elements.rs @@ -2,17 +2,20 @@ * [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 super::util::linked_list::{ListNode, to_list}; +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 @@ -39,6 +42,9 @@ mod tests { #[test] fn test_203() { - assert_eq!(Solution::remove_elements(linked![1,2,6,3,4,5,6], 6), linked![1,2,3,4,5]); + assert_eq!( + Solution::remove_elements(linked![1, 2, 6, 3, 4, 5, 6], 6), + linked![1, 2, 3, 4, 5] + ); } } diff --git a/src/n0204_count_primes.rs b/src/solution/s0204_count_primes.rs similarity index 79% rename from src/n0204_count_primes.rs rename to src/solution/s0204_count_primes.rs index df6d3a7a..d6f0f134 100644 --- a/src/n0204_count_primes.rs +++ b/src/solution/s0204_count_primes.rs @@ -2,23 +2,28 @@ * [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 } + if n <= 2 { + return 0; + } let mut is_prime = vec![true; n as usize]; is_prime[0] = false; is_prime[1] = false; @@ -26,7 +31,7 @@ impl Solution { while i * i < n { if !is_prime[i as usize] { i += 1; - continue + continue; } let mut j = i * i; while j < n { @@ -37,11 +42,12 @@ impl Solution { } let mut count = 0; for &v in is_prime.iter() { - if v { count += 1 } + if v { + count += 1 + } } count } - } // submission codes end diff --git a/src/n0205_isomorphic_strings.rs b/src/solution/s0205_isomorphic_strings.rs similarity index 64% rename from src/n0205_isomorphic_strings.rs rename to src/solution/s0205_isomorphic_strings.rs index 91730ed2..df697ebb 100644 --- a/src/n0205_isomorphic_strings.rs +++ b/src/solution/s0205_isomorphic_strings.rs @@ -2,41 +2,44 @@ * [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::collections::HashMap; -use std::collections::hash_map::Entry; 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) @@ -47,7 +50,7 @@ impl Solution { let mut start: char = '0'; let mut res = String::new(); for ch in s.chars() { - let v = map.entry(ch).or_insert_with(||{ + let v = map.entry(ch).or_insert_with(|| { start = ((start as u8) + 1) as char; start }); @@ -65,8 +68,17 @@ mod tests { #[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); + 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/n0206_reverse_linked_list.rs b/src/solution/s0206_reverse_linked_list.rs similarity index 68% rename from src/n0206_reverse_linked_list.rs rename to src/solution/s0206_reverse_linked_list.rs index 9cb97f5a..b62aced8 100644 --- a/src/n0206_reverse_linked_list.rs +++ b/src/solution/s0206_reverse_linked_list.rs @@ -16,7 +16,10 @@ * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +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 @@ -41,6 +44,9 @@ mod tests { #[test] fn test_206() { - assert_eq!(Solution::reverse_list(linked![1,2,3,4,5]), linked![5,4,3,2,1]); + assert_eq!( + Solution::reverse_list(linked![1, 2, 3, 4, 5]), + linked![5, 4, 3, 2, 1] + ); } } diff --git a/src/n0207_course_schedule.rs b/src/solution/s0207_course_schedule.rs similarity index 92% rename from src/n0207_course_schedule.rs rename to src/solution/s0207_course_schedule.rs index 2222adad..2a793683 100644 --- a/src/n0207_course_schedule.rs +++ b/src/solution/s0207_course_schedule.rs @@ -35,6 +35,9 @@ */ 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 diff --git a/src/n0208_implement_trie_prefix_tree.rs b/src/solution/s0208_implement_trie_prefix_tree.rs similarity index 92% rename from src/n0208_implement_trie_prefix_tree.rs rename to src/solution/s0208_implement_trie_prefix_tree.rs index be29d61b..9ac8e470 100644 --- a/src/n0208_implement_trie_prefix_tree.rs +++ b/src/solution/s0208_implement_trie_prefix_tree.rs @@ -26,6 +26,9 @@ */ 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)] diff --git a/src/n0209_minimum_size_subarray_sum.rs b/src/solution/s0209_minimum_size_subarray_sum.rs similarity index 77% rename from src/n0209_minimum_size_subarray_sum.rs rename to src/solution/s0209_minimum_size_subarray_sum.rs index ff7ff206..b6a692d7 100644 --- a/src/n0209_minimum_size_subarray_sum.rs +++ b/src/solution/s0209_minimum_size_subarray_sum.rs @@ -17,6 +17,9 @@ */ 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 { @@ -36,12 +39,15 @@ impl Solution { min = i32::min(min, j as i32 - i as i32 + 2); break; } - } } j += 1; } - if found { min } else { 0 } + if found { + min + } else { + 0 + } } } @@ -53,11 +59,7 @@ mod tests { #[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); + 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/n0210_course_schedule_ii.rs b/src/solution/s0210_course_schedule_ii.rs similarity index 87% rename from src/n0210_course_schedule_ii.rs rename to src/solution/s0210_course_schedule_ii.rs index 4b154595..dd3a1b03 100644 --- a/src/n0210_course_schedule_ii.rs +++ b/src/solution/s0210_course_schedule_ii.rs @@ -36,6 +36,9 @@ */ 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; @@ -70,7 +73,11 @@ impl Solution { } } } - if res.len() == num { res } else { vec![] } + if res.len() == num { + res + } else { + vec![] + } } } @@ -83,6 +90,9 @@ mod tests { #[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]); + 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/n0211_add_and_search_word_data_structure_design.rs b/src/solution/s0211_add_and_search_word_data_structure_design.rs similarity index 93% rename from src/n0211_add_and_search_word_data_structure_design.rs rename to src/solution/s0211_add_and_search_word_data_structure_design.rs index a2cbff82..0652f951 100644 --- a/src/n0211_add_and_search_word_data_structure_design.rs +++ b/src/solution/s0211_add_and_search_word_data_structure_design.rs @@ -28,8 +28,10 @@ */ pub struct Solution {} -// submission codes start here +// 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>, @@ -124,5 +126,4 @@ mod tests { // assert_eq!(dict.search(".ad".to_owned()), true); // assert_eq!(dict.search("da.".to_owned()), true); } - } diff --git a/src/n0212_word_search_ii.rs b/src/solution/s0212_word_search_ii.rs similarity index 87% rename from src/n0212_word_search_ii.rs rename to src/solution/s0212_word_search_ii.rs index 77914f04..ada034c8 100644 --- a/src/n0212_word_search_ii.rs +++ b/src/solution/s0212_word_search_ii.rs @@ -34,6 +34,9 @@ */ 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 diff --git a/src/n0213_house_robber_ii.rs b/src/solution/s0213_house_robber_ii.rs similarity index 84% rename from src/n0213_house_robber_ii.rs rename to src/solution/s0213_house_robber_ii.rs index 495a8d26..fbe55040 100644 --- a/src/n0213_house_robber_ii.rs +++ b/src/solution/s0213_house_robber_ii.rs @@ -25,6 +25,9 @@ */ 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 @@ -36,11 +39,11 @@ impl Solution { let (mut prev, mut curr) = (0, 0); for (k, &num) in nums.iter().enumerate() { if k == 0 && !rob_first { - continue + continue; } // k is last element but not the first element if k != 0 && k == (nums.len() - 1) && rob_first { - continue + continue; } let next = i32::max(prev + num, curr); prev = curr; @@ -60,7 +63,7 @@ mod tests { #[test] fn test_213() { - assert_eq!(Solution::rob(vec![2,3,2]), 3); - assert_eq!(Solution::rob(vec![1,2,3,1]), 4); + assert_eq!(Solution::rob(vec![2, 3, 2]), 3); + assert_eq!(Solution::rob(vec![1, 2, 3, 1]), 4); } } diff --git a/src/n0214_shortest_palindrome.rs b/src/solution/s0214_shortest_palindrome.rs similarity index 78% rename from src/n0214_shortest_palindrome.rs rename to src/solution/s0214_shortest_palindrome.rs index a8a23c60..425eec95 100644 --- a/src/n0214_shortest_palindrome.rs +++ b/src/solution/s0214_shortest_palindrome.rs @@ -18,6 +18,9 @@ */ 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 { diff --git a/src/n0215_kth_largest_element_in_an_array.rs b/src/solution/s0215_kth_largest_element_in_an_array.rs similarity index 74% rename from src/n0215_kth_largest_element_in_an_array.rs rename to src/solution/s0215_kth_largest_element_in_an_array.rs index 56b2c3ca..159e7af6 100644 --- a/src/n0215_kth_largest_element_in_an_array.rs +++ b/src/solution/s0215_kth_largest_element_in_an_array.rs @@ -22,10 +22,13 @@ */ 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::collections::BinaryHeap; 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; @@ -50,13 +53,10 @@ mod tests { #[test] fn test_215() { - assert_eq!(Solution::find_kth_largest( - vec![3, 2, 3, 1, 2, 4, 5, 5, 6], + assert_eq!( + Solution::find_kth_largest(vec![3, 2, 3, 1, 2, 4, 5, 5, 6], 4), 4 - ), 4); - assert_eq!(Solution::find_kth_largest( - vec![3,2,1,5,6,4], - 2 - ), 5); + ); + assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5); } } diff --git a/src/n0216_combination_sum_iii.rs b/src/solution/s0216_combination_sum_iii.rs similarity index 72% rename from src/n0216_combination_sum_iii.rs rename to src/solution/s0216_combination_sum_iii.rs index f2342f01..0f714e01 100644 --- a/src/n0216_combination_sum_iii.rs +++ b/src/solution/s0216_combination_sum_iii.rs @@ -28,17 +28,20 @@ */ 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![] + return vec![]; } - let max = (0..k).fold(0, |acc, t| { acc + 9 - t }); - let min = (0..k).fold(0, |acc, t| { acc + t }); + 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![] + return vec![]; } let mut res = Vec::new(); let mut seed = Vec::new(); @@ -51,9 +54,9 @@ impl Solution { if distance == 0 { res.push(curr); } - return + return; } - for i in (prev+1..=9) { + for i in (prev + 1..=9) { if distance - i < 0 { break; } @@ -72,6 +75,9 @@ mod tests { #[test] fn test_216() { - assert_eq!(Solution::combination_sum3(3, 9), vec![vec![1,2,6],vec![1,3,5], vec![2,3,4]]); + assert_eq!( + Solution::combination_sum3(3, 9), + vec![vec![1, 2, 6], vec![1, 3, 5], vec![2, 3, 4]] + ); } } diff --git a/src/n0217_contains_duplicate.rs b/src/solution/s0217_contains_duplicate.rs similarity index 71% rename from src/n0217_contains_duplicate.rs rename to src/solution/s0217_contains_duplicate.rs index c49f64a1..0d2e5e12 100644 --- a/src/n0217_contains_duplicate.rs +++ b/src/solution/s0217_contains_duplicate.rs @@ -26,17 +26,22 @@ */ 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 } + 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 + return true; } prev = nums[i] } @@ -54,7 +59,7 @@ mod tests { 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); + 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/n0218_the_skyline_problem.rs b/src/solution/s0218_the_skyline_problem.rs similarity index 94% rename from src/n0218_the_skyline_problem.rs rename to src/solution/s0218_the_skyline_problem.rs index 9e774db0..7f0ba3c1 100644 --- a/src/n0218_the_skyline_problem.rs +++ b/src/solution/s0218_the_skyline_problem.rs @@ -24,6 +24,9 @@ */ 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 { diff --git a/src/n0219_contains_duplicate_ii.rs b/src/solution/s0219_contains_duplicate_ii.rs similarity index 73% rename from src/n0219_contains_duplicate_ii.rs rename to src/solution/s0219_contains_duplicate_ii.rs index 5f9a0b1c..da446dae 100644 --- a/src/n0219_contains_duplicate_ii.rs +++ b/src/solution/s0219_contains_duplicate_ii.rs @@ -33,6 +33,9 @@ */ 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; @@ -46,8 +49,10 @@ impl Solution { return true; } map.insert(num, idx); - }, - None => { map.insert(num, idx); }, + } + None => { + map.insert(num, idx); + } } } false @@ -62,7 +67,13 @@ mod tests { #[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); + 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/n0220_contains_duplicate_iii.rs b/src/solution/s0220_contains_duplicate_iii.rs similarity index 70% rename from src/n0220_contains_duplicate_iii.rs rename to src/solution/s0220_contains_duplicate_iii.rs index d7c60991..0677b1d3 100644 --- a/src/n0220_contains_duplicate_iii.rs +++ b/src/solution/s0220_contains_duplicate_iii.rs @@ -33,23 +33,34 @@ */ 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 } + 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 + || 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); + 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); @@ -68,6 +79,9 @@ mod tests { 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); + 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 new file mode 100644 index 00000000..34f793ac --- /dev/null +++ b/src/solution/s0221_maximal_square.rs @@ -0,0 +1,84 @@ +/** + * [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/n0222_count_complete_tree_nodes.rs b/src/solution/s0222_count_complete_tree_nodes.rs similarity index 78% rename from src/n0222_count_complete_tree_nodes.rs rename to src/solution/s0222_count_complete_tree_nodes.rs index df44949b..ae0d410b 100644 --- a/src/n0222_count_complete_tree_nodes.rs +++ b/src/solution/s0222_count_complete_tree_nodes.rs @@ -22,12 +22,15 @@ * */ pub struct Solution {} -use super::util::tree::{to_tree, TreeNode}; +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::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn count_nodes(root: Option>>) -> i32 { // 0. get the hight of full nodes @@ -36,10 +39,12 @@ impl Solution { let mut result = 0; while let Some(inner) = curr { height += 1; - result += 2_i32.pow(height-1); + result += 2_i32.pow(height - 1); curr = inner.borrow().right.clone(); } - if height == 0 { return result } + 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(); @@ -53,7 +58,7 @@ impl Solution { } if node.unwrap().borrow().right.is_some() { curr_root = curr_root.unwrap().borrow().right.clone(); - result += 2_i32.pow(height-1); + result += 2_i32.pow(height - 1); } else { curr_root = curr_root.unwrap().borrow().left.clone(); } @@ -74,10 +79,10 @@ mod tests { #[test] fn test_222() { - assert_eq!(Solution::count_nodes(tree![1,1,1,1,1,1,1]), 7); + 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]), 2); assert_eq!(Solution::count_nodes(tree![1]), 1); - assert_eq!(Solution::count_nodes(tree![1,1,1]), 3); + assert_eq!(Solution::count_nodes(tree![1, 1, 1]), 3); } } diff --git a/src/n0223_rectangle_area.rs b/src/solution/s0223_rectangle_area.rs similarity index 72% rename from src/n0223_rectangle_area.rs rename to src/solution/s0223_rectangle_area.rs index 1604e8f7..647b6b2a 100644 --- a/src/n0223_rectangle_area.rs +++ b/src/solution/s0223_rectangle_area.rs @@ -20,18 +20,27 @@ */ 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 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 = 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 } diff --git a/src/n0224_basic_calculator.rs b/src/solution/s0224_basic_calculator.rs similarity index 76% rename from src/n0224_basic_calculator.rs rename to src/solution/s0224_basic_calculator.rs index e448a0ab..5d917661 100644 --- a/src/n0224_basic_calculator.rs +++ b/src/solution/s0224_basic_calculator.rs @@ -33,9 +33,12 @@ */ 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)] +#[derive(PartialEq, Copy, Clone, Debug)] enum Token { LeftBracket, RightBracket, @@ -52,7 +55,7 @@ impl Solution { let mut in_num = false; for ch in s.chars() { match ch { - '0'...'9' => { + '0'..='9' => { in_num = true; num = 10 * num + (ch as u8 - '0' as u8) as i64; } @@ -63,20 +66,27 @@ impl Solution { 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); }, - _ => {}, + '(' => { + 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(); @@ -95,35 +105,36 @@ impl Solution { 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 }; + 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 + return num as i32; } 0 } diff --git a/src/n0225_implement_stack_using_queues.rs b/src/solution/s0225_implement_stack_using_queues.rs similarity index 90% rename from src/n0225_implement_stack_using_queues.rs rename to src/solution/s0225_implement_stack_using_queues.rs index 9d449490..f162e9a6 100644 --- a/src/n0225_implement_stack_using_queues.rs +++ b/src/solution/s0225_implement_stack_using_queues.rs @@ -32,6 +32,9 @@ */ 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 { @@ -47,7 +50,7 @@ use std::collections::VecDeque; impl MyStack { /** Initialize your data structure here. */ fn new() -> Self { - MyStack{ + MyStack { q1: VecDeque::new(), q2: VecDeque::new(), } @@ -113,8 +116,8 @@ mod tests { stack.push(1); stack.push(2); - assert_eq!(stack.top(), 2); // returns 2 - assert_eq!(stack.pop(), 2); // returns 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/n0226_invert_binary_tree.rs b/src/solution/s0226_invert_binary_tree.rs similarity index 79% rename from src/n0226_invert_binary_tree.rs rename to src/solution/s0226_invert_binary_tree.rs index c41bda74..1a1b6115 100644 --- a/src/n0226_invert_binary_tree.rs +++ b/src/solution/s0226_invert_binary_tree.rs @@ -30,7 +30,10 @@ * */ pub struct Solution {} -use super::util::tree::{to_tree, TreeNode}; +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 @@ -58,6 +61,9 @@ mod tests { #[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]); + 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/n0227_basic_calculator_ii.rs b/src/solution/s0227_basic_calculator_ii.rs similarity index 82% rename from src/n0227_basic_calculator_ii.rs rename to src/solution/s0227_basic_calculator_ii.rs index 06fb2e5b..07e349dd 100644 --- a/src/n0227_basic_calculator_ii.rs +++ b/src/solution/s0227_basic_calculator_ii.rs @@ -35,6 +35,9 @@ */ 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 { @@ -47,7 +50,9 @@ impl Solution { let mut multiple = true; for ch in s.chars() { match ch { - '0'...'9' => { curr = 10 * curr + (ch as u8 - '0' as u8) as i64; }, + '0'..='9' => { + curr = 10 * curr + (ch as u8 - '0' as u8) as i64; + } '+' | '-' => { if has_prev { if multiple { @@ -58,9 +63,9 @@ impl Solution { has_prev = false; } acc += curr * sign; - curr = 0; - sign = if ch == '+' { 1 } else { -1 }; - } + curr = 0; + sign = if ch == '+' { 1 } else { -1 }; + } '*' | '/' => { if has_prev { if multiple { @@ -73,8 +78,8 @@ impl Solution { prev = curr; curr = 0; multiple = if ch == '*' { true } else { false }; - }, - _ => {}, + } + _ => {} } } if has_prev { @@ -91,7 +96,7 @@ impl Solution { // submission codes end - #[cfg(test)] +#[cfg(test)] mod tests { use super::*; diff --git a/src/n0228_summary_ranges.rs b/src/solution/s0228_summary_ranges.rs similarity index 79% rename from src/n0228_summary_ranges.rs rename to src/solution/s0228_summary_ranges.rs index e99dbad2..63e8fe77 100644 --- a/src/n0228_summary_ranges.rs +++ b/src/solution/s0228_summary_ranges.rs @@ -22,11 +22,16 @@ */ 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![] } + if nums.is_empty() { + return vec![]; + } let mut res = Vec::new(); let mut curr = nums[0]; let mut start = nums[0]; @@ -61,6 +66,9 @@ mod tests { #[test] fn test_228() { - assert_eq!(Solution::summary_ranges(vec![0,1,2,3,4,5,6]), vec_string!["0->6"]); + assert_eq!( + Solution::summary_ranges(vec![0, 1, 2, 3, 4, 5, 6]), + vec_string!["0->6"] + ); } } diff --git a/src/n0229_majority_element_ii.rs b/src/solution/s0229_majority_element_ii.rs similarity index 72% rename from src/n0229_majority_element_ii.rs rename to src/solution/s0229_majority_element_ii.rs index 7cbf6951..fab987ba 100644 --- a/src/n0229_majority_element_ii.rs +++ b/src/solution/s0229_majority_element_ii.rs @@ -20,11 +20,16 @@ */ 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![] } + 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 { @@ -67,10 +72,16 @@ mod tests { #[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, 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![]); + 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/n0230_kth_smallest_element_in_a_bst.rs b/src/solution/s0230_kth_smallest_element_in_a_bst.rs similarity index 76% rename from src/n0230_kth_smallest_element_in_a_bst.rs rename to src/solution/s0230_kth_smallest_element_in_a_bst.rs index c9063617..0533f705 100644 --- a/src/n0230_kth_smallest_element_in_a_bst.rs +++ b/src/solution/s0230_kth_smallest_element_in_a_bst.rs @@ -36,7 +36,10 @@ * */ pub struct Solution {} -use super::util::tree::{to_tree, TreeNode}; +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 @@ -51,7 +54,7 @@ impl Solution { pub fn helper(root: Option>>, k: i32, res: &mut i32) -> i32 { if k <= 0 { - return 0 + return 0; } if let Some(node) = root { let left = Solution::helper(node.borrow().left.clone(), k, res); @@ -74,8 +77,8 @@ mod tests { #[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); + 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/n0231_power_of_two.rs b/src/solution/s0231_power_of_two.rs similarity index 83% rename from src/n0231_power_of_two.rs rename to src/solution/s0231_power_of_two.rs index 683dfc91..334fc314 100644 --- a/src/n0231_power_of_two.rs +++ b/src/solution/s0231_power_of_two.rs @@ -27,6 +27,9 @@ */ pub struct Solution {} +// problem: https://leetcode.com/problems/power-of-two/ +// discuss: https://leetcode.com/problems/power-of-two/discuss/?currentPage=1&orderBy=most_votes&query= + // submission codes start here impl Solution { diff --git a/src/n0232_implement_queue_using_stacks.rs b/src/solution/s0232_implement_queue_using_stacks.rs similarity index 89% rename from src/n0232_implement_queue_using_stacks.rs rename to src/solution/s0232_implement_queue_using_stacks.rs index a142bd1c..70bf3735 100644 --- a/src/n0232_implement_queue_using_stacks.rs +++ b/src/solution/s0232_implement_queue_using_stacks.rs @@ -32,6 +32,9 @@ */ 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 { @@ -46,7 +49,7 @@ struct MyQueue { impl MyQueue { /** Initialize your data structure here. */ fn new() -> Self { - MyQueue{ + MyQueue { vec1: Vec::new(), vec2: Vec::new(), } @@ -100,8 +103,8 @@ mod tests { queue.push(1); queue.push(2); - assert_eq!(queue.peek(), 1); // returns 1 - assert_eq!(queue.pop(), 1); // returns 1 + 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/n0233_number_of_digit_one.rs b/src/solution/s0233_number_of_digit_one.rs similarity index 75% rename from src/n0233_number_of_digit_one.rs rename to src/solution/s0233_number_of_digit_one.rs index 74c0091c..60097ed0 100644 --- a/src/n0233_number_of_digit_one.rs +++ b/src/solution/s0233_number_of_digit_one.rs @@ -14,6 +14,9 @@ */ pub struct Solution {} +// problem: https://leetcode.com/problems/number-of-digit-one/ +// discuss: https://leetcode.com/problems/number-of-digit-one/discuss/?currentPage=1&orderBy=most_votes&query= + // submission codes start here impl Solution { diff --git a/src/n0238_product_of_array_except_self.rs b/src/solution/s0238_product_of_array_except_self.rs similarity index 67% rename from src/n0238_product_of_array_except_self.rs rename to src/solution/s0238_product_of_array_except_self.rs index 294eca4f..ef5683c4 100644 --- a/src/n0238_product_of_array_except_self.rs +++ b/src/solution/s0238_product_of_array_except_self.rs @@ -18,6 +18,9 @@ */ 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 /* @@ -28,16 +31,18 @@ x 2 3 4 = 24 */ impl Solution { pub fn product_except_self(nums: Vec) -> Vec { - if nums.len() < 2 { return 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]; + 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]; + n *= nums[i - 1]; res[i] *= n; } res @@ -52,6 +57,9 @@ mod tests { #[test] fn test_238() { - assert_eq!(Solution::product_except_self(vec![1,2,3,4]), vec![24,12,8,6]); + assert_eq!( + Solution::product_except_self(vec![1, 2, 3, 4]), + vec![24, 12, 8, 6] + ); } } diff --git a/src/n0239_sliding_window_maximum.rs b/src/solution/s0239_sliding_window_maximum.rs similarity index 74% rename from src/n0239_sliding_window_maximum.rs rename to src/solution/s0239_sliding_window_maximum.rs index 3685bb53..f7509cb9 100644 --- a/src/n0239_sliding_window_maximum.rs +++ b/src/solution/s0239_sliding_window_maximum.rs @@ -28,6 +28,9 @@ */ 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; @@ -74,10 +77,19 @@ mod tests { #[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]); + 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/n0241_different_ways_to_add_parentheses.rs b/src/solution/s0241_different_ways_to_add_parentheses.rs similarity index 75% rename from src/n0241_different_ways_to_add_parentheses.rs rename to src/solution/s0241_different_ways_to_add_parentheses.rs index 81070d49..a76bfa6a 100644 --- a/src/n0241_different_ways_to_add_parentheses.rs +++ b/src/solution/s0241_different_ways_to_add_parentheses.rs @@ -27,6 +27,9 @@ */ 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 { @@ -35,15 +38,17 @@ impl Solution { } pub fn helper(input: &str) -> Vec { - if input.is_empty() { return vec![] } + if input.is_empty() { + return vec![]; + } if let Ok(digit) = input.parse::() { - return vec![digit] + 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..]); + let right = Solution::helper(&input[i + 1..]); for &a in left.iter() { for &b in right.iter() { res.push(match ch { @@ -68,6 +73,9 @@ mod tests { #[test] fn test_241() { - assert_eq!(Solution::diff_ways_to_compute("2*3-4*5".to_owned()), vec![-34, -10, -14, -10, 10]); + assert_eq!( + Solution::diff_ways_to_compute("2*3-4*5".to_owned()), + vec![-34, -10, -14, -10, 10] + ); } } diff --git a/src/n0242_valid_anagram.rs b/src/solution/s0242_valid_anagram.rs similarity index 73% rename from src/n0242_valid_anagram.rs rename to src/solution/s0242_valid_anagram.rs index 12405169..ba7a58ae 100644 --- a/src/n0242_valid_anagram.rs +++ b/src/solution/s0242_valid_anagram.rs @@ -26,6 +26,9 @@ */ 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 { @@ -34,7 +37,7 @@ impl Solution { } fn hit(s: String) -> Vec { - let mut hit = vec![0;27]; + let mut hit = vec![0; 27]; for ch in s.chars() { hit[(ch as u8 - 'a' as u8) as usize] += 1; } @@ -50,6 +53,9 @@ mod tests { #[test] fn test_242() { - assert_eq!(Solution::is_anagram("anagram".to_owned(), "nagaram".to_owned()), true); + assert_eq!( + Solution::is_anagram("anagram".to_owned(), "nagaram".to_owned()), + true + ); } } diff --git a/src/n0257_binary_tree_paths.rs b/src/solution/s0257_binary_tree_paths.rs similarity index 82% rename from src/n0257_binary_tree_paths.rs rename to src/solution/s0257_binary_tree_paths.rs index 3ecde0cb..6c7833e2 100644 --- a/src/n0257_binary_tree_paths.rs +++ b/src/solution/s0257_binary_tree_paths.rs @@ -22,7 +22,10 @@ * */ pub struct Solution {} -use super::util::tree::{to_tree, TreeNode}; +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 @@ -74,6 +77,9 @@ mod tests { #[test] fn test_257() { - assert_eq!(Solution::binary_tree_paths(tree![1,2,3,null,5]), vec_string!["1->2->5", "1->3"]); + assert_eq!( + Solution::binary_tree_paths(tree![1, 2, 3, null, 5]), + vec_string!["1->2->5", "1->3"] + ); } } diff --git a/src/n0258_add_digits.rs b/src/solution/s0258_add_digits.rs similarity index 81% rename from src/n0258_add_digits.rs rename to src/solution/s0258_add_digits.rs index 1ebeda42..2248be1d 100644 --- a/src/n0258_add_digits.rs +++ b/src/solution/s0258_add_digits.rs @@ -17,6 +17,9 @@ */ 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 { diff --git a/src/n0260_single_number_iii.rs b/src/solution/s0260_single_number_iii.rs similarity index 78% rename from src/n0260_single_number_iii.rs rename to src/solution/s0260_single_number_iii.rs index d7a0f431..09d7a920 100644 --- a/src/n0260_single_number_iii.rs +++ b/src/solution/s0260_single_number_iii.rs @@ -18,6 +18,9 @@ */ 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 { @@ -48,7 +51,7 @@ mod tests { #[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]); + 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/n0263_ugly_number.rs b/src/solution/s0263_ugly_number.rs similarity index 80% rename from src/n0263_ugly_number.rs rename to src/solution/s0263_ugly_number.rs index c519d5f8..9ef3bf57 100644 --- a/src/n0263_ugly_number.rs +++ b/src/solution/s0263_ugly_number.rs @@ -37,6 +37,9 @@ */ 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 { @@ -46,11 +49,11 @@ impl Solution { } else if num == 1 { true } else if num % 5 == 0 { - Solution::is_ugly(num/5) + Solution::is_ugly(num / 5) } else if num % 3 == 0 { - Solution::is_ugly(num/3) + Solution::is_ugly(num / 3) } else if num % 2 == 0 { - Solution::is_ugly(num/2) + Solution::is_ugly(num / 2) } else { false } diff --git a/src/n0264_ugly_number_ii.rs b/src/solution/s0264_ugly_number_ii.rs similarity index 72% rename from src/n0264_ugly_number_ii.rs rename to src/solution/s0264_ugly_number_ii.rs index 428c4e80..8dda4f01 100644 --- a/src/n0264_ugly_number_ii.rs +++ b/src/solution/s0264_ugly_number_ii.rs @@ -21,6 +21,9 @@ */ 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 { @@ -28,15 +31,21 @@ impl Solution { let mut base2 = 0; let mut base3 = 0; let mut base5 = 0; - let mut ugly = vec![1;1]; + 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 } + if next2 == next { + base2 += 1 + } + if next3 == next { + base3 += 1 + } + if next5 == next { + base5 += 1 + } ugly.push(next) } *ugly.last().unwrap() diff --git a/src/n0268_missing_number.rs b/src/solution/s0268_missing_number.rs similarity index 67% rename from src/n0268_missing_number.rs rename to src/solution/s0268_missing_number.rs index ce7ca3d5..63291ee0 100644 --- a/src/n0268_missing_number.rs +++ b/src/solution/s0268_missing_number.rs @@ -22,11 +22,14 @@ */ 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 }) + ((nums.len() + 1) * nums.len()) as i32 / 2 - nums.into_iter().fold(0, |acc, v| acc + v) } } @@ -38,6 +41,6 @@ mod tests { #[test] fn test_268() { - assert_eq!(Solution::missing_number(vec![3,0,1]), 2); + assert_eq!(Solution::missing_number(vec![3, 0, 1]), 2); } } diff --git a/src/n0273_integer_to_english_words.rs b/src/solution/s0273_integer_to_english_words.rs similarity index 88% rename from src/n0273_integer_to_english_words.rs rename to src/solution/s0273_integer_to_english_words.rs index 7119014d..123a1f9d 100644 --- a/src/n0273_integer_to_english_words.rs +++ b/src/solution/s0273_integer_to_english_words.rs @@ -33,6 +33,9 @@ */ 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"]; diff --git a/src/n0274_h_index.rs b/src/solution/s0274_h_index.rs similarity index 86% rename from src/n0274_h_index.rs rename to src/solution/s0274_h_index.rs index 9e4aea5c..b36f65a3 100644 --- a/src/n0274_h_index.rs +++ b/src/solution/s0274_h_index.rs @@ -20,6 +20,9 @@ */ 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 { @@ -45,6 +48,6 @@ mod tests { #[test] fn test_274() { - assert_eq!(Solution::h_index(vec![3,0,6,1,5]), 3); + assert_eq!(Solution::h_index(vec![3, 0, 6, 1, 5]), 3); } } diff --git a/src/n0275_h_index_ii.rs b/src/solution/s0275_h_index_ii.rs similarity index 82% rename from src/n0275_h_index_ii.rs rename to src/solution/s0275_h_index_ii.rs index 7ac39a0f..027ad02a 100644 --- a/src/n0275_h_index_ii.rs +++ b/src/solution/s0275_h_index_ii.rs @@ -29,17 +29,24 @@ */ 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 } + 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 } + if mid == 0 { + break; + } high = mid - 1; } else { low = mid + 1; @@ -61,7 +68,7 @@ mod tests { 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); + 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/n0279_perfect_squares.rs b/src/solution/s0279_perfect_squares.rs similarity index 78% rename from src/n0279_perfect_squares.rs rename to src/solution/s0279_perfect_squares.rs index 60419c54..fe5f0a01 100644 --- a/src/n0279_perfect_squares.rs +++ b/src/solution/s0279_perfect_squares.rs @@ -19,20 +19,25 @@ */ 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 } + if n < 1 { + return 0; + } let mut deq = VecDeque::new(); - deq.push_back((1,n)); + 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 + return level; } deq.push_back((level + 1, num - base * base)); base += 1; diff --git a/src/n0282_expression_add_operators.rs b/src/solution/s0282_expression_add_operators.rs similarity index 83% rename from src/n0282_expression_add_operators.rs rename to src/solution/s0282_expression_add_operators.rs index a1c9d776..1c41367b 100644 --- a/src/n0282_expression_add_operators.rs +++ b/src/solution/s0282_expression_add_operators.rs @@ -39,6 +39,9 @@ */ 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 { diff --git a/src/n0283_move_zeroes.rs b/src/solution/s0283_move_zeroes.rs similarity index 77% rename from src/n0283_move_zeroes.rs rename to src/solution/s0283_move_zeroes.rs index e5949435..6581bcaf 100644 --- a/src/n0283_move_zeroes.rs +++ b/src/solution/s0283_move_zeroes.rs @@ -18,6 +18,9 @@ */ 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 { @@ -40,8 +43,8 @@ mod tests { #[test] fn test_283() { - let mut vec = vec![0,1,0,3,12]; + let mut vec = vec![0, 1, 0, 3, 12]; Solution::move_zeroes(&mut vec); - assert_eq!(vec, vec![1,3,12,0,0]); + assert_eq!(vec, vec![1, 3, 12, 0, 0]); } } diff --git a/src/n0287_find_the_duplicate_number.rs b/src/solution/s0287_find_the_duplicate_number.rs similarity index 79% rename from src/n0287_find_the_duplicate_number.rs rename to src/solution/s0287_find_the_duplicate_number.rs index b6dfe573..cea65001 100644 --- a/src/n0287_find_the_duplicate_number.rs +++ b/src/solution/s0287_find_the_duplicate_number.rs @@ -28,6 +28,9 @@ */ 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 的下标, 那么: @@ -63,9 +66,9 @@ mod tests { #[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); + 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 new file mode 100644 index 00000000..53d34623 --- /dev/null +++ b/src/solution/s0289_game_of_life.rs @@ -0,0 +1,118 @@ +/** + * [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 new file mode 100644 index 00000000..c758f352 --- /dev/null +++ b/src/solution/s0290_word_pattern.rs @@ -0,0 +1,86 @@ +/** + * [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 new file mode 100644 index 00000000..4c46505c --- /dev/null +++ b/src/solution/s0292_nim_game.rs @@ -0,0 +1,40 @@ +/** + * [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 new file mode 100644 index 00000000..02dc5331 --- /dev/null +++ b/src/solution/s0295_find_median_from_data_stream.rs @@ -0,0 +1,136 @@ +/** + * [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 new file mode 100644 index 00000000..08525c71 --- /dev/null +++ b/src/solution/s0299_bulls_and_cows.rs @@ -0,0 +1,80 @@ +/** + * [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 new file mode 100644 index 00000000..c0b7eb27 --- /dev/null +++ b/src/solution/s0300_longest_increasing_subsequence.rs @@ -0,0 +1,57 @@ +/** + * [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 new file mode 100644 index 00000000..2cec757c --- /dev/null +++ b/src/solution/s0301_remove_invalid_parentheses.rs @@ -0,0 +1,131 @@ +/** + * [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 new file mode 100644 index 00000000..c56f8ae9 --- /dev/null +++ b/src/solution/s0303_range_sum_query_immutable.rs @@ -0,0 +1,74 @@ +/** + * [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 new file mode 100644 index 00000000..42a0f41f --- /dev/null +++ b/src/solution/s0304_range_sum_query_2d_immutable.rs @@ -0,0 +1,124 @@ +/** + * [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 new file mode 100644 index 00000000..38f6c0b2 --- /dev/null +++ b/src/solution/s0306_additive_number.rs @@ -0,0 +1,113 @@ +/** + * [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 new file mode 100644 index 00000000..bbaac119 --- /dev/null +++ b/src/solution/s0307_range_sum_query_mutable.rs @@ -0,0 +1,151 @@ +/** + * [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 new file mode 100644 index 00000000..6f3e911d --- /dev/null +++ b/src/solution/s0309_best_time_to_buy_and_sell_stock_with_cooldown.rs @@ -0,0 +1,79 @@ +/** + * [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 new file mode 100644 index 00000000..4141273c --- /dev/null +++ b/src/solution/s0310_minimum_height_trees.rs @@ -0,0 +1,110 @@ +/** + * [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 new file mode 100644 index 00000000..f8833b5e --- /dev/null +++ b/src/solution/s0312_burst_balloons.rs @@ -0,0 +1,108 @@ +/** + * [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 new file mode 100644 index 00000000..bf99bcc8 --- /dev/null +++ b/src/solution/s0313_super_ugly_number.rs @@ -0,0 +1,94 @@ +/** + * [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 new file mode 100644 index 00000000..47a9b420 --- /dev/null +++ b/src/solution/s0509_fibonacci_number.rs @@ -0,0 +1,78 @@ +/** + * [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/s0704_binary_search.rs b/src/solution/s0704_binary_search.rs new file mode 100644 index 00000000..26ed0c8d --- /dev/null +++ b/src/solution/s0704_binary_search.rs @@ -0,0 +1,83 @@ +/** + * [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/s0969_pancake_sorting.rs b/src/solution/s0969_pancake_sorting.rs new file mode 100644 index 00000000..541ae423 --- /dev/null +++ b/src/solution/s0969_pancake_sorting.rs @@ -0,0 +1,148 @@ +/** + * [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 new file mode 100644 index 00000000..b2bb1839 --- /dev/null +++ b/src/solution/s1018_binary_prefix_divisible_by_5.rs @@ -0,0 +1,106 @@ +/** + * [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 new file mode 100644 index 00000000..871b4eb4 --- /dev/null +++ b/src/solution/s1046_last_stone_weight.rs @@ -0,0 +1,78 @@ +/** + * [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/util/linked_list.rs b/src/util/linked_list.rs index 6fd4ec6f..37b18e3d 100644 --- a/src/util/linked_list.rs +++ b/src/util/linked_list.rs @@ -1,16 +1,13 @@ #[derive(PartialEq, Eq, Debug)] pub struct ListNode { pub val: i32, - pub next: Option> + pub next: Option>, } impl ListNode { #[inline] pub fn new(val: i32) -> Self { - ListNode { - next: None, - val - } + ListNode { next: None, val } } } diff --git a/src/util/mod.rs b/src/util/mod.rs index b214c465..5a3e5744 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -5,4 +5,4 @@ pub mod vec_string; #[macro_use] pub mod tree; #[macro_use] -pub mod point; \ No newline at end of file +pub mod point; diff --git a/src/util/point.rs b/src/util/point.rs index 1cf308da..3af0c803 100644 --- a/src/util/point.rs +++ b/src/util/point.rs @@ -7,10 +7,7 @@ pub struct Point { impl Point { #[inline] pub fn new(x: i32, y: i32) -> Self { - Point { - x, - y - } + Point { x, y } } } diff --git a/src/util/testing.rs b/src/util/testing.rs index e69de29b..8b137891 100644 --- a/src/util/testing.rs +++ b/src/util/testing.rs @@ -0,0 +1 @@ + diff --git a/src/util/tree.rs b/src/util/tree.rs index 7c3076b1..dacda57d 100644 --- a/src/util/tree.rs +++ b/src/util/tree.rs @@ -1,5 +1,5 @@ -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { @@ -14,7 +14,7 @@ impl TreeNode { TreeNode { val, left: None, - right: None + right: None, } } } @@ -55,4 +55,3 @@ macro_rules! tree { }; ($($e:expr,)*) => {(tree![$($e),*])}; } - diff --git a/template.rs b/template.rs index 06c5c06d..11411f01 100644 --- a/template.rs +++ b/template.rs @@ -5,6 +5,9 @@ */ pub struct Solution {}__EXTRA_USE__ +// problem: __PROBLEM_LINK__ +// discuss: __DISCUSS_LINK__ + // submission codes start here __PROBLEM_DEFAULT_CODE__