From 9333e5e144212ba33de568c466db369377569d3e Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 11 Mar 2026 22:31:31 +0800 Subject: [PATCH] feat: fetch problem by pwsh script. Remove old C++ fetcher. --- .clang-format | 164 +---------- CMakeLists.txt | 8 - build.ps1 | 89 ++++++ justfile | 3 - main.cpp | 15 - src/fetcher.cpp | 276 ------------------ src/problems/0001-two-sum.cpp | 34 +++ src/problems/1-two-sum.cpp | 40 --- ...e-you-can-get-from-changing-an-integer.cpp | 130 ++++----- ...difference-between-increasing-elements.cpp | 52 ++-- ...rray-such-that-maximum-difference-is-k.cpp | 58 ++-- ...aximum-difference-by-remapping-a-digit.cpp | 94 +++--- ...nimize-the-maximum-difference-of-pairs.cpp | 71 ++--- ...-array-into-arrays-with-max-difference.cpp | 58 ++-- ...rays-with-k-matching-adjacent-elements.cpp | 95 +++--- src/template.cpp | 17 -- 16 files changed, 367 insertions(+), 837 deletions(-) create mode 100755 build.ps1 delete mode 100644 main.cpp delete mode 100644 src/fetcher.cpp create mode 100644 src/problems/0001-two-sum.cpp delete mode 100644 src/problems/1-two-sum.cpp delete mode 100644 src/template.cpp diff --git a/.clang-format b/.clang-format index fc79bcc..9b3aa8b 100644 --- a/.clang-format +++ b/.clang-format @@ -1,163 +1 @@ -# public, protected, private 修饰符对齐 -# AccessModifierOffset: 2 - -# 长函数调用时,参数对齐, 括号形式 -# someLongFunction( -# argument1, argument2 -# ) -# -AlignAfterOpenBracket: BlockIndent -AlignArrayOfStructures: None - -# 连续的赋值语句对齐 -AlignConsecutiveAssignments: - Enabled: true - AcrossEmptyLines: false - AcrossComments: false - AlignCompound: true - PadOperators: true - -#AlignConsecutiveBitFields: false -AlignConsecutiveDeclarations: None -AlignConsecutiveMacros: None -AlignEscapedNewlines: Right - -# Align -# x = aaaaaaaa + -# bbbbbbbb -# -# when BreakBeforeBinaryOperators is set -# -# x = aaaaaaaa + -# bbbbbbbb -# -# AlignAfterOperator -# x = aaaaaaaa -# + bbbbbbbb -#AlignOperands: AlignAfterOperator - -AlignTrailingComments: - Kind: Always - OverEmptyLines: 2 - - # true: - # callFunction( - # a, b, c, d); - # - # false: - # callFunction(a, - # b, - # c, - # d); -AllowAllArgumentsOnNextLine: false -AllowAllConstructorInitializersOnNextLine: false -AllowAllParametersOfDeclarationOnNextLine: false -AllowShortBlocksOnASingleLine: Never -AllowShortCaseLabelsOnASingleLine: true -#AllowShortEnumsOnASingleLine: true -AllowShortFunctionsOnASingleLine: Inline -AllowShortIfStatementsOnASingleLine: Never -AllowShortLambdasOnASingleLine: Empty -AllowShortLoopsOnASingleLine: false - -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: false - -# 在template声明时,是否换行 -# template -# T foo() { -# } -# template -# T foo(int aaaaaaaaaaaaaaaaaaaaa, -# int bbbbbbbbbbbbbbbbbbbbb) { -# } -AlwaysBreakTemplateDeclarations: Yes - -BinPackArguments: false -BinPackParameters: false -#BitFieldColonSpacing: Both -BreakBeforeBraces: "Allman" - -# true: -# veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription -# ? firstValue -# : SecondValueVeryVeryVeryVeryLong; -# -# false: -# veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ? -# firstValue : -# SecondValueVeryVeryVeryVeryLong; -BreakBeforeTernaryOperators: true -BreakConstructorInitializers: BeforeComma -BreakStringLiterals: false - -ColumnLimit: 0 # 0: no limit -CompactNamespaces: false -ConstructorInitializerIndentWidth: 4 -Cpp11BracedListStyle: true - - - -FixNamespaceComments: true # 加上丢失的namespace注释 -IncludeBlocks: Preserve -#IndentCaseBlocks: false -IndentCaseLabels: true -IndentGotoLabels: false - -# #if FOO -# #if BAR -# #include -# #endif -# #endif -IndentPPDirectives: BeforeHash -IndentWidth: 4 -AccessModifierOffset: -4 -KeepEmptyLinesAtTheStartOfBlocks: false -MaxEmptyLinesToKeep: 3 -NamespaceIndentation: None - -# Left: -# int* a; -# Right: -# int *a; -# Middle: -# int * a; -PointerAlignment: Right - -# QualifierOrder - -ReferenceAlignment: Right - -# 按照列数限制, 将注释进行换行 -ReflowComments: false - -SortIncludes: CaseSensitive -SortUsingDeclarations: true - -SpaceAfterCStyleCast: false -SpaceAfterLogicalNot: false -SpaceAfterTemplateKeyword: false -SpaceBeforeAssignmentOperators: true -SpaceBeforeCpp11BracedList: false -SpaceBeforeCaseColon: false -SpaceBeforeCtorInitializerColon: false -SpaceBeforeInheritanceColon: false -SpaceBeforeParens: ControlStatements -SpaceBeforeRangeBasedForLoopColon: true -SpaceBeforeSquareBrackets: false -SpaceInEmptyBlock: false -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 4 -SpacesInAngles: Leave -SpacesInCStyleCastParentheses: false -SpacesInConditionalStatement: false -SpacesInContainerLiterals: false -SpacesInParentheses: false -SpacesInSquareBrackets: false - -# Constructor -ConstructorInitializerAllOnOneLineOrOnePerLine: true - -Standard: c++20 -TabWidth: 4 -UseTab: Never \ No newline at end of file +BasedOnStyle: LLVM diff --git a/CMakeLists.txt b/CMakeLists.txt index 574bd03..ac735d9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,14 +4,6 @@ project(leetcode-cpp) set(CMAKE_CXX_STANDARD 20) include_directories(include) -find_package(CURL REQUIRED) -find_package(nlohmann_json REQUIRED) find_package(GTest REQUIRED) add_subdirectory(src) - -add_executable(leetcode-fetcher main.cpp - src/fetcher.cpp) - -target_link_libraries(leetcode-fetcher PRIVATE CURL::libcurl) -target_link_libraries(leetcode-fetcher PRIVATE nlohmann_json::nlohmann_json) diff --git a/build.ps1 b/build.ps1 new file mode 100755 index 0000000..d2b5d04 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,89 @@ +#!pwsh + +[CmdletBinding()] +param( + [Parameter(Mandatory = $true, Position = 0)] + [string]$problemId +) + +begin +{ + $ErrorActionPreference = 'Stop' +} + +end +{ + Write-Host "Try to fetch problem $($problemId)" + + $graphQuery = @' +query questionData($titleSlug: String!) { +question(titleSlug: $titleSlug) { +content +stats +codeDefinition +sampleTestCase +metaData +} +} +'@ + $response = Invoke-RestMethod -Uri "https://leetcode.cn/api/problems/algorithms/" -Method Get + $problem = @($response.stat_status_pairs | Where-Object { $_.stat.frontend_question_id -eq $problemId }) + + if ($problem.Count -ne 1) + { + Write-Error "Failed to find target problem $($problemId)" + } + $problem = $problem[0] + + $problemNumber = "{0:D4}" -f ($problem.stat.frontend_question_id -as [int]) + $filename = "$problemNumber-$($problem.stat.question__title_slug).cpp" + + $existedFile = @(Get-ChildItem ./src/problems | Where-Object { $_.Name -eq $filename}) + + if ($existedFile.Count -gt 0) + { + Write-Error "Problem $($problem.stat.question__title_slug) has been fetched, see src/problems/$filename." + } + + $variables = @{ + titleSlug = $problem.stat.question__title_slug + } | ConvertTo-Json + + $query = @{ + operationName = "questionData" + variables = $variables + query = $graphQuery + } + + Write-Host "Try to fetch details of $($problem.stat.question__title_slug)" + $response = Invoke-RestMethod -Uri "https://leetcode.cn/graphql" -Body $query -Method Post + + $codeDefinition = @($response.data.question.codeDefinition | ConvertFrom-Json | Where-Object { $_.value -eq "cpp" }) + if ($codeDefinition.Count -ne 1) + { + Write-Error "Failed to find C++ code definition" + } + $testcaseName = "P$($problem.stat.frontend_question_id)" + + $outputCode = @" +/** +* [$($problem.stat.frontend_question_id)] $($problem.stat.question__title_slug) +*/ +#include +using namespace std; + + +// submission codes start here + +$($codeDefinition[0].defaultCode) + +// submission codes end + +TEST($testcaseName, Test1) +{ +} +"@ + + Set-Content -Path "./src/problems/$($filename)" -Value $outputCode + Write-Host "Saved as $filename." +} diff --git a/justfile b/justfile index 33ce382..9bb5e6d 100644 --- a/justfile +++ b/justfile @@ -26,6 +26,3 @@ commit: test git add -A git commit -m "$message" git push - -pull id: build - ./cmake-build-debug-clang/leetcode-fetcher {{ id }} diff --git a/main.cpp b/main.cpp deleted file mode 100644 index 14ba58a..0000000 --- a/main.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "fetcher.h" - -int main(int argc, char **argv) -{ - Fetcher fetcher; - - if (argc != 2) - { - throw std::invalid_argument("The fetcher expect the program id."); - } - - fetcher.fetchProblem(argv[1]); - - return 0; -} \ No newline at end of file diff --git a/src/fetcher.cpp b/src/fetcher.cpp deleted file mode 100644 index 53a7e55..0000000 --- a/src/fetcher.cpp +++ /dev/null @@ -1,276 +0,0 @@ -// -// Created by ricardo on 12/06/25. -// -#include -#include "fetcher.h" - -std::vector Fetcher::getProblems() const -{ - std::string body; - - curl_easy_setopt(client.get(), CURLOPT_URL, kProblemsUrl.c_str()); - curl_easy_setopt(client.get(), CURLOPT_WRITEFUNCTION, Fetcher::httpWriteCallback); - curl_easy_setopt(client.get(), CURLOPT_WRITEDATA, &body); - - const CURLcode code = curl_easy_perform(client.get()); - - if (code != CURLE_OK) - { - std::cout << "Failed to fetch problems." << std::endl; - return {}; - } - - std::vector problems; - - try - { - nlohmann::json jsonResponse = nlohmann::json::parse(body); - - for (const auto &item : jsonResponse["stat_status_pairs"]) - { - bool paidOnly = item["paid_only"]; - - const auto &stat_item = item["stat"]; - - std::string frontendQuestionId = stat_item["frontend_question_id"]; - int questionId = stat_item["question_id"]; - std::string questionTitle = stat_item["question__title"]; - std::string questionTitleSlug = stat_item["question__title_slug"]; - - problems.emplace_back(paidOnly, frontendQuestionId, questionId, questionTitle, questionTitleSlug); - } - } - catch (const nlohmann::json::parse_error &e) - { - std::cout << "JSON parse error: " << e.what() << std::endl; - std::cout << "Raw response: " << body << std::endl; - } - - return problems; -} - -std::unique_ptr Fetcher::fetchProblemContent(const LeetCodeProblem &problem) const -{ - curl_easy_setopt(client.get(), CURLOPT_URL, kGraphQlUrl.c_str()); - curl_easy_setopt(client.get(), CURLOPT_POST, 1L); - - curl_slist *headers = nullptr; - headers = curl_slist_append(headers, "Content-Type: application/json"); - - curl_easy_setopt(client.get(), CURLOPT_HTTPHEADER, headers); - - std::string requestBody = formatQueryJson(problem.questionTitleSlug).dump(); - - curl_easy_setopt(client.get(), CURLOPT_POSTFIELDS, requestBody.c_str()); - curl_easy_setopt(client.get(), CURLOPT_POSTFIELDSIZE, requestBody.size()); - - std::string responseBody; - - curl_easy_setopt(client.get(), CURLOPT_WRITEFUNCTION, Fetcher::httpWriteCallback); - curl_easy_setopt(client.get(), CURLOPT_WRITEDATA, &responseBody); - - CURLcode code = curl_easy_perform(client.get()); - - if (code != CURLE_OK) - { - throw std::runtime_error("Failed to fetch problem."); - } - - const nlohmann::json jsonResponse = nlohmann::json::parse(responseBody); - return extractContentFromJson(jsonResponse, problem); -} - -static std::string replaceString(const std::string &original, - const std::string_view old_sub, - const std::string_view new_sub) -{ - if (old_sub.empty()) - return original; // 防止空字符串导致死循环 - - std::string result; - size_t pos = 0; - size_t old_len = old_sub.size(); - size_t new_len = new_sub.size(); - - // 预计算总长度以减少内存分配 - size_t total_length = original.size(); - size_t count = 0; - size_t start = 0; - - while ((pos = original.find(old_sub, start)) != std::string::npos) - { - total_length += (new_len - old_len); // 更新总长度 - count++; - start = pos + old_len; // 下一次查找起始位置 - } - - result.reserve(total_length); // 预分配内存 - - start = 0; - while ((pos = original.find(old_sub, start)) != std::string::npos) - { - // 添加旧子串之前的部分 - result.append(original.data() + start, pos - start); - // 添加新子串 - result.append(new_sub.data(), new_sub.size()); - // 更新起始位置 - start = pos + old_len; - } - - // 添加剩余部分 - result.append(original.data() + start, original.size() - start); - - return result; -} - -std::string ProblemContent::formatTemplate(const std::string &templateContent) const -{ - const auto it = std::ranges::find_if(codeDefinitions, - [](const CodeDefinition &definition) - { - return definition.value == "cpp"; - }); - - if (it == codeDefinitions.end()) - { - throw std::runtime_error("The target problem has no C++ template."); - } - - std::string result = replaceString(templateContent, "__PROBLEM_ID__", std::to_string(questionId)); - result = replaceString(result, "__PROBLEM_TITLE__", title); - result = replaceString(result, "__PROBLEM_DEFAULT_CODE__", it->defaultCode); - std::string testCaseName = "P" + std::to_string(questionId); - result = replaceString(result, "__TEST_CASE_NAME__", testCaseName); - - return result; -} - -std::string ProblemContent::formatFilename() const -{ - std::ostringstream stream("p"); - stream << questionId; - stream << "-" << titleSlug << ".cpp"; - - return stream.str(); -} - -void Fetcher::fetchProblem(const std::string &idString) const -{ - std::vector problems = getProblems(); - - const auto it = std::ranges::find_if(problems, - [idString](const LeetCodeProblem &problem) - { - return problem.frontendQuestionId == idString; - }); - - if (it == problems.end()) - { - throw std::runtime_error("The target problem does not exist."); - } - - std::unique_ptr problemContent = fetchProblemContent(*it); - const std::string templateFile = readTemplateFile(); - std::string problemFileContent = problemContent->formatTemplate(templateFile); - std::string problemFilename = problemContent->formatFilename(); - - auto problemFile = std::ofstream("src/problems/" + problemFilename); - - if (!problemFile.is_open()) - { - throw std::runtime_error("Failed to open problem file."); - } - - problemFile << problemFileContent; - - problemFile.close(); -} - -nlohmann::json Fetcher::formatQueryJson(const std::string &title) -{ - nlohmann::json result; - - result["operationName"] = "questionData"; - result["query"] = R"(query questionData($titleSlug: String!) { - question(titleSlug: $titleSlug) { - content - stats - codeDefinition - sampleTestCase - } -})"; - - nlohmann::json variables; - variables["titleSlug"] = title; - result["variables"] = variables; - - return result; -} - -std::unique_ptr Fetcher::extractContentFromJson(const nlohmann::json &json, const LeetCodeProblem &problem) -{ - const auto questionJson = json["data"]["question"]; - std::string content = questionJson["content"]; - - std::vector codeDefinitions; - const std::string codeDefinitionString = questionJson["codeDefinition"]; - - for (nlohmann::json codeDefinitionJson = nlohmann::json::parse(codeDefinitionString); - const auto &codeDefinitionItem : codeDefinitionJson) - { - std::string value = codeDefinitionItem["value"]; - std::string text = codeDefinitionItem["text"]; - std::string defaultCode = codeDefinitionItem["defaultCode"]; - - codeDefinitions.emplace_back(value, text, defaultCode); - } - - return std::make_unique( - problem.questionTitle, - problem.questionTitleSlug, - content, - codeDefinitions, - std::stoi(problem.frontendQuestionId)); -} - -std::string Fetcher::readTemplateFile() -{ - std::ifstream file; - file.open("src/template.cpp"); - - std::stringstream buffer; - if (file.is_open()) - { - buffer << file.rdbuf(); - } - else - { - throw std::runtime_error("Failed to read template file."); - } - - file.close(); - - return buffer.str(); -} - -bool Fetcher::validateExistedProblem(const ProblemContent &problem) -{ - std::filesystem::path problemDirectory = "src/problems"; - std::string defaultFilename = problem.formatFilename(); - - if (!std::filesystem::exists(problemDirectory)) - { - throw std::runtime_error("The problem directory is not exitsed."); - } - - return std::ranges::any_of(std::filesystem::directory_iterator(problemDirectory), - [&](const std::filesystem::directory_entry &entry) - { - if (!entry.is_regular_file()) - { - return false; - } - - return entry.path().filename() == defaultFilename; - }); -} \ No newline at end of file diff --git a/src/problems/0001-two-sum.cpp b/src/problems/0001-two-sum.cpp new file mode 100644 index 0000000..03c97ba --- /dev/null +++ b/src/problems/0001-two-sum.cpp @@ -0,0 +1,34 @@ +/** + * [1] two-sum + */ +#include +#include +#include +using namespace std; + +// submission codes start here + +class Solution { +public: + vector twoSum(vector &nums, int target) { + unordered_map map; + + int index = 0; + for (const auto &i : nums) { + const auto &it = map.find(i); + if (it != map.end()) { + return {index, it->second}; + } + + map.insert({target - i, index}); + + ++index; + } + + return {}; + } +}; + +// submission codes end + +TEST(P1, Test1) {} diff --git a/src/problems/1-two-sum.cpp b/src/problems/1-two-sum.cpp deleted file mode 100644 index 7a79f00..0000000 --- a/src/problems/1-two-sum.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/** -* [1] Two Sum - */ -#include -#include -using namespace std; - - -// submission codes start here - -class Solution -{ -public: - vector twoSum(vector &nums, int target) - { - unordered_map map; - - for (int i = 0; i < nums.size(); ++i) - { - if (const auto &it = map.find(target - nums[i]); it != map.end()) - { - return {it->second, i}; - } - - map.insert({nums[i], i}); - } - - return {}; - } -}; - -// submission codes endo - -TEST(P1, Test1) -{ - Solution s; - vector nums = {2, 7, 11, 15}; - vector result = {0, 1}; - ASSERT_EQ(s.twoSum(nums, 9), result); -} \ No newline at end of file diff --git a/src/problems/1432-max-difference-you-can-get-from-changing-an-integer.cpp b/src/problems/1432-max-difference-you-can-get-from-changing-an-integer.cpp index ab2bd04..4158dfc 100644 --- a/src/problems/1432-max-difference-you-can-get-from-changing-an-integer.cpp +++ b/src/problems/1432-max-difference-you-can-get-from-changing-an-integer.cpp @@ -1,94 +1,78 @@ /** -* [1432] Max Difference You Can Get From Changing an Integer + * [1432] Max Difference You Can Get From Changing an Integer */ #include #include using namespace std; - // submission codes start here -class Solution -{ +class Solution { public: - int maxDiff(int num) - { - string numString = to_string(num); + int maxDiff(int num) { + string numString = to_string(num); - // Select the first, not 9 number. - int targetPos = 0; - while (targetPos < numString.size() - 1) - { - if (numString[targetPos] != '9') - { - break; - } + // Select the first, not 9 number. + int targetPos = 0; + while (targetPos < numString.size() - 1) { + if (numString[targetPos] != '9') { + break; + } - targetPos += 1; - } - - auto maxNumber = replaceDigit(numString, numString[targetPos], '9'); - - targetPos = 0; - char minimumChar = '1'; - // If the first number is not 1, select the first number. - // If the first number is 1, select next, not zero number. - if (numString[targetPos] == '1') - { - targetPos = 1; - minimumChar = '0'; - while (targetPos < numString.size()) - { - if (numString[targetPos] == '1') - { - // Can not replace 1 when the first number is 1. - targetPos += 1; - continue; - } - - if (numString[targetPos] != '0') - { - break; - } - - targetPos += 1; - } - } - - int minNumber = num; - if (targetPos != numString.size()) - { - minNumber = replaceDigit(numString, numString[targetPos], minimumChar); - } - - return maxNumber - minNumber; + targetPos += 1; } - static auto replaceDigit(const string &num, char source, char target) -> int - { - int result = 0; - for (const char i : num) - { - if (i == source) - { - result = result * 10 + target - '0'; - } - else - { - result = result * 10 + i - '0'; - } + auto maxNumber = replaceDigit(numString, numString[targetPos], '9'); + + targetPos = 0; + char minimumChar = '1'; + // If the first number is not 1, select the first number. + // If the first number is 1, select next, not zero number. + if (numString[targetPos] == '1') { + targetPos = 1; + minimumChar = '0'; + while (targetPos < numString.size()) { + if (numString[targetPos] == '1') { + // Can not replace 1 when the first number is 1. + targetPos += 1; + continue; } - return result; + if (numString[targetPos] != '0') { + break; + } + + targetPos += 1; + } } + + int minNumber = num; + if (targetPos != numString.size()) { + minNumber = replaceDigit(numString, numString[targetPos], minimumChar); + } + + return maxNumber - minNumber; + } + + static auto replaceDigit(const string &num, char source, char target) -> int { + int result = 0; + for (const char i : num) { + if (i == source) { + result = result * 10 + target - '0'; + } else { + result = result * 10 + i - '0'; + } + } + + return result; + } }; // submission codes end -TEST(P1432, Test1) -{ - ASSERT_EQ(888, Solution().maxDiff(555)); - ASSERT_EQ(8, Solution().maxDiff(9)); - ASSERT_EQ(888, Solution().maxDiff(111)); - ASSERT_EQ(80000, Solution().maxDiff(10000)); +TEST(P1432, Test1) { + ASSERT_EQ(888, Solution().maxDiff(555)); + ASSERT_EQ(8, Solution().maxDiff(9)); + ASSERT_EQ(888, Solution().maxDiff(111)); + ASSERT_EQ(80000, Solution().maxDiff(10000)); } \ No newline at end of file diff --git a/src/problems/2016-maximum-difference-between-increasing-elements.cpp b/src/problems/2016-maximum-difference-between-increasing-elements.cpp index bc8757a..566aca3 100644 --- a/src/problems/2016-maximum-difference-between-increasing-elements.cpp +++ b/src/problems/2016-maximum-difference-between-increasing-elements.cpp @@ -1,49 +1,43 @@ /** -* [2016] Maximum Difference Between Increasing Elements + * [2016] Maximum Difference Between Increasing Elements */ #include #include using namespace std; - // submission codes start here -class Solution -{ +class Solution { public: - int maximumDifference(vector &nums) - { - vector heap; - heap.reserve(nums.size()); + int maximumDifference(vector &nums) { + vector heap; + heap.reserve(nums.size()); - ranges::make_heap(heap, greater()); + ranges::make_heap(heap, greater()); - int result = -1; - for (int i = 1; i < nums.size(); ++i) - { - heap.push_back(nums[i - 1]); - ranges::push_heap(heap, greater()); + int result = -1; + for (int i = 1; i < nums.size(); ++i) { + heap.push_back(nums[i - 1]); + ranges::push_heap(heap, greater()); - if (heap[0] < nums[i]) - { - result = max(result, nums[i] - heap[0]); - } - } - - return result; + if (heap[0] < nums[i]) { + result = max(result, nums[i] - heap[0]); + } } + + return result; + } }; // submission codes end -TEST(P2016, Test1) -{ - vector nums1 = {7, 1, 5, 4}; - ASSERT_EQ(4, Solution().maximumDifference(nums1)); +TEST(P2016, Test1) { + vector nums1 = {7, 1, 5, 4}; + ASSERT_EQ(4, Solution().maximumDifference(nums1)); - vector nums2 = {9, 4, 3, 2}; - ASSERT_EQ(-1, Solution().maximumDifference(nums2)); + vector nums2 = {9, 4, 3, 2}; + ASSERT_EQ(-1, Solution().maximumDifference(nums2)); - vector nums3 = {1, 5, 2, 10}; - ASSERT_EQ(9, Solution().maximumDifference(nums3)); + vector nums3 = {1, 5, 2, 10}; + ASSERT_EQ(9, Solution().maximumDifference(nums3)); } \ No newline at end of file diff --git a/src/problems/2294-partition-array-such-that-maximum-difference-is-k.cpp b/src/problems/2294-partition-array-such-that-maximum-difference-is-k.cpp index e8d6bbe..ad4ddec 100644 --- a/src/problems/2294-partition-array-such-that-maximum-difference-is-k.cpp +++ b/src/problems/2294-partition-array-such-that-maximum-difference-is-k.cpp @@ -1,50 +1,42 @@ /** -* [2294] Partition Array Such That Maximum Difference Is K + * [2294] Partition Array Such That Maximum Difference Is K */ #include #include using namespace std; - // submission codes start here -class Solution -{ +class Solution { public: - int partitionArray(vector &nums, int k) - { - ranges::sort(nums); + int partitionArray(vector &nums, int k) { + ranges::sort(nums); - // At least to split into one segment. - int result = 1; - int pos = 1; - int minValue = nums[0]; + // At least to split into one segment. + int result = 1; + int pos = 1; + int minValue = nums[0]; - while (pos < nums.size()) - { - if (nums[pos] > minValue + k) - { - result += 1; - minValue = nums[pos]; - } - else - { - pos += 1; - } - } - - return result; + while (pos < nums.size()) { + if (nums[pos] > minValue + k) { + result += 1; + minValue = nums[pos]; + } else { + pos += 1; + } } + + return result; + } }; // submission codes end -TEST(P2294, Test1) -{ - vector nums1 = {3, 6, 1, 2, 5}; - ASSERT_EQ(2, Solution().partitionArray(nums1, 2)); - vector nums2 = {1, 2, 3}; - ASSERT_EQ(2, Solution().partitionArray(nums2, 1)); - vector nums3 = {2, 2, 4, 5}; - ASSERT_EQ(3, Solution().partitionArray(nums3, 0)); +TEST(P2294, Test1) { + vector nums1 = {3, 6, 1, 2, 5}; + ASSERT_EQ(2, Solution().partitionArray(nums1, 2)); + vector nums2 = {1, 2, 3}; + ASSERT_EQ(2, Solution().partitionArray(nums2, 1)); + vector nums3 = {2, 2, 4, 5}; + ASSERT_EQ(3, Solution().partitionArray(nums3, 0)); } \ No newline at end of file diff --git a/src/problems/2566-maximum-difference-by-remapping-a-digit.cpp b/src/problems/2566-maximum-difference-by-remapping-a-digit.cpp index c7a722b..306ae2e 100644 --- a/src/problems/2566-maximum-difference-by-remapping-a-digit.cpp +++ b/src/problems/2566-maximum-difference-by-remapping-a-digit.cpp @@ -1,71 +1,57 @@ /** -* [2566] Maximum Difference by Remapping a Digit + * [2566] Maximum Difference by Remapping a Digit */ #include #include using namespace std; - // submission codes start here -class Solution -{ +class Solution { public: - int minMaxDifference(int num) - { - const string numString = to_string(num); + int minMaxDifference(int num) { + const string numString = to_string(num); - // Select the first not 9 number when converting to maximum value. - int targetPos = 0; - while (targetPos < numString.size() - 1) - { - if (numString[targetPos] != '9') - { - break; - } + // Select the first not 9 number when converting to maximum value. + int targetPos = 0; + while (targetPos < numString.size() - 1) { + if (numString[targetPos] != '9') { + break; + } - targetPos += 1; - } - - int maxNum = 0; - - char targetChar = numString[targetPos]; - for (const auto c : numString) - { - if (c == targetChar) - { - maxNum = maxNum * 10 + 9; - } - else - { - maxNum = maxNum * 10 + c - '0'; - } - } - - // The minimum value is replacing the first number into zero. - - targetChar = numString[0]; - int minNum = 0; - for (const auto c : numString) - { - if (c == targetChar) - { - minNum = minNum * 10; - } - else - { - minNum = minNum * 10 + c - '0'; - } - } - - return maxNum - minNum; + targetPos += 1; } + + int maxNum = 0; + + char targetChar = numString[targetPos]; + for (const auto c : numString) { + if (c == targetChar) { + maxNum = maxNum * 10 + 9; + } else { + maxNum = maxNum * 10 + c - '0'; + } + } + + // The minimum value is replacing the first number into zero. + + targetChar = numString[0]; + int minNum = 0; + for (const auto c : numString) { + if (c == targetChar) { + minNum = minNum * 10; + } else { + minNum = minNum * 10 + c - '0'; + } + } + + return maxNum - minNum; + } }; // submission codes end -TEST(P2566, Test1) -{ - ASSERT_EQ(99009, Solution().minMaxDifference(11891)); - ASSERT_EQ(99, Solution().minMaxDifference(90)); +TEST(P2566, Test1) { + ASSERT_EQ(99009, Solution().minMaxDifference(11891)); + ASSERT_EQ(99, Solution().minMaxDifference(90)); } \ No newline at end of file diff --git a/src/problems/2616-minimize-the-maximum-difference-of-pairs.cpp b/src/problems/2616-minimize-the-maximum-difference-of-pairs.cpp index 39b34a0..2a8936a 100644 --- a/src/problems/2616-minimize-the-maximum-difference-of-pairs.cpp +++ b/src/problems/2616-minimize-the-maximum-difference-of-pairs.cpp @@ -1,60 +1,49 @@ /** -* [2616] Minimize the Maximum Difference of Pairs + * [2616] Minimize the Maximum Difference of Pairs */ #include #include using namespace std; - // submission codes start here -class Solution -{ +class Solution { public: - int minimizeMax(vector &nums, int p) - { - ranges::sort(nums); + int minimizeMax(vector &nums, int p) { + ranges::sort(nums); - auto check = [&](int value) -> bool - { - int count = 0; + auto check = [&](int value) -> bool { + int count = 0; - for (int i = 0; i < nums.size() - 1; ++i) - { - if (nums[i + 1] - nums[i] <= value) - { - count += 1; - i += 1; - } - } - - return count >= p; - }; - - int left = 0, right = nums.back() - nums[0]; - - while (left < right) - { - int middle = (left + right) >> 1; - if (check(middle)) - { - right = middle; - } - else - { - left = middle + 1; - } + for (int i = 0; i < nums.size() - 1; ++i) { + if (nums[i + 1] - nums[i] <= value) { + count += 1; + i += 1; } + } - return left; + return count >= p; + }; + + int left = 0, right = nums.back() - nums[0]; + + while (left < right) { + int middle = (left + right) >> 1; + if (check(middle)) { + right = middle; + } else { + left = middle + 1; + } } + + return left; + } }; // submission codes end. -TEST(P2616, Test1) -{ - vector nums = {10, 1, 2, 7, 1, 3}; - Solution s; - ASSERT_EQ(s.minimizeMax(nums, 2), 1); +TEST(P2616, Test1) { + vector nums = {10, 1, 2, 7, 1, 3}; + Solution s; + ASSERT_EQ(s.minimizeMax(nums, 2), 1); } \ No newline at end of file diff --git a/src/problems/2966-divide-array-into-arrays-with-max-difference.cpp b/src/problems/2966-divide-array-into-arrays-with-max-difference.cpp index aaa751f..61ec5ca 100644 --- a/src/problems/2966-divide-array-into-arrays-with-max-difference.cpp +++ b/src/problems/2966-divide-array-into-arrays-with-max-difference.cpp @@ -1,51 +1,45 @@ /** -* [2966] Divide Array Into Arrays With Max Difference + * [2966] Divide Array Into Arrays With Max Difference */ #include #include using namespace std; - // submission codes start here -class Solution -{ +class Solution { public: - vector> divideArray(vector &nums, int k) - { - ranges::sort(nums); + vector> divideArray(vector &nums, int k) { + ranges::sort(nums); - vector> result; - bool flag = true; - result.reserve(nums.size() / 3); + vector> result; + bool flag = true; + result.reserve(nums.size() / 3); - for (int i = 0; i < nums.size(); i += 3) - { - if (nums[i + 2] - nums[i + 1] > k || nums[i + 1] - nums[i] > k || nums[i + 2] - nums[i] > k) - { - flag = false; - break; - } + for (int i = 0; i < nums.size(); i += 3) { + if (nums[i + 2] - nums[i + 1] > k || nums[i + 1] - nums[i] > k || + nums[i + 2] - nums[i] > k) { + flag = false; + break; + } - vector array = {nums[i], nums[i + 1], nums[i + 2]}; - result.push_back(move(array)); - } - - if (flag) - { - return result; - } - - return {}; + vector array = {nums[i], nums[i + 1], nums[i + 2]}; + result.push_back(move(array)); } + + if (flag) { + return result; + } + + return {}; + } }; // submission codes end -TEST(P2966, Test1) -{ - vector nums = {1, 3, 4, 8, 7, 9, 3, 5, 1}; - vector> result = {{1, 1, 3}, {3, 4, 5}, {7, 8, 9}}; +TEST(P2966, Test1) { + vector nums = {1, 3, 4, 8, 7, 9, 3, 5, 1}; + vector> result = {{1, 1, 3}, {3, 4, 5}, {7, 8, 9}}; - ASSERT_EQ(result, Solution().divideArray(nums, 2)); + ASSERT_EQ(result, Solution().divideArray(nums, 2)); } \ No newline at end of file diff --git a/src/problems/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.cpp b/src/problems/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.cpp index 82d438d..883b1dc 100644 --- a/src/problems/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.cpp +++ b/src/problems/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.cpp @@ -1,80 +1,69 @@ /** -* [3405] Count the Number of Arrays with K Matching Adjacent Elements + * [3405] Count the Number of Arrays with K Matching Adjacent Elements */ #include #include using namespace std; - // submission codes start here -constexpr long long MOD = 1e9 + 7; +constexpr long long MOD = 1e9 + 7; constexpr long long UPPER_BOUND = 1e5; static long long fact[UPPER_BOUND]; static long long inverseFact[UPPER_BOUND]; -class Solution -{ - static long long quickPower(long long x, int n) - { - long long result = 1; +class Solution { + static long long quickPower(long long x, int n) { + long long result = 1; - while (n > 0) - { - if ((n & 1) == 1) - { - result = result * x % MOD; - } + while (n > 0) { + if ((n & 1) == 1) { + result = result * x % MOD; + } - x = x * x % MOD; - n >>= 1; - } - - return result; + x = x * x % MOD; + n >>= 1; } - static long long combine(int n, int m) - { - return fact[n] * inverseFact[m] % MOD * inverseFact[n - m] % MOD; + return result; + } + + static long long combine(int n, int m) { + return fact[n] * inverseFact[m] % MOD * inverseFact[n - m] % MOD; + } + + static void init() { + if (fact[0] != 0) { + return; } - static void init() - { - if (fact[0] != 0) - { - return; - } - - fact[0] = 1; - for (int i = 1; i < UPPER_BOUND; ++i) - { - fact[i] = fact[i - 1] * i % MOD; - } - - // Modular Multiplicative Inverse is calculated by the quick power. - inverseFact[UPPER_BOUND - 1] = quickPower(fact[UPPER_BOUND - 1], MOD - 2); - for (int i = UPPER_BOUND - 1; i > 0; --i) - { - inverseFact[i - 1] = inverseFact[i] * i % MOD; - } + fact[0] = 1; + for (int i = 1; i < UPPER_BOUND; ++i) { + fact[i] = fact[i - 1] * i % MOD; } + // Modular Multiplicative Inverse is calculated by the quick power. + inverseFact[UPPER_BOUND - 1] = quickPower(fact[UPPER_BOUND - 1], MOD - 2); + for (int i = UPPER_BOUND - 1; i > 0; --i) { + inverseFact[i - 1] = inverseFact[i] * i % MOD; + } + } + public: - int countGoodArrays(int n, int m, int k) - { - init(); - const long long result = combine(n - 1, k) * m % MOD * quickPower(m - 1, n - k - 1) % MOD; - return result; - } + int countGoodArrays(int n, int m, int k) { + init(); + const long long result = + combine(n - 1, k) * m % MOD * quickPower(m - 1, n - k - 1) % MOD; + return result; + } }; // submission codes end -TEST(P3405, Test1) -{ - Solution s; - ASSERT_EQ(4, s.countGoodArrays(3, 2, 1)); - ASSERT_EQ(6, s.countGoodArrays(4, 2, 2)); - ASSERT_EQ(2, s.countGoodArrays(5, 2, 0)); +TEST(P3405, Test1) { + Solution s; + ASSERT_EQ(4, s.countGoodArrays(3, 2, 1)); + ASSERT_EQ(6, s.countGoodArrays(4, 2, 2)); + ASSERT_EQ(2, s.countGoodArrays(5, 2, 0)); } \ No newline at end of file diff --git a/src/template.cpp b/src/template.cpp deleted file mode 100644 index 6883b56..0000000 --- a/src/template.cpp +++ /dev/null @@ -1,17 +0,0 @@ -/** -* [__PROBLEM_ID__] __PROBLEM_TITLE__ - */ -#include -#include -using namespace std; - - -// submission codes start here - -__PROBLEM_DEFAULT_CODE__ - -// submission codes end - -TEST(__TEST_CASE_NAME__, Test1) -{ -} \ No newline at end of file