diff --git a/.gitattributes b/.gitattributes index 494bd80a..607cda74 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,4 @@ ### - # @Github: https://github.com/Certseeds/CS203_DSAA_template # @Author: nanoseeds # @Date: 2020-07-15 23:48:29 # @LastEditors: nanoseeds diff --git a/.github/workflows/daily.yml b/.github/workflows/daily.yml deleted file mode 100644 index d882cd0c..00000000 --- a/.github/workflows/daily.yml +++ /dev/null @@ -1,93 +0,0 @@ -name: daily build - -# Controls when the action will run. Triggers the workflow on push or pull request -# events but only for the master branch -on: - schedule: - - cron: '0 15 * * *' - -# A workflow run is made up of one or more jobs that can run sequentially or in parallel -jobs: - test: - name: daily build - # The type of runner that the job will run on - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ ubuntu-20.04, ubuntu-22.04 ] - env: - CC: gcc-10 - CXX: g++-10 - # Steps represent a sequence of tasks that will be executed as part of the job - steps: - - # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - - name: checkout code - uses: actions/checkout@v3 - with: - ref: dev - - uses: actions/cache@v3 - env: - cache-name: cache-cmake-files - with: - path: | - ~/.ccache - ~/.cache - key: ${{ matrix.os }}-cmake-build-${{ hashFiles('CMakeLists.txt', '**/CMakeLists.txt', '**/*.cmake') }} - restore-keys: | - ${{ matrix.os }}-cmake-build - ${{ matrix.os }} - - # ensure the path and files of project - - name: ensure the path and files of project - run: sudo apt-get install tree; tree - - - name: Install ccache, check gcc version - run: | - sudo add-apt-repository ppa:ubuntu-toolchain-r/test - sudo apt-get update && sudo apt-get install -y ccache - gcc --version - g++ --version - - - name: prepare libopencv - run: | - sudo apt-get update && sudo apt-get install libopencv-dev - - - name: Use cmake - run: cmake --version - - - name: cmake prepare for compile - run: cmake -S . -B ./CMAKE_DEBUG_PATH -DCMAKE_BUILD_TYPE=DEBUG - - - name: cmake compile lab_00 - working-directory: ./CMAKE_DEBUG_PATH/lab_00 - run: cmake --build . --config DEBUG --parallel - - - name: cmake compile algorithm/2021F - working-directory: ./CMAKE_DEBUG_PATH/algorithm/2021F - run: cmake --build . --config DEBUG --parallel - - - name: cmake compile algorithm/matrix - working-directory: ./CMAKE_DEBUG_PATH/algorithm/matrix - run: cmake --build . --config DEBUG --parallel - - - name: cmake compile algorithm - working-directory: ./CMAKE_DEBUG_PATH/algorithm/ - run: cmake --build . - - - name: cmake compile basic - working-directory: ./CMAKE_DEBUG_PATH/basic - run: cmake --build . --config DEBUG --parallel - - - name: cmake compile - working-directory: ./CMAKE_DEBUG_PATH - run: cmake --build . --config DEBUG --parallel - - - name: cmake test - working-directory: ./CMAKE_DEBUG_PATH - run: ctest --parallel $(nproc) - - - name: cache configs output - run: | - ccache -p - ccache -s diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 62a7bee7..50639f00 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -15,17 +15,17 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ ubuntu-20.04, ubuntu-22.04 ] + os: [ ubuntu-24.04 ] env: - CC: gcc-10 - CXX: g++-10 + CC: gcc-13 + CXX: g++-13 # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - name: checkout code - uses: actions/checkout@v3 - - uses: actions/cache@v3 + uses: actions/checkout@v5 + - uses: actions/cache@v4 env: cache-name: cache-cmake-files with: @@ -105,14 +105,14 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ ubuntu-20.04, ubuntu-22.04 ] + os: [ ubuntu-24.04 ] # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - name: checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v5 # ensure the path and files of project - name: ensure the path and files of project diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 04faf262..252a339c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,16 +16,16 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ ubuntu-20.04, ubuntu-22.04 ] + os: [ ubuntu-24.04 ] env: - CC: gcc-10 - CXX: g++-10 + CC: gcc-13 + CXX: g++-13 # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - name: checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v5 - name: hardwares - cpu run: nproc; cat /proc/cpuinfo @@ -78,16 +78,19 @@ jobs: # This workflow contains a single job called "build" build: name: publish release - if: github.repository == 'Certseeds/CS203_DSAA_template' + env: + CC: gcc-13 + CXX: g++-13 + if: github.repository == 'Certseeds/algorithm-template' needs: test # The type of runner that the job will run on - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - name: checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v5 - name: Branch name id: branch_name @@ -128,11 +131,11 @@ jobs: - name: zip the packet working-directory: ./../ run: | - zip -r script_no_need.zip ./CS203_DSAA_template -x "*/.git/*" + zip -r script_no_need.zip ./algorithm-template -x "*/.git/*" tree - name: release - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 if: startsWith(github.ref, 'refs/tags/') with: files: ./../script_no_need.zip @@ -144,18 +147,19 @@ jobs: release-branch: name: publish release-branch - if: github.repository == 'Certseeds/CS203_DSAA_template' + env: + CC: gcc-13 + CXX: g++-13 + if: github.repository == 'Certseeds/algorithm-template' needs: [ test, build ] # The type of runner that the job will run on - runs-on: ubuntu-22.04 - env: - GCC_V: 11 + runs-on: ubuntu-24.04 # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - name: checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v5 - name: Branch name id: branch_name diff --git a/.github/workflows/rust_build.yml b/.github/workflows/rust_build.yml index f631d0a9..a7646ed4 100644 --- a/.github/workflows/rust_build.yml +++ b/.github/workflows/rust_build.yml @@ -9,7 +9,7 @@ name: Rust Build and Test # Controls when the action will run. Triggers the workflow on push or pull request # events but only for the master branch on: - [ push,pull_request ] + workflow_dispatch: # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: @@ -20,16 +20,16 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ windows-latest,ubuntu-20.04, ubuntu-22.04 ] + os: [ windows-latest,ubuntu-24.04 ] # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - name: checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v5 - name: Cache Packages - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ~/.cargo key: ${{ matrix.os }}-rust-toolchain-${{ hashFiles('**/*.toml') }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c83d2082..626889cb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,7 +9,7 @@ jobs: test: name: test dev # The type of runner that the job will run on - runs-on: ubuntu-22.04 + runs-on: ubuntu-latest # Steps represent a sequence of tasks that will be executed as part of the job steps: diff --git a/.gitignore b/.gitignore index 699db3ff..56170a86 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ ### -## @Github: https://github.com/Certseeds/CS203_DSAA_template ## @Author: nanoseeds ## @Date: 2020-07-15 23:48:29 ## @LastEditors: nanoseeds @@ -316,8 +315,6 @@ build/ # idea .idea/* -!.idea/codeStyles -!.idea/fileTemplates # File-based project format *.iws @@ -340,3 +337,7 @@ fabric.properties *.o *.so *.exe + +## + +*.old diff --git a/.idea/.gitattributes b/.idea/.gitattributes deleted file mode 100644 index 36fe3a53..00000000 --- a/.idea/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -* linguist-vendored \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 0f7f53c6..00000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -!* -CS203_DSAA_template.iml -deployment.xml -misc.xml -modules.xml -vcs.xml -workspace.xml -file.template.settings.xml -.name -other.xml -sshConfigs.xml \ No newline at end of file diff --git a/.idea/codeStyles/.gitignore b/.idea/codeStyles/.gitignore deleted file mode 100644 index 68302260..00000000 --- a/.idea/codeStyles/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -* -!.gitignore -!codeStyleConfig.xml -!Project.xml \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml deleted file mode 100644 index 3456a0b1..00000000 --- a/.idea/codeStyles/Project.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml deleted file mode 100644 index 79ee123c..00000000 --- a/.idea/codeStyles/codeStyleConfig.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml deleted file mode 100644 index c2bae49d..00000000 --- a/.idea/encodings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/fileTemplates/includes/.gitignore b/.idea/fileTemplates/includes/.gitignore deleted file mode 100644 index bbbdc748..00000000 --- a/.idea/fileTemplates/includes/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -* -!.gitignore -!FILE_HEAD_CPP.h -!FILE_HEAD_PY.py -!LICENSE_AGPL_CPP.h -!LICENSE_AGPL_PY.py diff --git a/.idea/fileTemplates/includes/FILE_HEAD_CPP.h b/.idea/fileTemplates/includes/FILE_HEAD_CPP.h deleted file mode 100644 index 34238ddf..00000000 --- a/.idea/fileTemplates/includes/FILE_HEAD_CPP.h +++ /dev/null @@ -1,8 +0,0 @@ -#set( ${GITHUB_USER} = "Certseeds") -/** - * @Github: https://github.com/${GITHUB_USER}/${PROJECT_NAME} - * @Author: ${USER} - * @Date: ${YEAR}-${MONTH}-${DAY} ${HOUR}:${MINUTE}:${SECOND} - * @LastEditors: ${USER} - * SPDX-License-Identifier: AGPL-3.0-or-later - */ diff --git a/.idea/fileTemplates/includes/FILE_HEAD_PY.py b/.idea/fileTemplates/includes/FILE_HEAD_PY.py deleted file mode 100644 index 80cdfc13..00000000 --- a/.idea/fileTemplates/includes/FILE_HEAD_PY.py +++ /dev/null @@ -1,10 +0,0 @@ -#set( ${GITHUB_USER} = "Certseeds") -#!/usr/bin/env python3 -# coding=utf-8 -""" -@Github: https://github.com/${GITHUB_USER}/${PROJECT_NAME} -@Author: ${USER} -@Date: ${YEAR}-${MONTH}-${DAY} ${HOUR}:${MINUTE}:${SECOND} -@LastEditors: ${USER} -@SPDX-License-Identifier: AGPL-3.0-or-later -""" diff --git a/.idea/fileTemplates/includes/LICENSE_AGPL_CPP.h b/.idea/fileTemplates/includes/LICENSE_AGPL_CPP.h deleted file mode 100644 index 99856ab6..00000000 --- a/.idea/fileTemplates/includes/LICENSE_AGPL_CPP.h +++ /dev/null @@ -1,7 +0,0 @@ -/* -SPDX-License-Identifier: AGPL-3.0-or-later - -${PROJECT_NAME} - -Copyright (C) 2020-${YEAR} ${USER} -*/ diff --git a/.idea/fileTemplates/includes/LICENSE_AGPL_PY.py b/.idea/fileTemplates/includes/LICENSE_AGPL_PY.py deleted file mode 100644 index 50eeb87a..00000000 --- a/.idea/fileTemplates/includes/LICENSE_AGPL_PY.py +++ /dev/null @@ -1,8 +0,0 @@ -""" -SPDX-License-Identifier: AGPL-3.0-or-later - -${PROJECT_NAME} - -Copyright (c) 2020-${YEAR} ${USER} - -""" diff --git a/.idea/fileTemplates/internal/.gitignore b/.idea/fileTemplates/internal/.gitignore deleted file mode 100644 index 65ef282f..00000000 --- a/.idea/fileTemplates/internal/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -* -!.gitignore -!C++ Class.cc -!C++ Class Header.h -!C Header File.h -!C Source File.c -!Python Script.py -!Python Unit Test.py \ No newline at end of file diff --git a/.idea/fileTemplates/internal/C Header File.h b/.idea/fileTemplates/internal/C Header File.h deleted file mode 100644 index 8b63689e..00000000 --- a/.idea/fileTemplates/internal/C Header File.h +++ /dev/null @@ -1,7 +0,0 @@ -#set( $GITHUB_USER = "Certseeds" ) -#parse("FILE_HEAD_CPP.h") -#parse("LICENSE_AGPL_CPP.h") -#[[#ifndef]]# ${INCLUDE_GUARD} -#[[#define]]# ${INCLUDE_GUARD} - -#[[#endif]]# //${INCLUDE_GUARD} diff --git a/.idea/fileTemplates/internal/C Source File.c b/.idea/fileTemplates/internal/C Source File.c deleted file mode 100644 index 48a2f074..00000000 --- a/.idea/fileTemplates/internal/C Source File.c +++ /dev/null @@ -1,6 +0,0 @@ -#set( $GITHUB_USER = "Certseeds" ) -#parse("FILE_HEAD_CPP.h") -#parse("LICENSE_AGPL_CPP.h") -#if (${HEADER_FILENAME}) -#[[#include]]# "${HEADER_FILENAME}" -#end diff --git a/.idea/fileTemplates/internal/C++ Class Header.h b/.idea/fileTemplates/internal/C++ Class Header.h deleted file mode 100644 index 7e2ed460..00000000 --- a/.idea/fileTemplates/internal/C++ Class Header.h +++ /dev/null @@ -1,15 +0,0 @@ -#set( $GITHUB_USER = "Certseeds" ) -#parse("FILE_HEAD_CPP.h") -#parse("LICENSE_AGPL_CPP.h") -#[[#ifndef]]# ${INCLUDE_GUARD} -#[[#define]]# ${INCLUDE_GUARD} - -${NAMESPACES_OPEN} - -class ${NAME} { - -}; - -${NAMESPACES_CLOSE} - -#[[#endif]]# //${INCLUDE_GUARD} diff --git a/.idea/fileTemplates/internal/C++ Class.cc b/.idea/fileTemplates/internal/C++ Class.cc deleted file mode 100644 index 619f6ed7..00000000 --- a/.idea/fileTemplates/internal/C++ Class.cc +++ /dev/null @@ -1,4 +0,0 @@ -#set( $GITHUB_USER = "Certseeds" ) -#parse("FILE_HEAD_CPP.h") -#parse("LICENSE_AGPL_CPP.h") -#[[#include]]# "${HEADER_FILENAME}" diff --git a/.idea/fileTemplates/internal/Python Script.py b/.idea/fileTemplates/internal/Python Script.py deleted file mode 100644 index 451a58ed..00000000 --- a/.idea/fileTemplates/internal/Python Script.py +++ /dev/null @@ -1,2 +0,0 @@ -#parse("FILE_HEAD_PY.py") -#parse("LICENSE_AGPL_PY.py") diff --git a/.idea/fileTemplates/internal/Python Unit Test.py b/.idea/fileTemplates/internal/Python Unit Test.py deleted file mode 100644 index 517619b9..00000000 --- a/.idea/fileTemplates/internal/Python Unit Test.py +++ /dev/null @@ -1,10 +0,0 @@ -#parse("FILE_HEAD_PY.py") -#parse("LICENSE_AGPL_PY.py") -import unittest - -class MyTestCase(unittest.TestCase): - def test_something(self): - self.assertEqual(True, False) - -if __name__ == '__main__': - unittest.main() diff --git a/.idea/fileTemplates/j2ee/.gitignore b/.idea/fileTemplates/j2ee/.gitignore deleted file mode 100644 index 46f86df4..00000000 --- a/.idea/fileTemplates/j2ee/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -* -!.gitignore -!cpp.*.CMakeLists.txt diff --git a/.idea/fileTemplates/j2ee/cpp.executable.CMakeLists.txt b/.idea/fileTemplates/j2ee/cpp.executable.CMakeLists.txt deleted file mode 100644 index f79bb90a..00000000 --- a/.idea/fileTemplates/j2ee/cpp.executable.CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -cmake_minimum_required(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}) -project (${PROJECT_NAME} CXX) - -set(CMAKE_CXX_STANDARD ${CMAKE_LANGUAGE_VERSION}) - -add_executable(${PROJECT_NAME} ${CMAKE_DEFAULT_PROJECT_FILE}) diff --git a/.idea/fileTemplates/j2ee/cpp.library.CMakeLists.txt b/.idea/fileTemplates/j2ee/cpp.library.CMakeLists.txt deleted file mode 100644 index d244fe02..00000000 --- a/.idea/fileTemplates/j2ee/cpp.library.CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -cmake_minimum_required(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}) -project (${PROJECT_NAME} CXX) - -set(CMAKE_CXX_STANDARD ${CMAKE_LANGUAGE_VERSION}) - -add_library(${PROJECT_NAME} ${CMAKE_LIBRARY_TYPE} ${CMAKE_DEFAULT_PROJECT_FILE}) diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml deleted file mode 100644 index 4ccab0a6..00000000 --- a/.idea/inspectionProfiles/Project_Default.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 5d41a2a7..14556e8e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,12 +1,12 @@ cmake_minimum_required(VERSION 3.16.6) set(PROJECT_VERSION_MAJOR 0) -set(PROJECT_VERSION_MINOR 11) -set(PROJECT_VERSION_PATCH 1) # delete endsWith strs when master merge dev +set(PROJECT_VERSION_MINOR 12) +set(PROJECT_VERSION_PATCH 0) # delete endsWith strs when master merge dev -project(CS203_DSAA_template +project(algorithm_template DESCRIPTION "Template for Algorithm Based on C++11 and Modern CMake" - HOMEPAGE_URL "https://github.com/Certseeds/CS203_DSAA_template" + HOMEPAGE_URL "https://github.com/Certseeds/algorithm-template" LANGUAGES CXX) set(CMAKE_CXX_STANDARD 11) diff --git a/README.md b/README.md index 02eeeedf..3358d648 100644 --- a/README.md +++ b/README.md @@ -17,16 +17,16 @@

An awesome Algorithm Template for IO-Driven Single-File Problem(like Online-Judge Problem) !
- 分布式1 去中心化2 的IO驱动型单文件问题4解题模板 + 分布式1 去中心化2 的IO驱动型单文件问题4解题模板
- Explore the docs » + Explore the docs »

- View Demo + View Demo · - Report Bug + Report Bug · - Request Feature + Request Feature

@@ -57,11 +57,11 @@ ## About The Project -OJ系统存在着一些特殊要求-因此考虑到下面的因素,设计了一套代码模板,以适应OJ系统的独特环境. +OJ系统存在着一些特殊要求-因此考虑到下面的因素, 设计了一套代码模板, 以适应OJ系统的独特环境. -+ 上交题目无需修改类名,方法名等等内容,只需复制粘贴. -+ 支持为每个问题撰写测试用例,并支持用户之间方便的交换测试用例 -+ 只依赖于Unix-Like系统,支持C++17的编译器与仓库本身,没有依赖包 ++ 上交题目无需修改类名, 方法名等等内容, 只需复制粘贴. ++ 支持为每个问题撰写测试用例, 并支持用户之间方便的交换测试用例 ++ 只依赖于Unix-Like系统, 支持C++17的编译器与仓库本身, 没有依赖包 + 易于拓展, 提供基本算法接口与实现 ### Built With @@ -72,13 +72,13 @@ OJ系统存在着一些特殊要求-因此考虑到下面的因素,设计了一 ## Getting Started -1. 下载Release中的[压缩包][download_zip]或者[另一个压缩包][download_zip_refs],之后解压使用(简易) -2. 使用绿色按钮[Use This Template][Use_This_Template],生成仓库,clone下来使用(推荐) -3. fork repo, clone下来使用(不推荐,fork的仓库只有合入主仓库才被github计入提交图) +1. 下载Release中的[压缩包][download_zip]或者[另一个压缩包][download_zip_refs], 之后解压使用(简易) +2. 使用绿色按钮[Use This Template][Use_This_Template], 生成仓库, clone下来使用(推荐) +3. fork repo, clone下来使用(不推荐, fork的仓库只有合入主仓库才被github计入提交图) -[download_zip]: https://github.com/Certseeds/CS203_DSAA_template/releases/latest/download/script_no_need.zip -[download_zip_refs]: https://github.com/Certseeds/CS203_DSAA_template/archive/refs/heads/release.zip -[Use_This_Template]: https://github.com/Certseeds/CS203_DSAA_template/generate +[download_zip]: https://github.com/Certseeds/algorithm-template/releases/latest/download/script_no_need.zip +[download_zip_refs]: https://github.com/Certseeds/algorithm-template/archive/refs/heads/release.zip +[Use_This_Template]: https://github.com/Certseeds/algorithm-template/generate ### Prerequisites @@ -86,7 +86,7 @@ This is an example of how to list things you need to use the software and how to #### Windows -1. WSL(推荐ubuntu 22.04 | 20.04), `sudo apt install build-essential ccache` +1. WSL(推荐ubuntu 24.04), `sudo apt install build-essential ccache` + 命令行检测gcc版本 @@ -103,38 +103,35 @@ ccache --version + generate -点击绿色按钮[Use This Template][Use_This_Template],生成仓库 +点击绿色按钮[Use This Template][Use_This_Template], 生成仓库 + clone生成的自己的仓库到本地 ``` bash # 在use this template之后 -git clone https://github.com/${YOUE_GITHUB_USER_NAME}/CS203_DSAA_template.git +git clone https://github.com/${YOUE_GITHUB_USER_NAME}/algorithm-template.git ``` + 使用CLion打开仓库 + 可选项: - + 将脚本创建的版权声明中的所有者替换成自己: - 1. `./.idea`中的`#set( ${GITHUB_USER} = "Certseeds")` -> `#set( ${GITHUB_USER} = "YOUR_GITHUB_NAME")` - 2. `./script/file_template.py` 里面的 `Certseeds` to `YOUR_GITHUB_NAME`,`nanoseeds` to `YOUR_USER_NAME`, + 使用脚本产生自定义的文件(适合source.zip或者有bonuslab): - 使用命令行,进入`./script`下,编辑`file_template`的`labs` & `problem_orders`, - `python3 ./file_template.py`,出现`produce files finish`提示,即为创建成功. + 使用命令行, 进入`./script`下, 编辑`file_template`的`labs` & `problem_orders`, + `python3 ./file_template.py`, 出现`produce files finish`提示, 即为创建成功.

(back to top)

## Usage: 执行代码和测试 -使用clion打开文件夹,配置好C++环境的基础上,会自动识别`CmakeList.txt`. +使用clion打开文件夹, 配置好C++环境的基础上, 会自动识别`CmakeList.txt`. -产生`CS203_lab${order}_${ques_Order}`,`CS203_lab${order}_${ques_Order}_test` 形式的复数个可以运行的可选项. +产生`CS203_lab${order}_${ques_Order}`, `CS203_lab${order}_${ques_Order}_test` 形式的复数个可以运行的可选项. -`lab${order}_${ques_Order}`为对应题号,比如`lab07_01`对应lab_07的C1题. +`lab${order}_${ques_Order}`为对应题号, 比如`lab07_01`对应lab_07的C1题. -+ `CS203_lab07_01`将调用`lab_07\lab_07_C1\lab07_C1.cpp`,为将要提交的源文件. -+ `CS203_lab07_01_test`将调用`lab_07\lab_07_C1\lab07_C1_test.cpp`,对其进行测试. -+ `lab_*\lab_*_*\lab_*_*_test.cpp`目的为方便测试,同时便于分享测试用例. ++ `CS203_lab07_01`将调用`lab_07\lab_07_C1\lab07_C1.cpp`, 为将要提交的源文件. ++ `CS203_lab07_01_test`将调用`lab_07\lab_07_C1\lab07_C1_test.cpp`, 对其进行测试. ++ `lab_*\lab_*_*\lab_*_*_test.cpp`目的为方便测试, 同时便于分享测试用例.

(back to top)

@@ -142,45 +139,45 @@ git clone https://github.com/${YOUE_GITHUB_USER_NAME}/CS203_DSAA_template.git ### 为什么要将 `读取` `数据处理` `输出` 分开? -1. 便于理清思路,读完题目之后,不管别的,先把数据读入,输出的函数写好,方便后续写作. +1. 便于理清思路, 读完题目之后, 不管别的, 先把数据读入, 输出的函数写好, 方便后续写作. 2. 交流代码逻辑的时候不会受到无关逻辑的影响 -3. 可以互相分享少量代码而不触及核心逻辑,方便协作. +3. 可以互相分享少量代码而不触及核心逻辑, 方便协作. 4. 便于使用测试. -### 基本测试用例展示 A+B: lab_00_A ,测试样例 +### 基本测试用例展示 A+B: lab_00_A , 测试样例 -+ 这个问题较为简单,见[A+B](./lab_00/lab_00_A/lab_00_A.cpp).解决起来不复杂. -+ 虽然可以手工一个一个输入,然后观察输出. 但是如果我们希望严谨的测试,要100组测试数据,难道每次出新版本都要手动输入100次吗? ++ 这个问题较为简单, 见[A+B](./lab_00/lab_00_A/lab_00_A.cpp).解决起来不复杂. ++ 虽然可以手工一个一个输入, 然后观察输出. 但是如果我们希望严谨的测试, 要100组测试数据, 难道每次出新版本都要手动输入100次吗? -显然,有更好的解决方式:使用测试框架. +显然, 有更好的解决方式:使用测试框架. -+ 在本repo,使用`Catch2`测试框架. - + 比如,我们有四组数据,第一组,第二组测试边界值,第三组使用随机数测试对偶性与正确性,第四组测试几个手动的随机值. ++ 在本repo, 使用`Catch2`测试框架. + + 比如, 我们有四组数据, 第一组, 第二组测试边界值, 第三组使用随机数测试对偶性与正确性, 第四组测试几个手动的随机值. + 参见[test_for_lab00_A](./lab_00/lab_00_A/lab_00_A_test.cpp). -+ 这样一来,我们只需要每次修改完主文件之后,run `CS203_DSAA_template_test`, 对其进行调用,就能验证其在所有的测试用例上的正确性. ++ 这样一来, 我们只需要每次修改完主文件之后, run `algorithm-template_test`, 对其进行调用, 就能验证其在所有的测试用例上的正确性. ### 多个输出值的检查:`Catch::Matchers` -上面的例子里,输出值只是一个值,所以手动检查的难度不大,但是如果目标输出是一个数组,那么手动检查的难度就非常大了. +上面的例子里, 输出值只是一个值, 所以手动检查的难度不大, 但是如果目标输出是一个数组, 那么手动检查的难度就非常大了. -举例:[Crzay Plan](https://acm.sustech.edu.cn/onlinejudge/problem.php?id=1250),输入可能有1.1*10^6个. +举例:[Crzay Plan](https://acm.sustech.edu.cn/onlinejudge/problem.php?id=1250), 输入可能有1.1*10^6个. -这种情况下对这么多值进行直接的观察就很难,所以我们预先将期望的值直接写在测试文件里,用Catch2内置的Matcher比较(见[test_for_lab00_B](./lab_00/lab_00_B/lab_00_B_test.cpp)的`CHECK_THAT()`部分.) +这种情况下对这么多值进行直接的观察就很难, 所以我们预先将期望的值直接写在测试文件里, 用Catch2内置的Matcher比较(见[test_for_lab00_B](./lab_00/lab_00_B/lab_00_B_test.cpp)的`CHECK_THAT()`部分.) -PS: 当然,这种情况也只适用于规模比较小的情况,规模再大的话,直接由人手动写在测试文件里也太占空间了. +PS: 当然, 这种情况也只适用于规模比较小的情况, 规模再大的话, 直接由人手动写在测试文件里也太占空间了. ### 输入输出重定向-Stage 1: 从文件中读取输入 -常见于tree,graph类的问题,debug需要的数据集都比较大,不方便直接写在代码中. +常见于tree, graph类的问题, debug需要的数据集都比较大, 不方便直接写在代码中. -比如[判断二分图](./lab_00/lab_00_C/lab_00_C.cpp),一张图可以有几十上百个node,写在内部占用空间太大. +比如[判断二分图](./lab_00/lab_00_C/lab_00_C.cpp), 一张图可以有几十上百个node, 写在内部占用空间太大. -而在这里,使用`CS203_redirect`对象,便可以省去手动输入的方式. +而在这里, 使用`CS203_redirect`对象, 便可以省去手动输入的方式. ``` cpp TEST_CASE("test case 1", "[test 00 C]") { const CS203_redirect cr{"01.data.in", ""}; - // 重定向开始,开始run + // 重定向开始, 开始run // or CS203_redirect cr{"01.data.in"}; const auto output_data = isBipartite(read()); // 重定向结束 @@ -188,23 +185,23 @@ TEST_CASE("test case 1", "[test 00 C]") { } ``` -只需要准备好输入的数据与结果,就可以从文件中读取,执行后判断结果是否符合预期. +只需要准备好输入的数据与结果, 就可以从文件中读取, 执行后判断结果是否符合预期. -+ test case 1-5为最简单的逐个判断,最简单,代码量最大. -+ test case loop 则优化了一些,但是还是比较麻烦,for循环还需要了解测试样例的个数. -+ test case with tuple 则最优雅,修改起来的难度最小. -+ test case with sequence 比tuple更优雅,输入,输出全为自动产生. ++ test case 1-5为最简单的逐个判断, 最简单, 代码量最大. ++ test case loop 则优化了一些, 但是还是比较麻烦, for循环还需要了解测试样例的个数. ++ test case with tuple 则最优雅, 修改起来的难度最小. ++ test case with sequence 比tuple更优雅, 输入, 输出全为自动产生. -PS: 此处注意,引用文件的相对路径,不是直接的`test/lab_00/lab_00_C/resource/01.data.in`, +PS: 此处注意, 引用文件的相对路径, 不是直接的`test/lab_00/lab_00_C/resource/01.data.in`, 而是编译出的文件相对于测试数据的相对路径. -在样例中,编译出的文件在`CS203_DSAA_template/cmake-build-debug`下,所以需要加`./../` +在样例中, 编译出的文件在`algorithm-template/cmake-build-debug`下, 所以需要加`./../` -### 输入输出重定向-Stage 2: 从文件中读取输入,将输出定向到文件中 +### 输入输出重定向-Stage 2: 从文件中读取输入, 将输出定向到文件中 -+ 一般来说,题目的输出不会太复杂,但是反例也不是没有.:比如专门考输出的[立体图](./lab_00/lab_00_D/lab_00_D.cpp) -+ 这种情况下,使用c++的重定向输出就可以较为方便的对输入进行处理,同时保存输出方便调试. ++ 一般来说, 题目的输出不会太复杂, 但是反例也不是没有.:比如专门考输出的[立体图](./lab_00/lab_00_D/lab_00_D.cpp) ++ 这种情况下, 使用c++的重定向输出就可以较为方便的对输入进行处理, 同时保存输出方便调试. ``` cpp TEST_CASE("test case 2", "[test 00 D]") { @@ -218,9 +215,9 @@ PS: 此处注意,引用文件的相对路径,不是直接的`test/lab_00/lab_00_ } ``` -这样就将标准输出重定向到了01.test.out中,并与01.data.out比对. +这样就将标准输出重定向到了01.test.out中, 并与01.data.out比对. -PS: 至于比较文件之间的差异,可以使用内置的`compareFiles(string path1,string path2)`函数进行比较. +PS: 至于比较文件之间的差异, 可以使用内置的`compareFiles(string path1, string path2)`函数进行比较. 参考[文本比对_test_case_2](./lab_00/lab_00_D/lab_00_D_test.cpp) @@ -233,29 +230,29 @@ PS: 至于比较文件之间的差异,可以使用内置的`compareFiles(string [dalao1](https://acm.sustech.edu.cn/onlinejudge/status.php?user_id=11710724&jresult=4) [dalao2](https://acm.sustech.edu.cn/onlinejudge/status.php?user_id=11612908&jresult=4) [dalao3](https://acm.sustech.edu.cn/onlinejudge/status.php?user_id=11712510&jresult=4) -等等dalao的解题页面看看,会发现在排行榜榜首的人,绝大多数题目使用的都是C++. +等等dalao的解题页面看看, 会发现在排行榜榜首的人, 绝大多数题目使用的都是C++. 2. 速度. -+ oj内一般java的最大运行时间都会是c++的2倍,显然是暗示速度之间的差别. -+ 其次,C++可以通过一些魔法操作,比如下文的优化等操作再获取一些时间上的优势. ++ oj内一般java的最大运行时间都会是c++的2倍, 显然是暗示速度之间的差别. ++ 其次, C++可以通过一些魔法操作, 比如下文的优化等操作再获取一些时间上的优势. 3. 对数据结构的友好性 -DSAA既然内含Data structure,就势必涉及到类似Node,Tree,Graph等等数据结构,这类数据结构使用C++写,比较方便理解. +DSAA既然内含Data structure, 就势必涉及到类似Node, Tree, Graph等等数据结构, 这类数据结构使用C++写, 比较方便理解. 4. 对算法友好的性能: -之前写树和图相关的题目时,最头疼的就是Java的爆栈,有一段时间只要用递归就爆栈,相同算法修改为C++之后问题就消失了. +之前写树和图相关的题目时, 最头疼的就是Java的爆栈, 有一段时间只要用递归就爆栈, 相同算法修改为C++之后问题就消失了. 5. 相关资源的丰富程度 -不管怎么说,c++是dalao的选择,所以在网络上搜索题目,得到的大多数答案都是C/C++,java的数量很少. +不管怎么说, c++是dalao的选择, 所以在网络上搜索题目, 得到的大多数答案都是C/C++, java的数量很少. ### 如何手动开优化 1. 将[magic_optimize](./include/magic_macro/magic_macro.hpp)内的内容粘贴到代码最上方. -2. 关闭同步, +2. 关闭同步, ``` cpp static const auto faster_streams = [] { @@ -266,14 +263,14 @@ static const auto faster_streams = [] { std::ostream::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); - // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. + // 关闭c++风格输入输出 , 与C风格输入输出的同步, 提高性能. return 0; }(); ``` -已放置在源文件最下方,注意**不要混用**C风格输入输出(`scanf`,`printf`)与c++风格输入输出(`cin`,`cout`) +已放置在源文件最下方, 注意**不要混用**C风格输入输出(`scanf`, `printf`)与c++风格输入输出(`cin`, `cout`) -通常情况下,可以将运行时间缩短到1/2甚至更少. +通常情况下, 可以将运行时间缩短到1/2甚至更少. ### Why choose Catch? @@ -285,7 +282,7 @@ static const auto faster_streams = [] { | 是否需要提前在系统内安装 | X | √ | √ | √ | √(and visual studio make it) | | 语法 | 简单 | 简单 | 复杂 | 简单 | Unknown | -先筛选跨平台,去掉了Microsoft,再筛选不需要安装,只剩Catch2, 结束. +先筛选跨平台, 去掉了Microsoft, 再筛选不需要安装, 只剩Catch2, 结束. ## Roadmap @@ -308,7 +305,7 @@ static const auto faster_streams = [] { + [x] CD: Tag触发的自动Release + [x] leetcode题目 + [x] ~~预编译头文件~~ccache加速编译 -+ [x] basic文件夹添加CS205内容,方便入门C++ ++ [x] basic文件夹添加CS205内容, 方便入门C++ + [x] 以及一部分rust代码 + [ ] Cyaron测试数据生成 + [ ] WiKi Page @@ -334,7 +331,7 @@ Don't forget to give the project a star! Thanks again! ### AGPLv3.0+ LICENSE -绝大多数代码(`*.cpp`,`*.hpp`,etc)基于 AGPLv3.0+协议: 限制最强的主流开源协议 +绝大多数代码(`*.cpp`, `*.hpp`, etc)基于 AGPLv3.0+协议: 限制最强的主流开源协议 + 由于本仓库设计只包括"上交"源码这一种场景, 因此实际上不存在二进制分发以及被云服务使用这种场景. + 具体内容请看[`LICENSE_AGPL_V3_0.md`](./LICENSE_AGPL_V3_0.md) @@ -345,9 +342,9 @@ some code is based on this license 所有其他非代码部分(主要是*.md)基于CC-BY-NC-SA-4.0(或以后版本)协议. + 相同方式共享-署名-非商业性使用的知识共享协议4.0或任何以后版本. -+ 署名(BY)-使用到相应内容的其他地方,应该加以注释,保留来源. -+ 非商业性使用(NC)-默认情况下,只要署名,可以在不盈利的情况下使用.(并不是指商业情况不能用,而是需要和原作者沟通) -+ 相同方式共享(SA)-使得协议具有传染性,只要其他内容采用了本repo的内容,就需要在署名的同时,保证其协议也是CC-BY-NC-SA-4.0 or later version. ++ 署名(BY)-使用到相应内容的其他地方, 应该加以注释, 保留来源. ++ 非商业性使用(NC)-默认情况下, 只要署名, 可以在不盈利的情况下使用.(并不是指商业情况不能用, 而是需要和原作者沟通) ++ 相同方式共享(SA)-使得协议具有传染性, 只要其他内容采用了本repo的内容, 就需要在署名的同时, 保证其协议也是CC-BY-NC-SA-4.0 or later version. + 具体内容请看[`LICENSE_CC_BY_NC_SA_V4_0.md`](./LICENSE_CC_BY_NC_SA_V4_0.md)

(back to top)

@@ -360,7 +357,7 @@ some code is based on this license 讨论内容相关的,请到 [Discussion][discussion_LINK] -Project Link: [https://github.com/Certseeds/CS203_DSAA_template][Project_LINK] +Project Link: [https://github.com/Certseeds/algorithm-template][Project_LINK]

(back to top)

@@ -378,32 +375,32 @@ Use this space to list resources you find helpful and would like to give credit 考虑到[whexy][GitHub-Whexy] 的博客文章[用两个晚上做超简易 OpenJudge][Two-Night-Online-Judge]里`因平台显著降低了作业难度。按任课教师要求已经关停。`这一句. -设计时将分布式1 去中心化2 跨平台3都纳入考虑. +设计时将分布式1 去中心化2 跨平台3都纳入考虑.

(back to top)

[Best-Readme-Template]: https://github.com/othneildrew/Best-README-Template -[Project_LINK]: https://github.com/Certseeds/CS203_DSAA_template -[issue_LINK]: https://github.com/Certseeds/CS203_DSAA_template/issues -[pr_LINK]: https://github.com/Certseeds/CS203_DSAA_template/pulls -[discussion_LINK]: https://github.com/Certseeds/CS203_DSAA_template/discussions +[Project_LINK]: https://github.com/Certseeds/algorithm-template +[issue_LINK]: https://github.com/Certseeds/algorithm-template/issues +[pr_LINK]: https://github.com/Certseeds/algorithm-template/pulls +[discussion_LINK]: https://github.com/Certseeds/algorithm-template/discussions [catch2_image]: https://raw.githubusercontent.com/catchorg/Catch2/v2.x/artwork/catch2-logo-small.png [AGPL-shield]: https://img.shields.io/badge/License-AGPL-orange?style=for-the-badge [AGPL_Link]: http://opensource.org/licenses/AGPL [cc_by_nc_sa_4_0_shield]: https://img.shields.io/badge/License-CC%20BY--NC--SA%204.0-orange?style=for-the-badge [cc_by_nc_sa_4_0]: https://creativecommons.org/licenses/by-nc-sa/4.0/ [cc_by_nc_sa_4_0_image]: https://licensebuttons.net/l/by-nc-sa/4.0/88x31.png -[contributors-shield]: https://img.shields.io/github/contributors/Certseeds/CS203_DSAA_template.svg?style=for-the-badge -[contributors-url]: https://github.com/Certseeds/CS203_DSAA_template/graphs/contributors -[forks-shield]: https://img.shields.io/github/forks/Certseeds/CS203_DSAA_template.svg?style=for-the-badge -[forks-url]: https://github.com/Certseeds/CS203_DSAA_template/network/members -[stars-shield]: https://img.shields.io/github/stars/Certseeds/CS203_DSAA_template.svg?style=for-the-badge -[stars-url]: https://github.com/Certseeds/CS203_DSAA_template/stargazers -[issues-shield]: https://img.shields.io/github/issues/Certseeds/CS203_DSAA_template.svg?style=for-the-badge -[issues-url]: https://github.com/Certseeds/CS203_DSAA_template/issues -[license-shield]: https://img.shields.io/github/license/Certseeds/CS203_DSAA_template.svg?style=for-the-badge -[license-url]: https://github.com/Certseeds/CS203_DSAA_template/blob/master/LICENSE.md -[release-shield]: https://img.shields.io/github/release/Certseeds/CS203_DSAA_template.svg?style=for-the-badge -[release-url]: https://github.com/Certseeds/CS203_DSAA_template/releases +[contributors-shield]: https://img.shields.io/github/contributors/Certseeds/algorithm-template.svg?style=for-the-badge +[contributors-url]: https://github.com/Certseeds/algorithm-template/graphs/contributors +[forks-shield]: https://img.shields.io/github/forks/Certseeds/algorithm-template.svg?style=for-the-badge +[forks-url]: https://github.com/Certseeds/algorithm-template/network/members +[stars-shield]: https://img.shields.io/github/stars/Certseeds/algorithm-template.svg?style=for-the-badge +[stars-url]: https://github.com/Certseeds/algorithm-template/stargazers +[issues-shield]: https://img.shields.io/github/issues/Certseeds/algorithm-template.svg?style=for-the-badge +[issues-url]: https://github.com/Certseeds/algorithm-template/issues +[license-shield]: https://img.shields.io/github/license/Certseeds/algorithm-template.svg?style=for-the-badge +[license-url]: https://github.com/Certseeds/algorithm-template/blob/master/LICENSE.md +[release-shield]: https://img.shields.io/github/release/Certseeds/algorithm-template.svg?style=for-the-badge +[release-url]: https://github.com/Certseeds/algorithm-template/releases [GitHub-Whexy]: https://github.com/whexy [Two-Night-Online-Judge]: https://www.whexy.com/posts/wannaAC diff --git a/algorithm/2020S/20200415/20200415.cpp b/algorithm/2020S/20200415/20200415.cpp index bd81f30c..9fcd29c1 100644 --- a/algorithm/2020S/20200415/20200415.cpp +++ b/algorithm/2020S/20200415/20200415.cpp @@ -1,10 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -#include #include +#include +#include #include #include @@ -16,7 +15,7 @@ int main() { int32_t n; cin >> n; unordered_map value_max; - int32_t max_v = INT32_MIN / 2; + int32_t max_v = std::numeric_limits::min() / 2; for (int32_t i = 0; i < n; ++i) { int32_t a; int32_t b; diff --git a/algorithm/2020S/20200426/20200426_1st.cpp b/algorithm/2020S/20200426/20200426_1st.cpp index 60158b31..ff10e495 100644 --- a/algorithm/2020S/20200426/20200426_1st.cpp +++ b/algorithm/2020S/20200426/20200426_1st.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include diff --git a/algorithm/2020S/20200426/20200426_3rd.cpp b/algorithm/2020S/20200426/20200426_3rd.cpp index 22ca5488..c99847a3 100644 --- a/algorithm/2020S/20200426/20200426_3rd.cpp +++ b/algorithm/2020S/20200426/20200426_3rd.cpp @@ -1,12 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include #include #include +#include int32_t main() { int32_t n{0}; @@ -25,7 +24,7 @@ int32_t main() { } std::sort(a.begin(), a.end()); std::sort(b.begin(), b.end()); - double min_value = INT32_MAX / 2; + double min_value = std::numeric_limits::max() / 2; struct compare { bool operator()(const std::pair &value, const int &key) { diff --git a/algorithm/2020S/20200426/20200426_4th.cpp b/algorithm/2020S/20200426/20200426_4th.cpp index 00462e24..54197922 100644 --- a/algorithm/2020S/20200426/20200426_4th.cpp +++ b/algorithm/2020S/20200426/20200426_4th.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include diff --git a/algorithm/2020S/20200426/20200426_5th.cpp b/algorithm/2020S/20200426/20200426_5th.cpp index 2154ad9c..d1b3b468 100644 --- a/algorithm/2020S/20200426/20200426_5th.cpp +++ b/algorithm/2020S/20200426/20200426_5th.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include diff --git a/algorithm/2020S/20200511/20200511_4th.cpp b/algorithm/2020S/20200511/20200511_4th.cpp index 0245abb4..8643017b 100644 --- a/algorithm/2020S/20200511/20200511_4th.cpp +++ b/algorithm/2020S/20200511/20200511_4th.cpp @@ -1,14 +1,12 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace fourth_20200511{ #endif @@ -68,6 +66,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2020S/20200511/20200511_4th_test.cpp b/algorithm/2020S/20200511/20200511_4th_test.cpp index 6a6dfb8d..99ad6bb7 100644 --- a/algorithm/2020S/20200511/20200511_4th_test.cpp +++ b/algorithm/2020S/20200511/20200511_4th_test.cpp @@ -1,11 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include @@ -46,4 +41,4 @@ TEST_CASE("test case with sequence", "[test 4th_20200511 1]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2020S/20200511/20200511_fst.cpp b/algorithm/2020S/20200511/20200511_fst.cpp index 28dedfb3..74165798 100644 --- a/algorithm/2020S/20200511/20200511_fst.cpp +++ b/algorithm/2020S/20200511/20200511_fst.cpp @@ -1,14 +1,12 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace fst_20200511{ #endif @@ -71,6 +69,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2020S/20200511/20200511_fst_test.cpp b/algorithm/2020S/20200511/20200511_fst_test.cpp index 5ab917bf..aeaa9b58 100644 --- a/algorithm/2020S/20200511/20200511_fst_test.cpp +++ b/algorithm/2020S/20200511/20200511_fst_test.cpp @@ -1,11 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include @@ -46,4 +41,4 @@ TEST_CASE("test case with sequence", "[test 02 A]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2020S/20200511/20200511_snd.cpp b/algorithm/2020S/20200511/20200511_snd.cpp index fc2da509..59b1a5ae 100644 --- a/algorithm/2020S/20200511/20200511_snd.cpp +++ b/algorithm/2020S/20200511/20200511_snd.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include @@ -9,7 +7,7 @@ #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace snd_20200511 { #endif @@ -75,6 +73,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2020S/20200511/20200511_snd_test.cpp b/algorithm/2020S/20200511/20200511_snd_test.cpp index 7d5ac17c..20e4fc01 100644 --- a/algorithm/2020S/20200511/20200511_snd_test.cpp +++ b/algorithm/2020S/20200511/20200511_snd_test.cpp @@ -1,11 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include @@ -46,4 +41,4 @@ TEST_CASE("test case with sequence", "[test snd_20200511 1]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2020S/20200511/20200511_trd.cpp b/algorithm/2020S/20200511/20200511_trd.cpp index 7f113e04..c6566854 100644 --- a/algorithm/2020S/20200511/20200511_trd.cpp +++ b/algorithm/2020S/20200511/20200511_trd.cpp @@ -1,13 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace trd_20200511{ #endif @@ -44,6 +42,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2020S/20200511/20200511_trd_test.cpp b/algorithm/2020S/20200511/20200511_trd_test.cpp index d928c8aa..5a3c6090 100644 --- a/algorithm/2020S/20200511/20200511_trd_test.cpp +++ b/algorithm/2020S/20200511/20200511_trd_test.cpp @@ -1,11 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include @@ -46,4 +41,4 @@ TEST_CASE("test case with sequence", "[test trd_20200511 1]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2020S/20200511/CMakeLists.txt b/algorithm/2020S/20200511/CMakeLists.txt index fbd7160a..b728bb04 100644 --- a/algorithm/2020S/20200511/CMakeLists.txt +++ b/algorithm/2020S/20200511/CMakeLists.txt @@ -11,8 +11,8 @@ foreach (elementName IN LISTS dependencies) add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_DAY}_${elementName}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_${elementName}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_DAY}_${elementName}_test.cpp) - target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE CS203_DSAA_TEST_MACRO) - target_link_libraries(${PROJECT_NAME}_${elementName}_test PRIVATE CS203_DSAA_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE ALGORITHM_TEST_MACRO) + target_link_libraries(${PROJECT_NAME}_${elementName}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_DAY}_${elementName}.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2020S/20200610/20200610_fst.cpp b/algorithm/2020S/20200610/20200610_fst.cpp index 0cefdf86..4d447c08 100644 --- a/algorithm/2020S/20200610/20200610_fst.cpp +++ b/algorithm/2020S/20200610/20200610_fst.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include @@ -9,7 +7,7 @@ #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace fst_20200610 { #endif @@ -107,6 +105,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2020S/20200610/20200610_snd.cpp b/algorithm/2020S/20200610/20200610_snd.cpp index 8cbb9c08..f7a5557d 100644 --- a/algorithm/2020S/20200610/20200610_snd.cpp +++ b/algorithm/2020S/20200610/20200610_snd.cpp @@ -1,13 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace snd_20200610 { #endif @@ -58,6 +56,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2020S/20200610/20200610_trd.cpp b/algorithm/2020S/20200610/20200610_trd.cpp index 589309cf..f4438ff6 100644 --- a/algorithm/2020S/20200610/20200610_trd.cpp +++ b/algorithm/2020S/20200610/20200610_trd.cpp @@ -1,12 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace trd_20200610 { #endif @@ -45,6 +43,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_02/lab_02_A/CMakeLists.txt b/algorithm/2021F/lab_02/lab_02_A/CMakeLists.txt index 41fc7dbf..354751e1 100644 --- a/algorithm/2021F/lab_02/lab_02_A/CMakeLists.txt +++ b/algorithm/2021F/lab_02/lab_02_A/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_02/lab_02_A/lab_02_A.cpp b/algorithm/2021F/lab_02/lab_02_A/lab_02_A.cpp index dfb24368..ec9440ec 100644 --- a/algorithm/2021F/lab_02/lab_02_A/lab_02_A.cpp +++ b/algorithm/2021F/lab_02/lab_02_A/lab_02_A.cpp @@ -1,19 +1,16 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Done + #include #include #include +#include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_02_A{ #endif @@ -101,6 +98,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_02/lab_02_A/lab_02_A_test.cpp b/algorithm/2021F/lab_02/lab_02_A/lab_02_A_test.cpp index 0470e2c9..d64aaa4d 100644 --- a/algorithm/2021F/lab_02/lab_02_A/lab_02_A_test.cpp +++ b/algorithm/2021F/lab_02/lab_02_A/lab_02_A_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_02_A.cpp" @@ -45,4 +41,4 @@ TEST_CASE("test case with sequence", "[test 02 A]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_02/lab_02_B/CMakeLists.txt b/algorithm/2021F/lab_02/lab_02_B/CMakeLists.txt index 571102e9..c490830a 100644 --- a/algorithm/2021F/lab_02/lab_02_B/CMakeLists.txt +++ b/algorithm/2021F/lab_02/lab_02_B/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_02/lab_02_B/lab_02_B.cpp b/algorithm/2021F/lab_02/lab_02_B/lab_02_B.cpp index ce7a740d..d60e11b8 100644 --- a/algorithm/2021F/lab_02/lab_02_B/lab_02_B.cpp +++ b/algorithm/2021F/lab_02/lab_02_B/lab_02_B.cpp @@ -1,18 +1,14 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Done #include #include +#include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_02_B{ #endif @@ -75,6 +71,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_02/lab_02_B/lab_02_B_test.cpp b/algorithm/2021F/lab_02/lab_02_B/lab_02_B_test.cpp index 7eb83a94..3ec7c3b6 100644 --- a/algorithm/2021F/lab_02/lab_02_B/lab_02_B_test.cpp +++ b/algorithm/2021F/lab_02/lab_02_B/lab_02_B_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_02_B.cpp" @@ -46,4 +42,4 @@ TEST_CASE("test case with sequence", "[test 02 B]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_02/lab_02_C/CMakeLists.txt b/algorithm/2021F/lab_02/lab_02_C/CMakeLists.txt index 8809d6b1..5de3f24f 100644 --- a/algorithm/2021F/lab_02/lab_02_C/CMakeLists.txt +++ b/algorithm/2021F/lab_02/lab_02_C/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_02/lab_02_C/lab_02_C.cpp b/algorithm/2021F/lab_02/lab_02_C/lab_02_C.cpp index 3b84a609..65556b25 100644 --- a/algorithm/2021F/lab_02/lab_02_C/lab_02_C.cpp +++ b/algorithm/2021F/lab_02/lab_02_C/lab_02_C.cpp @@ -1,21 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Done #include #include #include #include +#include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_02_C{ #endif @@ -110,6 +106,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_02/lab_02_C/lab_02_C_test.cpp b/algorithm/2021F/lab_02/lab_02_C/lab_02_C_test.cpp index f5c79869..3d910870 100644 --- a/algorithm/2021F/lab_02/lab_02_C/lab_02_C_test.cpp +++ b/algorithm/2021F/lab_02/lab_02_C/lab_02_C_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_02_C.cpp" @@ -59,4 +55,4 @@ TEST_CASE("test case with sequence", "[test 02 C][.]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_02/lab_02_D/CMakeLists.txt b/algorithm/2021F/lab_02/lab_02_D/CMakeLists.txt index ffff7238..dce330ce 100644 --- a/algorithm/2021F/lab_02/lab_02_D/CMakeLists.txt +++ b/algorithm/2021F/lab_02/lab_02_D/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_02/lab_02_D/lab_02_D.cpp b/algorithm/2021F/lab_02/lab_02_D/lab_02_D.cpp index 4551a30e..d7844610 100644 --- a/algorithm/2021F/lab_02/lab_02_D/lab_02_D.cpp +++ b/algorithm/2021F/lab_02/lab_02_D/lab_02_D.cpp @@ -1,19 +1,15 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Done #include +#include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_02_D{ #endif // 10^9 * 2 < 2^31 -1 @@ -119,6 +115,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_02/lab_02_D/lab_02_D_test.cpp b/algorithm/2021F/lab_02/lab_02_D/lab_02_D_test.cpp index 8e58dfb5..100e7d23 100644 --- a/algorithm/2021F/lab_02/lab_02_D/lab_02_D_test.cpp +++ b/algorithm/2021F/lab_02/lab_02_D/lab_02_D_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_02_D.cpp" @@ -65,4 +61,4 @@ TEST_CASE("test case with sequence", "[.][test 02 D]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_02/lab_02_E/CMakeLists.txt b/algorithm/2021F/lab_02/lab_02_E/CMakeLists.txt index 7e7867bb..c43d3c98 100644 --- a/algorithm/2021F/lab_02/lab_02_E/CMakeLists.txt +++ b/algorithm/2021F/lab_02/lab_02_E/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_02/lab_02_E/lab_02_E.cpp b/algorithm/2021F/lab_02/lab_02_E/lab_02_E.cpp index 39c132d6..a1939137 100644 --- a/algorithm/2021F/lab_02/lab_02_E/lab_02_E.cpp +++ b/algorithm/2021F/lab_02/lab_02_E/lab_02_E.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag TODO #include #include @@ -14,13 +9,14 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_02_E{ #endif @@ -102,6 +98,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_02/lab_02_E/lab_02_E_test.cpp b/algorithm/2021F/lab_02/lab_02_E/lab_02_E_test.cpp index cfe2363f..0c9ba9af 100644 --- a/algorithm/2021F/lab_02/lab_02_E/lab_02_E_test.cpp +++ b/algorithm/2021F/lab_02/lab_02_E/lab_02_E_test.cpp @@ -1,14 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include +#include #include #include @@ -59,4 +55,4 @@ TEST_CASE("test case with sequence", "[test 02 E]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_02/lab_02_F/CMakeLists.txt b/algorithm/2021F/lab_02/lab_02_F/CMakeLists.txt index b6564222..7bd14a82 100644 --- a/algorithm/2021F/lab_02/lab_02_F/CMakeLists.txt +++ b/algorithm/2021F/lab_02/lab_02_F/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_02/lab_02_F/lab_02_F.cpp b/algorithm/2021F/lab_02/lab_02_F/lab_02_F.cpp index 6f1c5d17..b0505237 100644 --- a/algorithm/2021F/lab_02/lab_02_F/lab_02_F.cpp +++ b/algorithm/2021F/lab_02/lab_02_F/lab_02_F.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag TODO #include #include @@ -14,13 +9,14 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_02_F{ #endif @@ -86,6 +82,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_02/lab_02_F/lab_02_F_test.cpp b/algorithm/2021F/lab_02/lab_02_F/lab_02_F_test.cpp index 847585aa..efde1036 100644 --- a/algorithm/2021F/lab_02/lab_02_F/lab_02_F_test.cpp +++ b/algorithm/2021F/lab_02/lab_02_F/lab_02_F_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_02_F.cpp" @@ -62,4 +58,4 @@ TEST_CASE("test case with sequence", "[test 02 F][.]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_03/lab_03_A/CMakeLists.txt b/algorithm/2021F/lab_03/lab_03_A/CMakeLists.txt index 41fc7dbf..354751e1 100644 --- a/algorithm/2021F/lab_03/lab_03_A/CMakeLists.txt +++ b/algorithm/2021F/lab_03/lab_03_A/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_03/lab_03_A/lab_03_A.cpp b/algorithm/2021F/lab_03/lab_03_A/lab_03_A.cpp index d4861d02..7e584667 100644 --- a/algorithm/2021F/lab_03/lab_03_A/lab_03_A.cpp +++ b/algorithm/2021F/lab_03/lab_03_A/lab_03_A.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* * @题目描述 * 在____内, 如果数组C中,有 i,j ∈N+, i < j, C[i]>C[j], 则 (C[i],C[j])为一个逆序对 @@ -27,10 +22,11 @@ Copyright (C) 2020-2023 nanoseeds //@Tag Done #include #include +#include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_03_A{ #endif @@ -151,6 +147,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_03/lab_03_A/lab_03_A_test.cpp b/algorithm/2021F/lab_03/lab_03_A/lab_03_A_test.cpp index 1d6db449..dab569ba 100644 --- a/algorithm/2021F/lab_03/lab_03_A/lab_03_A_test.cpp +++ b/algorithm/2021F/lab_03/lab_03_A/lab_03_A_test.cpp @@ -1,19 +1,15 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag 归并排序 //@Tag Merge Sort //@Tag 逆序对 -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_03_A.cpp" @@ -55,4 +51,4 @@ TEST_CASE("test case with sequence", "[test 03 A]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_03/lab_03_B/CMakeLists.txt b/algorithm/2021F/lab_03/lab_03_B/CMakeLists.txt index 571102e9..c490830a 100644 --- a/algorithm/2021F/lab_03/lab_03_B/CMakeLists.txt +++ b/algorithm/2021F/lab_03/lab_03_B/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_03/lab_03_B/lab_03_B.cpp b/algorithm/2021F/lab_03/lab_03_B/lab_03_B.cpp index 5d63fbb9..a0cd5b2d 100644 --- a/algorithm/2021F/lab_03/lab_03_B/lab_03_B.cpp +++ b/algorithm/2021F/lab_03/lab_03_B/lab_03_B.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* * @题目描述 * 数组α具有ν个元素,请输出数组a `中位数的double形式` @@ -27,11 +22,12 @@ Copyright (C) 2020-2023 nanoseeds #pragma GCC target("mmx") #include +#include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_03_B{ #endif @@ -135,6 +131,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_03/lab_03_B/lab_03_B_test.cpp b/algorithm/2021F/lab_03/lab_03_B/lab_03_B_test.cpp index b655ff92..7fa0a73f 100644 --- a/algorithm/2021F/lab_03/lab_03_B/lab_03_B_test.cpp +++ b/algorithm/2021F/lab_03/lab_03_B/lab_03_B_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_03_B.cpp" @@ -51,4 +47,4 @@ TEST_CASE("test case with sequence", "[test 03 B]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_03/lab_03_C/CMakeLists.txt b/algorithm/2021F/lab_03/lab_03_C/CMakeLists.txt index 8809d6b1..5de3f24f 100644 --- a/algorithm/2021F/lab_03/lab_03_C/CMakeLists.txt +++ b/algorithm/2021F/lab_03/lab_03_C/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_03/lab_03_C/lab_03_C.cpp b/algorithm/2021F/lab_03/lab_03_C/lab_03_C.cpp index af2fbffe..fd6f742b 100644 --- a/algorithm/2021F/lab_03/lab_03_C/lab_03_C.cpp +++ b/algorithm/2021F/lab_03/lab_03_C/lab_03_C.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* *@题目描述 * 输入为一个无序序列, 请分别插入排序和选择排序,并比较哪一个更好 @@ -34,13 +29,14 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_03_C{ #endif // TODO @@ -182,6 +178,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_03/lab_03_C/lab_03_C_test.cpp b/algorithm/2021F/lab_03/lab_03_C/lab_03_C_test.cpp index e52013f4..0771abb8 100644 --- a/algorithm/2021F/lab_03/lab_03_C/lab_03_C_test.cpp +++ b/algorithm/2021F/lab_03/lab_03_C/lab_03_C_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_03_C.cpp" @@ -52,4 +48,4 @@ TEST_CASE("test case with sequence", "[test 03 C]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_03/lab_03_D/CMakeLists.txt b/algorithm/2021F/lab_03/lab_03_D/CMakeLists.txt index ffff7238..dce330ce 100644 --- a/algorithm/2021F/lab_03/lab_03_D/CMakeLists.txt +++ b/algorithm/2021F/lab_03/lab_03_D/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_03/lab_03_D/lab_03_D.cpp b/algorithm/2021F/lab_03/lab_03_D/lab_03_D.cpp index c5e8a263..9c634dc8 100644 --- a/algorithm/2021F/lab_03/lab_03_D/lab_03_D.cpp +++ b/algorithm/2021F/lab_03/lab_03_D/lab_03_D.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include @@ -13,13 +8,14 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_03_D{ #endif @@ -85,6 +81,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_03/lab_03_D/lab_03_D_test.cpp b/algorithm/2021F/lab_03/lab_03_D/lab_03_D_test.cpp index c4c33a92..b1f14950 100644 --- a/algorithm/2021F/lab_03/lab_03_D/lab_03_D_test.cpp +++ b/algorithm/2021F/lab_03/lab_03_D/lab_03_D_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_03_D.cpp" @@ -63,4 +59,4 @@ TEST_CASE("test case with sequence", "[test 03 D][.]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_03/lab_03_E/CMakeLists.txt b/algorithm/2021F/lab_03/lab_03_E/CMakeLists.txt index 7e7867bb..c43d3c98 100644 --- a/algorithm/2021F/lab_03/lab_03_E/CMakeLists.txt +++ b/algorithm/2021F/lab_03/lab_03_E/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_03/lab_03_E/lab_03_E.cpp b/algorithm/2021F/lab_03/lab_03_E/lab_03_E.cpp index aa61a9b9..75c4a0a6 100644 --- a/algorithm/2021F/lab_03/lab_03_E/lab_03_E.cpp +++ b/algorithm/2021F/lab_03/lab_03_E/lab_03_E.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include @@ -13,13 +8,14 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_03_E{ #endif @@ -85,6 +81,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_03/lab_03_E/lab_03_E_test.cpp b/algorithm/2021F/lab_03/lab_03_E/lab_03_E_test.cpp index ce6acc43..2ed5a30f 100644 --- a/algorithm/2021F/lab_03/lab_03_E/lab_03_E_test.cpp +++ b/algorithm/2021F/lab_03/lab_03_E/lab_03_E_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_03_E.cpp" @@ -63,4 +59,4 @@ TEST_CASE("test case with sequence", "[test 03 E][.]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_03/lab_03_F/CMakeLists.txt b/algorithm/2021F/lab_03/lab_03_F/CMakeLists.txt index b6564222..7bd14a82 100644 --- a/algorithm/2021F/lab_03/lab_03_F/CMakeLists.txt +++ b/algorithm/2021F/lab_03/lab_03_F/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_03/lab_03_F/lab_03_F.cpp b/algorithm/2021F/lab_03/lab_03_F/lab_03_F.cpp index 44cdb119..cba4a8b2 100644 --- a/algorithm/2021F/lab_03/lab_03_F/lab_03_F.cpp +++ b/algorithm/2021F/lab_03/lab_03_F/lab_03_F.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include @@ -13,13 +8,14 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_03_F{ #endif @@ -85,6 +81,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_03/lab_03_F/lab_03_F_test.cpp b/algorithm/2021F/lab_03/lab_03_F/lab_03_F_test.cpp index 38cbc180..eed57d8f 100644 --- a/algorithm/2021F/lab_03/lab_03_F/lab_03_F_test.cpp +++ b/algorithm/2021F/lab_03/lab_03_F/lab_03_F_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_03_F.cpp" @@ -63,4 +59,4 @@ TEST_CASE("test case with sequence", "[test 03 F][.]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_04/lab_04_2A/CMakeLists.txt b/algorithm/2021F/lab_04/lab_04_2A/CMakeLists.txt index 9f7dbcfb..a78119fe 100644 --- a/algorithm/2021F/lab_04/lab_04_2A/CMakeLists.txt +++ b/algorithm/2021F/lab_04/lab_04_2A/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_04/lab_04_2A/lab_04_2A.cpp b/algorithm/2021F/lab_04/lab_04_2A/lab_04_2A.cpp index e399b501..b4409daf 100644 --- a/algorithm/2021F/lab_04/lab_04_2A/lab_04_2A.cpp +++ b/algorithm/2021F/lab_04/lab_04_2A/lab_04_2A.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* *@题目描述 * 给出两个各有ν(希腊字母Nu),μ(希腊字母Mu)长的多项式Ν(大写希腊字母Nu),Μ(大写希腊字母Mu),请计算两者之和 @@ -20,7 +15,7 @@ Copyright (C) 2020-2023 nanoseeds * */ // DONE -#ifndef CS203_DSAA_TEST_MACRO +#ifndef ALGORITHM_TEST_MACRO #pragma GCC optimize(3, "Ofast", "inline", "no-stack-protector", "unroll-loops") #pragma GCC optimize("inline-small-functions") #pragma GCC optimize("-finline-small-functions") @@ -29,11 +24,12 @@ Copyright (C) 2020-2023 nanoseeds #include #include +#include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_04_2A{ #endif @@ -111,6 +107,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_04/lab_04_2A/lab_04_2A_test.cpp b/algorithm/2021F/lab_04/lab_04_2A/lab_04_2A_test.cpp index 3b67a4e8..70c6c80c 100644 --- a/algorithm/2021F/lab_04/lab_04_2A/lab_04_2A_test.cpp +++ b/algorithm/2021F/lab_04/lab_04_2A/lab_04_2A_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_04_2A.cpp" @@ -51,5 +47,5 @@ TEST_CASE("test case with sequence [test 04_2A]", "[test 04_2A]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_04/lab_04_A/CMakeLists.txt b/algorithm/2021F/lab_04/lab_04_A/CMakeLists.txt index 41fc7dbf..354751e1 100644 --- a/algorithm/2021F/lab_04/lab_04_A/CMakeLists.txt +++ b/algorithm/2021F/lab_04/lab_04_A/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_04/lab_04_A/lab_04_A.cpp b/algorithm/2021F/lab_04/lab_04_A/lab_04_A.cpp index a9caabae..1202c376 100644 --- a/algorithm/2021F/lab_04/lab_04_A/lab_04_A.cpp +++ b/algorithm/2021F/lab_04/lab_04_A/lab_04_A.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* *@题目描述 * 给出两个各有ν(希腊字母Nu),μ(希腊字母Mu)长的多项式Ν(大写希腊字母Nu),Μ(大写希腊字母Mu),请计算两者之和 @@ -19,7 +14,7 @@ Copyright (C) 2020-2023 nanoseeds * 之后分行输出 ${系数},${指数} * */ // DONE -#ifndef CS203_DSAA_TEST_MACRO +#ifndef ALGORITHM_TEST_MACRO #pragma GCC optimize(3, "Ofast", "inline", "no-stack-protector", "unroll-loops") #pragma GCC optimize("inline-small-functions") #pragma GCC optimize("-finline-small-functions") @@ -30,7 +25,7 @@ Copyright (C) 2020-2023 nanoseeds #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_04_A{ #endif @@ -96,6 +91,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_04/lab_04_A/lab_04_A_test.cpp b/algorithm/2021F/lab_04/lab_04_A/lab_04_A_test.cpp index f955254d..ff0ed881 100644 --- a/algorithm/2021F/lab_04/lab_04_A/lab_04_A_test.cpp +++ b/algorithm/2021F/lab_04/lab_04_A/lab_04_A_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_04_A.cpp" @@ -51,4 +47,4 @@ TEST_CASE("test case with sequence [test 04_A]", "[test 04_A]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_04/lab_04_B/CMakeLists.txt b/algorithm/2021F/lab_04/lab_04_B/CMakeLists.txt index 571102e9..c490830a 100644 --- a/algorithm/2021F/lab_04/lab_04_B/CMakeLists.txt +++ b/algorithm/2021F/lab_04/lab_04_B/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_04/lab_04_B/lab_04_B.cpp b/algorithm/2021F/lab_04/lab_04_B/lab_04_B.cpp index b1d056f2..0b02f524 100644 --- a/algorithm/2021F/lab_04/lab_04_B/lab_04_B.cpp +++ b/algorithm/2021F/lab_04/lab_04_B/lab_04_B.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* *@题目描述 * 甲 个学生排成一排 @@ -36,7 +31,7 @@ please find the going-out order of student. //@Tag Done -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO #include @@ -55,14 +50,15 @@ struct ListNode { explicit ListNode(int32_t x) : ListNode(x, nullptr) {} }; } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO #include +#include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_04_B{ #endif @@ -147,6 +143,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_04/lab_04_B/lab_04_B_test.cpp b/algorithm/2021F/lab_04/lab_04_B/lab_04_B_test.cpp index e2dd365b..05e1b242 100644 --- a/algorithm/2021F/lab_04/lab_04_B/lab_04_B_test.cpp +++ b/algorithm/2021F/lab_04/lab_04_B/lab_04_B_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_04_B.cpp" @@ -51,4 +47,4 @@ TEST_CASE("test case with sequence [test 04_B]", "[test 04_B]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_04/lab_04_C/CMakeLists.txt b/algorithm/2021F/lab_04/lab_04_C/CMakeLists.txt index 8809d6b1..5de3f24f 100644 --- a/algorithm/2021F/lab_04/lab_04_C/CMakeLists.txt +++ b/algorithm/2021F/lab_04/lab_04_C/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_04/lab_04_C/lab_04_C.cpp b/algorithm/2021F/lab_04/lab_04_C/lab_04_C.cpp index 8fc596c9..bfecda43 100644 --- a/algorithm/2021F/lab_04/lab_04_C/lab_04_C.cpp +++ b/algorithm/2021F/lab_04/lab_04_C/lab_04_C.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* *@题目描述 * 假设有一些自行车链条的链粒,每一个链粒都有一个权重 @@ -42,7 +37,7 @@ Copyright (C) 2020-2023 nanoseeds * 输出`3 5` * */ //@Tag DONE -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO #include @@ -65,15 +60,16 @@ struct ListNode { #pragma GCC optimize("inline-small-functions") #pragma GCC optimize("-finline-small-functions") #pragma GCC target("mmx") -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO #include #include +#include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_04_C{ #endif @@ -191,6 +187,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_04/lab_04_C/lab_04_C_test.cpp b/algorithm/2021F/lab_04/lab_04_C/lab_04_C_test.cpp index c8242e99..e41a9f71 100644 --- a/algorithm/2021F/lab_04/lab_04_C/lab_04_C_test.cpp +++ b/algorithm/2021F/lab_04/lab_04_C/lab_04_C_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_04_C.cpp" @@ -51,4 +47,4 @@ TEST_CASE("test case with sequence [test 04_C]", "[test 04_C]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_04/lab_04_D/CMakeLists.txt b/algorithm/2021F/lab_04/lab_04_D/CMakeLists.txt index ffff7238..dce330ce 100644 --- a/algorithm/2021F/lab_04/lab_04_D/CMakeLists.txt +++ b/algorithm/2021F/lab_04/lab_04_D/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_04/lab_04_D/lab_04_D.cpp b/algorithm/2021F/lab_04/lab_04_D/lab_04_D.cpp index 66b47481..14d51018 100644 --- a/algorithm/2021F/lab_04/lab_04_D/lab_04_D.cpp +++ b/algorithm/2021F/lab_04/lab_04_D/lab_04_D.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* *@题目描述 * 给一个序列 α, 一共有ν(希腊字母Nu)个元素,其中的第ι(希腊字幕iota)个元素为$α_ι$ @@ -40,7 +35,7 @@ Copyright (C) 2020-2023 nanoseeds * PS: 据说跳表也可以,没尝试故不分析 * */ //@Tag DONE -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO #else @@ -51,7 +46,7 @@ Copyright (C) 2020-2023 nanoseeds #pragma GCC optimize("inline-small-functions") #pragma GCC optimize("-finline-small-functions") #pragma GCC target("sse,sse2,mmx") -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO #include #include @@ -60,7 +55,7 @@ Copyright (C) 2020-2023 nanoseeds #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_04_D{ #endif using std::cin; @@ -357,6 +352,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_04/lab_04_D/lab_04_D_test.cpp b/algorithm/2021F/lab_04/lab_04_D/lab_04_D_test.cpp index 534ba05e..5416b01c 100644 --- a/algorithm/2021F/lab_04/lab_04_D/lab_04_D_test.cpp +++ b/algorithm/2021F/lab_04/lab_04_D/lab_04_D_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_04_D.cpp" @@ -51,4 +47,4 @@ TEST_CASE("test case with sequence [test 04_D]", "[test 04_D]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_05/lab_05_A/CMakeLists.txt b/algorithm/2021F/lab_05/lab_05_A/CMakeLists.txt index 41fc7dbf..354751e1 100644 --- a/algorithm/2021F/lab_05/lab_05_A/CMakeLists.txt +++ b/algorithm/2021F/lab_05/lab_05_A/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_05/lab_05_A/lab_05_A.cpp b/algorithm/2021F/lab_05/lab_05_A/lab_05_A.cpp index def2a0b8..a8b73128 100644 --- a/algorithm/2021F/lab_05/lab_05_A/lab_05_A.cpp +++ b/algorithm/2021F/lab_05/lab_05_A/lab_05_A.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* * @题目描述 * 惧亡者排成一个队列,每个惧亡者都有一个生体转化偏好 @@ -42,7 +37,7 @@ Copyright (C) 2020-2023 nanoseeds * */ //@Tag DONE -#ifndef CS203_DSAA_TEST_MACRO +#ifndef ALGORITHM_TEST_MACRO #pragma GCC optimize(3, "Ofast", "inline", "no-stack-protector", "unroll-loops") #pragma GCC optimize("inline-small-functions") #pragma GCC optimize("-finline-small-functions") @@ -52,10 +47,11 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_05_A{ #endif @@ -151,6 +147,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_05/lab_05_A/lab_05_A_test.cpp b/algorithm/2021F/lab_05/lab_05_A/lab_05_A_test.cpp index c094d7e0..82fff60a 100644 --- a/algorithm/2021F/lab_05/lab_05_A/lab_05_A_test.cpp +++ b/algorithm/2021F/lab_05/lab_05_A/lab_05_A_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_05_A.cpp" @@ -51,4 +47,4 @@ TEST_CASE("test case with sequence [test 05_A]", "[test 05_A]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_05/lab_05_B/CMakeLists.txt b/algorithm/2021F/lab_05/lab_05_B/CMakeLists.txt index 571102e9..c490830a 100644 --- a/algorithm/2021F/lab_05/lab_05_B/CMakeLists.txt +++ b/algorithm/2021F/lab_05/lab_05_B/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_05/lab_05_B/lab_05_B.cpp b/algorithm/2021F/lab_05/lab_05_B/lab_05_B.cpp index 4fb0a664..6dadf006 100644 --- a/algorithm/2021F/lab_05/lab_05_B/lab_05_B.cpp +++ b/algorithm/2021F/lab_05/lab_05_B/lab_05_B.cpp @@ -1,17 +1,12 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* * @题目描述 * TODO * */ //@Tag DONE -#ifndef CS203_DSAA_TEST_MACRO +#ifndef ALGORITHM_TEST_MACRO #pragma GCC optimize(3, "Ofast", "inline", "no-stack-protector", "unroll-loops") #pragma GCC optimize("inline-small-functions") #pragma GCC optimize("-finline-small-functions") @@ -22,9 +17,10 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_05_B{ #endif @@ -130,6 +126,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_05/lab_05_B/lab_05_B_test.cpp b/algorithm/2021F/lab_05/lab_05_B/lab_05_B_test.cpp index 95d994f6..49ace72f 100644 --- a/algorithm/2021F/lab_05/lab_05_B/lab_05_B_test.cpp +++ b/algorithm/2021F/lab_05/lab_05_B/lab_05_B_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_05_B.cpp" @@ -51,4 +47,4 @@ TEST_CASE("test case with sequence [test 05_B]", "[test 05_B]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_05/lab_05_C/CMakeLists.txt b/algorithm/2021F/lab_05/lab_05_C/CMakeLists.txt index 8809d6b1..5de3f24f 100644 --- a/algorithm/2021F/lab_05/lab_05_C/CMakeLists.txt +++ b/algorithm/2021F/lab_05/lab_05_C/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_05/lab_05_C/lab_05_C.cpp b/algorithm/2021F/lab_05/lab_05_C/lab_05_C.cpp index eb0d6b29..5e35f038 100644 --- a/algorithm/2021F/lab_05/lab_05_C/lab_05_C.cpp +++ b/algorithm/2021F/lab_05/lab_05_C/lab_05_C.cpp @@ -1,17 +1,12 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* * @题目描述 * 匹配括号,输出是否匹配 * */ //@Tag DONE -#ifndef CS203_DSAA_TEST_MACRO +#ifndef ALGORITHM_TEST_MACRO #pragma GCC optimize(3, "Ofast", "inline", "no-stack-protector", "unroll-loops") #pragma GCC optimize("inline-small-functions") #pragma GCC optimize("-finline-small-functions") @@ -24,9 +19,10 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_05_C{ #endif @@ -120,6 +116,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_05/lab_05_C/lab_05_C_test.cpp b/algorithm/2021F/lab_05/lab_05_C/lab_05_C_test.cpp index 1c4fb8c8..d995f90a 100644 --- a/algorithm/2021F/lab_05/lab_05_C/lab_05_C_test.cpp +++ b/algorithm/2021F/lab_05/lab_05_C/lab_05_C_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_05_C.cpp" @@ -51,4 +47,4 @@ TEST_CASE("test case with sequence [test 05_C]", "[test 05_C]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_05/lab_05_D/CMakeLists.txt b/algorithm/2021F/lab_05/lab_05_D/CMakeLists.txt index ffff7238..dce330ce 100644 --- a/algorithm/2021F/lab_05/lab_05_D/CMakeLists.txt +++ b/algorithm/2021F/lab_05/lab_05_D/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_05/lab_05_D/lab_05_D.cpp b/algorithm/2021F/lab_05/lab_05_D/lab_05_D.cpp index 94876dcb..f06e9626 100644 --- a/algorithm/2021F/lab_05/lab_05_D/lab_05_D.cpp +++ b/algorithm/2021F/lab_05/lab_05_D/lab_05_D.cpp @@ -1,16 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* * @题目描述 * */ //@Tag DONE -#ifndef CS203_DSAA_TEST_MACRO +#ifndef ALGORITHM_TEST_MACRO #pragma GCC optimize(3, "Ofast", "inline", "no-stack-protector", "unroll-loops") #pragma GCC optimize("inline-small-functions") #pragma GCC optimize("-finline-small-functions") @@ -21,9 +16,10 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_05_D{ #endif @@ -105,6 +101,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_05/lab_05_D/lab_05_D_test.cpp b/algorithm/2021F/lab_05/lab_05_D/lab_05_D_test.cpp index 2fa7b222..9958bb16 100644 --- a/algorithm/2021F/lab_05/lab_05_D/lab_05_D_test.cpp +++ b/algorithm/2021F/lab_05/lab_05_D/lab_05_D_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_05_D.cpp" @@ -50,4 +46,4 @@ TEST_CASE("test case with sequence [test 05_D]", "[test 05_D]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_welcome/lab_welcome_A/CMakeLists.txt b/algorithm/2021F/lab_welcome/lab_welcome_A/CMakeLists.txt index 41fc7dbf..354751e1 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_A/CMakeLists.txt +++ b/algorithm/2021F/lab_welcome/lab_welcome_A/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_welcome/lab_welcome_A/lab_welcome_A.cpp b/algorithm/2021F/lab_welcome/lab_welcome_A/lab_welcome_A.cpp index c805ca92..c788175b 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_A/lab_welcome_A.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_A/lab_welcome_A.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* * 题目描述 Given two arrays A with length n and B with length T. We want to know whether each element in array B is in array A or not. @@ -21,11 +16,12 @@ The 4th line contains T integers b1,b2,...,bT.For each bi∈[1,10^9] #include #include #include +#include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_welcome_A{ #endif @@ -111,6 +107,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_welcome/lab_welcome_A/lab_welcome_A_test.cpp b/algorithm/2021F/lab_welcome/lab_welcome_A/lab_welcome_A_test.cpp index 798ff7bd..9fa7bc85 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_A/lab_welcome_A_test.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_A/lab_welcome_A_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_welcome_A.cpp" @@ -56,4 +52,4 @@ TEST_CASE("test case with sequence", "[test welcome A]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_welcome/lab_welcome_B/CMakeLists.txt b/algorithm/2021F/lab_welcome/lab_welcome_B/CMakeLists.txt index 571102e9..c490830a 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_B/CMakeLists.txt +++ b/algorithm/2021F/lab_welcome/lab_welcome_B/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_welcome/lab_welcome_B/lab_welcome_B.cpp b/algorithm/2021F/lab_welcome/lab_welcome_B/lab_welcome_B.cpp index c0778359..32c6e38d 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_B/lab_welcome_B.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_B/lab_welcome_B.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* * 题目描述 Given two arrays A with length n and B with length T. We want to know whether each element in array B is in array A or not. @@ -21,11 +16,12 @@ The 4th line contains T integers b1,b2,...,bT.For each bi∈[1,10^5] #include #include #include +#include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_welcome_B{ #endif @@ -111,6 +107,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_welcome/lab_welcome_B/lab_welcome_B_test.cpp b/algorithm/2021F/lab_welcome/lab_welcome_B/lab_welcome_B_test.cpp index 241ae2e9..63ad632c 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_B/lab_welcome_B_test.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_B/lab_welcome_B_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_welcome_B.cpp" @@ -56,4 +52,4 @@ TEST_CASE("test case with sequence", "[test welcome B]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_welcome/lab_welcome_C/CMakeLists.txt b/algorithm/2021F/lab_welcome/lab_welcome_C/CMakeLists.txt index 8809d6b1..5de3f24f 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_C/CMakeLists.txt +++ b/algorithm/2021F/lab_welcome/lab_welcome_C/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_welcome/lab_welcome_C/lab_welcome_C.cpp b/algorithm/2021F/lab_welcome/lab_welcome_C/lab_welcome_C.cpp index 1a539a8b..a3019aac 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_C/lab_welcome_C.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_C/lab_welcome_C.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds /* *题目描述 Suppose in CS203, the number system only has three values 2,3,6. It holds 2<3<6. Given an integer n, please find the n-th smallest number in CS203 number system. @@ -36,7 +31,7 @@ Next T lines, each line contains an integer an integer n,[1,10^9] #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_welcome_C{ #endif @@ -137,6 +132,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_welcome/lab_welcome_C/lab_welcome_C_test.cpp b/algorithm/2021F/lab_welcome/lab_welcome_C/lab_welcome_C_test.cpp index de650c2a..7a89f766 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_C/lab_welcome_C_test.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_C/lab_welcome_C_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_welcome_C.cpp" @@ -50,4 +46,4 @@ TEST_CASE("test case 1", "[test welcome C]") { CHECK(cal_detail(1000000000) == "3226236233626363362"); } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_welcome/lab_welcome_D/CMakeLists.txt b/algorithm/2021F/lab_welcome/lab_welcome_D/CMakeLists.txt index ffff7238..dce330ce 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_D/CMakeLists.txt +++ b/algorithm/2021F/lab_welcome/lab_welcome_D/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_welcome/lab_welcome_D/lab_welcome_D.cpp b/algorithm/2021F/lab_welcome/lab_welcome_D/lab_welcome_D.cpp index ae561f33..05a5eb65 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_D/lab_welcome_D.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_D/lab_welcome_D.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include @@ -14,13 +9,14 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_welcome_D{ #endif @@ -195,6 +191,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_welcome/lab_welcome_D/lab_welcome_D_test.cpp b/algorithm/2021F/lab_welcome/lab_welcome_D/lab_welcome_D_test.cpp index e2e30062..5e01d183 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_D/lab_welcome_D_test.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_D/lab_welcome_D_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_welcome_D.cpp" @@ -51,4 +47,4 @@ TEST_CASE("test case with sequence", "[test welcome D]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_welcome/lab_welcome_E/CMakeLists.txt b/algorithm/2021F/lab_welcome/lab_welcome_E/CMakeLists.txt index 7e7867bb..c43d3c98 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_E/CMakeLists.txt +++ b/algorithm/2021F/lab_welcome/lab_welcome_E/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_welcome/lab_welcome_E/lab_welcome_E.cpp b/algorithm/2021F/lab_welcome/lab_welcome_E/lab_welcome_E.cpp index 764a75ab..0c2eaae2 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_E/lab_welcome_E.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_E/lab_welcome_E.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include @@ -14,13 +9,14 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_welcome_E{ #endif @@ -87,6 +83,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_welcome/lab_welcome_E/lab_welcome_E_test.cpp b/algorithm/2021F/lab_welcome/lab_welcome_E/lab_welcome_E_test.cpp index a05b4d2f..04b92ff6 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_E/lab_welcome_E_test.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_E/lab_welcome_E_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_welcome_E.cpp" @@ -62,4 +58,4 @@ TEST_CASE("test case with sequence", "[test welcome E][.]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/2021F/lab_welcome/lab_welcome_F/CMakeLists.txt b/algorithm/2021F/lab_welcome/lab_welcome_F/CMakeLists.txt index b6564222..7bd14a82 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_F/CMakeLists.txt +++ b/algorithm/2021F/lab_welcome/lab_welcome_F/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/2021F/lab_welcome/lab_welcome_F/lab_welcome_F.cpp b/algorithm/2021F/lab_welcome/lab_welcome_F/lab_welcome_F.cpp index 1a8cf1e8..989620ad 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_F/lab_welcome_F.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_F/lab_welcome_F.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include @@ -14,13 +9,14 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include #include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_welcome_F{ #endif @@ -87,6 +83,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/algorithm/2021F/lab_welcome/lab_welcome_F/lab_welcome_F_test.cpp b/algorithm/2021F/lab_welcome/lab_welcome_F/lab_welcome_F_test.cpp index 669d2429..2f13cd5e 100644 --- a/algorithm/2021F/lab_welcome/lab_welcome_F/lab_welcome_F_test.cpp +++ b/algorithm/2021F/lab_welcome/lab_welcome_F/lab_welcome_F_test.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include #include #include "lab_welcome_F.cpp" @@ -62,4 +58,4 @@ TEST_CASE("test case with sequence", "[test welcome F][.]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/algorithm/array/CMakeLists.txt b/algorithm/array/CMakeLists.txt index 3ee9ee96..fd67b98a 100644 --- a/algorithm/array/CMakeLists.txt +++ b/algorithm/array/CMakeLists.txt @@ -24,7 +24,7 @@ list(APPEND leetcode_order 944 977 985 986 989) list(APPEND leetcode_order 999 1010 1013 1030 1051) list(APPEND leetcode_order 1089 1108 1170 1184 1200) list(APPEND leetcode_order 1217 1329 1360 1365 1371) -list(APPEND leetcode_order 1391) +list(APPEND leetcode_order 1391 golden_0812) LIST(TRANSFORM leetcode_order PREPEND leetcode_) set(dependencies ${dependencies} ${leetcode_order}) @@ -32,10 +32,10 @@ set(dependencies ${dependencies} ${leetcode_order}) unset(leetcode_order) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE CS203_DSAA_TEST_MACRO) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) endforeach () unset(dependencies) diff --git a/algorithm/array/leetcode_1.cpp b/algorithm/array/leetcode_1.cpp index 59f2981c..34355889 100644 --- a/algorithm/array/leetcode_1.cpp +++ b/algorithm/array/leetcode_1.cpp @@ -1,29 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_1_test.hpp" #include +#include +#include +#include namespace leetcode_1 { using std::unordered_map; +using std::vector; +#endif -vector leetcode_1::twoSum(const vector &nums, int32_t target) { - const auto nums_size{nums.size()}; - unordered_map umaps; - for (size_t i{0}; i < nums_size; i++) { - if (umaps.find(target - nums[i]) != std::end(umaps)) { - return {static_cast(i), umaps[target - nums[i]] - 1}; +class Solution { +public: + vector twoSum(const vector &nums, int32_t target) { + const auto nums_size{nums.size()}; + unordered_map umaps; + for (size_t i{0}; i < nums_size; i++) { + if (umaps.find(target - nums[i]) != std::end(umaps)) { + return {static_cast(i), umaps[target - nums[i]] - 1}; + } + umaps[nums[i]] = static_cast(i) + 1; } - umaps[nums[i]] = static_cast(i) + 1; + return {}; } - return {}; -} +}; + /* if the number is not so big, it's better to use brute force, if number > 50,choose hashmap. */ +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/array/leetcode_1010.cpp b/algorithm/array/leetcode_1010.cpp index 48062913..43ab2b57 100644 --- a/algorithm/array/leetcode_1010.cpp +++ b/algorithm/array/leetcode_1010.cpp @@ -1,24 +1,29 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1010_test.hpp" +#include #include +#include namespace leetcode_1010 { +using std::vector; using std::array; +#endif -int32_t leetcode_1010::numPairsDivisibleBy60(const vector &time) { - array uses{0}; - int32_t willreturn{0}; - for (const int32_t i: time) { - uses[i % 60]++; - willreturn += uses[(60 - i % 60) % 60]; +class Solution { +public: + int32_t numPairsDivisibleBy60(const vector &time) { + array uses{0}; + int32_t willreturn{0}; + for (const int32_t i: time) { + uses[i % 60]++; + willreturn += uses[(60 - i % 60) % 60]; + } + return willreturn - uses[30] - uses[0]; } - return willreturn - uses[30] - uses[0]; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1010_test.cpp b/algorithm/array/leetcode_1010_test.cpp new file mode 100644 index 00000000..1dc0ac71 --- /dev/null +++ b/algorithm/array/leetcode_1010_test.cpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 暴力解法 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1010_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1010_TEST_HPP + +#include "leetcode_1010.cpp" +#include + +namespace leetcode_1010 { +using std::vector; + + +TEST_CASE("test case 1 {test_1010}", "{test_1010}") { + auto sol = Solution(); + const vector input{30, 20, 150, 100, 40}; + static constexpr const auto result{3}; + CHECK(result == sol.numPairsDivisibleBy60(input)); +} + +TEST_CASE("test case 2 {test_1010}", "{test_1010}") { + auto sol = Solution(); + const vector input{60, 60, 60}; + static constexpr const auto result{3}; + CHECK(result == sol.numPairsDivisibleBy60(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1010_TEST_HPP diff --git a/algorithm/array/leetcode_1010_test.hpp b/algorithm/array/leetcode_1010_test.hpp deleted file mode 100644 index 3ec4f0fe..00000000 --- a/algorithm/array/leetcode_1010_test.hpp +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 暴力解法 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1010_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1010_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_1010 { -using std::vector; - -struct leetcode_1010 { - static int32_t numPairsDivisibleBy60(const vector &time); -}; - -TEST_CASE("test case 1 {test_1010}", "{test_1010}") { - const vector input{30, 20, 150, 100, 40}; - static constexpr const auto result{3}; - CHECK(result == leetcode_1010::numPairsDivisibleBy60(input)); -} - -TEST_CASE("test case 2 {test_1010}", "{test_1010}") { - const vector input{60, 60, 60}; - static constexpr const auto result{3}; - CHECK(result == leetcode_1010::numPairsDivisibleBy60(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1010_TEST_HPP diff --git a/algorithm/array/leetcode_1013.cpp b/algorithm/array/leetcode_1013.cpp index a442918f..fb4a0d04 100644 --- a/algorithm/array/leetcode_1013.cpp +++ b/algorithm/array/leetcode_1013.cpp @@ -1,34 +1,40 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1013_test.hpp" +#include #include +#include namespace leetcode_1013 { +using std::vector; +#endif -bool leetcode_1013::canThreePartsEqualSum(const vector &arr) { - const int32_t sums = std::accumulate(arr.begin(), arr.end(), 0); - if (sums % 3 != 0) { - return false; - } - const int32_t divide = sums / 3; - for (int x{1}, y = arr.size() - 2, sum_x{arr.front()}, sum_y{arr.back()}; x < y;) { - if (sum_x != divide) { - sum_x += arr[x]; - x++; - } - if (sum_y != divide) { - sum_y += arr[y]; - y--; +class Solution { +public: + bool canThreePartsEqualSum(std::vector &arr) { + const int32_t sums = std::accumulate(arr.begin(), arr.end(), 0); + if (sums % 3 != 0) { + return false; } - if (sum_x == divide && sum_y == divide && x <= y) { - return true; + const int32_t divide = sums / 3; + for (int32_t x{1}, y = arr.size() - 2, sum_x{arr.front()}, sum_y{arr.back()}; x < y;) { + if (sum_x != divide) { + sum_x += arr[x]; + x++; + } + if (sum_y != divide) { + sum_y += arr[y]; + y--; + } + if (sum_x == divide && sum_y == divide && x <= y) { + return true; + } } + return false; } - return false; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1013_test.cpp b/algorithm/array/leetcode_1013_test.cpp new file mode 100644 index 00000000..d6c66344 --- /dev/null +++ b/algorithm/array/leetcode_1013_test.cpp @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag "双"指针 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1013_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1013_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_1013.cpp" + +namespace leetcode_1013 { + +TEST_CASE("test case 1 {test_1013}", "{test_1013}") { + auto sol = Solution(); + std::vector input{1, -1, 1, -1}; + CHECK_FALSE(sol.canThreePartsEqualSum(input)); +} + +TEST_CASE("test case 5 {test_1013}", "{test_1013}") { + auto sol = Solution(); + std::vector input{0, 1, -1, 1, -1, 0}; + CHECK(sol.canThreePartsEqualSum(input)); +} + +TEST_CASE("test case 2 {test_1013}", "{test_1013}") { + auto sol = Solution(); + std::vector input{3, 3, 6, 5, -2, 2, 5, 1, -9, 4}; + CHECK(sol.canThreePartsEqualSum(input)); +} + +TEST_CASE("test case 3 {test_1013}", "{test_1013}") { + auto sol = Solution(); + std::vector input{0, 2, 1, -6, 6, -7, 9, 1, 2, 0, 1}; + CHECK(sol.canThreePartsEqualSum(input)); +} + +TEST_CASE("test case 4 {test_1013}", "{test_1013}") { + auto sol = Solution(); + std::vector input{0, 2, 1, -6, 6, 7, 9, -1, 2, 0, 1}; + CHECK_FALSE(sol.canThreePartsEqualSum(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1013_TEST_HPP diff --git a/algorithm/array/leetcode_1013_test.hpp b/algorithm/array/leetcode_1013_test.hpp deleted file mode 100644 index 7ce6f93c..00000000 --- a/algorithm/array/leetcode_1013_test.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag "双"指针 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1013_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1013_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_1013 { -using std::vector; - -struct leetcode_1013 { - static bool canThreePartsEqualSum(const vector &arr); -}; - -TEST_CASE("test case 1 {test_1013}", "{test_1013}") { - const vector input{1, -1, 1, -1}; - CHECK_FALSE(leetcode_1013::canThreePartsEqualSum(input)); -} - -TEST_CASE("test case 5 {test_1013}", "{test_1013}") { - const vector input{0, 1, -1, 1, -1, 0}; - CHECK(leetcode_1013::canThreePartsEqualSum(input)); -} - -TEST_CASE("test case 2 {test_1013}", "{test_1013}") { - const vector input{3, 3, 6, 5, -2, 2, 5, 1, -9, 4}; - CHECK(leetcode_1013::canThreePartsEqualSum(input)); -} - -TEST_CASE("test case 3 {test_1013}", "{test_1013}") { - const vector input{0, 2, 1, -6, 6, -7, 9, 1, 2, 0, 1}; - CHECK(leetcode_1013::canThreePartsEqualSum(input)); -} - -TEST_CASE("test case 4 {test_1013}", "{test_1013}") { - const vector input{0, 2, 1, -6, 6, 7, 9, -1, 2, 0, 1}; - CHECK_FALSE(leetcode_1013::canThreePartsEqualSum(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1013_TEST_HPP diff --git a/algorithm/array/leetcode_1020.cpp b/algorithm/array/leetcode_1020.cpp index 8927c3f5..0b1d0813 100644 --- a/algorithm/array/leetcode_1020.cpp +++ b/algorithm/array/leetcode_1020.cpp @@ -1,67 +1,76 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1020_test.hpp" +#include +#include +#include namespace leetcode_1020 { -void visit(const vector> &grid, vector> &visited, size_t row, size_t col) { - const auto judge = [& grid, &visited](size_t r, size_t c) { - return grid[r][c] == 1 && visited[r][c] == 0; - }; - if (!judge(row, col)) { - return; - } - const auto row_size{grid.size()}, col_size{grid.front().size()}; - for (std::vector> now{{row, col}}, next{}; !now.empty(); next.clear()) { - for (const auto &[this_row, this_col]: now) { - visited[this_row][this_col] = 1; - if (this_col > 0 && judge(this_row, this_col - 1)) { - next.emplace_back(this_row, this_col - 1); - } - if (this_row > 0 && judge(this_row - 1, this_col)) { - next.emplace_back(this_row - 1, this_col); - } - if (this_col + 1 < col_size && judge(this_row, this_col + 1)) { - next.emplace_back(this_row, this_col + 1); - } - if (this_row + 1 < row_size && judge(this_row + 1, this_col)) { - next.emplace_back(this_row + 1, this_col); +using std::vector; +using std::size_t; +#endif + +class Solution { +private: + void visit(const vector> &grid, vector> &visited, size_t row, size_t col) { + const auto judge = [& grid, &visited](size_t r, size_t c) { + return grid[r][c] == 1 && visited[r][c] == 0; + }; + if (!judge(row, col)) { + return; + } + const auto row_size{grid.size()}, col_size{grid.front().size()}; + for (std::vector> now{{row, col}}, next{}; !now.empty(); next.clear()) { + for (const auto &[this_row, this_col]: now) { + visited[this_row][this_col] = 1; + if (this_col > 0 && judge(this_row, this_col - 1)) { + next.emplace_back(this_row, this_col - 1); + } + if (this_row > 0 && judge(this_row - 1, this_col)) { + next.emplace_back(this_row - 1, this_col); + } + if (this_col + 1 < col_size && judge(this_row, this_col + 1)) { + next.emplace_back(this_row, this_col + 1); + } + if (this_row + 1 < row_size && judge(this_row + 1, this_col)) { + next.emplace_back(this_row + 1, this_col); + } } + std::swap(now, next); } - std::swap(now, next); } -} -int32_t leetcode_1020::numEnclaves(const vector> &grid) { - if (grid.empty() || grid.front().empty()) { - return 0; - } - const auto row{grid.size()}, col{grid.front().size()}; - vector> visited(row, vector(col, 0)); - int32_t ones{0}; - for (const auto &rows: grid) { - for (const auto &num: rows) { - ones += (num == 1); +public: + int32_t numEnclaves(const vector> &grid) { + if (grid.empty() || grid.front().empty()) { + return 0; } - } - for (size_t i{0}; i < col; ++i) { - visit(grid, visited, 0, i); - visit(grid, visited, row - 1, i); - } - for (size_t i{1}; i + 1 < row; ++i) { - visit(grid, visited, i, 0); - visit(grid, visited, i, col - 1); - } - for (const auto &rows: visited) { - for (const auto &num: rows) { - ones -= (num == 1); + const auto row{grid.size()}, col{grid.front().size()}; + vector> visited(row, vector(col, 0)); + int32_t ones{0}; + for (const auto &rows: grid) { + for (const auto &num: rows) { + ones += (num == 1); + } + } + for (size_t i{0}; i < col; ++i) { + visit(grid, visited, 0, i); + visit(grid, visited, row - 1, i); } + for (size_t i{1}; i + 1 < row; ++i) { + visit(grid, visited, i, 0); + visit(grid, visited, i, col - 1); + } + for (const auto &rows: visited) { + for (const auto &num: rows) { + ones -= (num == 1); + } + } + return ones; } - return ones; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1020_test.hpp b/algorithm/array/leetcode_1020_test.cpp similarity index 74% rename from algorithm/array/leetcode_1020_test.hpp rename to algorithm/array/leetcode_1020_test.cpp index 0f80e3b1..86c68515 100644 --- a/algorithm/array/leetcode_1020_test.hpp +++ b/algorithm/array/leetcode_1020_test.cpp @@ -1,28 +1,18 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag 暴力解法 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1020_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1020_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1020_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1020_TEST_HPP #include -#include -#include -#include + +#include "leetcode_1020.cpp" namespace leetcode_1020 { using std::vector; -struct leetcode_1020 { - static int32_t numEnclaves(const vector> &grid); -}; - TEST_CASE("test case 4 {test_1020}", "{test_1020}") { const vector> input{ {0}, @@ -32,13 +22,15 @@ TEST_CASE("test case 4 {test_1020}", "{test_1020}") { {0} }; static constexpr const auto result{0}; - CHECK(result == leetcode_1020::numEnclaves(input)); + Solution solution; + CHECK(result == solution.numEnclaves(input)); } TEST_CASE("test case 6 {test_1020}", "{test_1020}") { const vector> input{{0, 1, 1, 0, 0}}; static constexpr const auto result{0}; - CHECK(result == leetcode_1020::numEnclaves(input)); + Solution solution; + CHECK(result == solution.numEnclaves(input)); } TEST_CASE("test case 3 {test_1020}", "{test_1020}") { @@ -49,7 +41,8 @@ TEST_CASE("test case 3 {test_1020}", "{test_1020}") { {0, 0, 0, 0}, }; static constexpr const auto result{0}; - CHECK(result == leetcode_1020::numEnclaves(input)); + Solution solution; + CHECK(result == solution.numEnclaves(input)); } TEST_CASE("test case 2 {test_1020}", "{test_1020}") { @@ -60,7 +53,8 @@ TEST_CASE("test case 2 {test_1020}", "{test_1020}") { {0, 0, 1, 0}, }; static constexpr const auto result{0}; - CHECK(result == leetcode_1020::numEnclaves(input)); + Solution solution; + CHECK(result == solution.numEnclaves(input)); } TEST_CASE("test case 1 {test_1020}", "{test_1020}") { @@ -71,7 +65,8 @@ TEST_CASE("test case 1 {test_1020}", "{test_1020}") { {0, 0, 0, 0}, }; static constexpr const auto result{3}; - CHECK(result == leetcode_1020::numEnclaves(input)); + Solution solution; + CHECK(result == solution.numEnclaves(input)); } TEST_CASE("test case 5 {test_1020}", "{test_1020}") { @@ -86,8 +81,9 @@ TEST_CASE("test case 5 {test_1020}", "{test_1020}") { {1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0}, {1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1}}; static constexpr const auto result{7}; - CHECK(result == leetcode_1020::numEnclaves(input)); + Solution solution; + CHECK(result == solution.numEnclaves(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1020_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1020_TEST_HPP diff --git a/algorithm/array/leetcode_1030.cpp b/algorithm/array/leetcode_1030.cpp index 12d03e7d..c310b318 100644 --- a/algorithm/array/leetcode_1030.cpp +++ b/algorithm/array/leetcode_1030.cpp @@ -1,68 +1,72 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1030_test.hpp" +#include +#include +#include namespace leetcode_1030 { +using std::vector; +#endif -vector> -leetcode_1030::allCellsDistOrder(int32_t rows, int32_t cols, int32_t rCenter, int32_t cCenter) { - const auto distance = [rCenter, cCenter](int32_t x, int32_t y) { - return std::abs(rCenter - x) + std::abs(cCenter - y); - }; - const auto max_distance = std::max( - {distance(0, 0), distance(0, cols - 1), distance(rows - 1, 0), distance(rows - 1, cols - 1)} - ); - vector> will_return{{rCenter, cCenter}}; - const auto in = [rows, cols, &will_return](int32_t x, int32_t y) { - const auto judge = (0 <= x && x < rows) && (0 <= y && y < cols); - if (judge) { - will_return.push_back({x, y}); - } - }; - for (int32_t i{1}; i <= max_distance; ++i) { - in(rCenter, cCenter + i); - in(rCenter, cCenter - i); - for (int32_t j{1}; j < i; ++j) { - const auto row{j}, col{i - j}; - in(rCenter + row, cCenter + col); - in(rCenter + row, cCenter - col); - in(rCenter - row, cCenter + col); - in(rCenter - row, cCenter - col); +class Solution { +public: + vector> allCellsDistOrder(int32_t rows, int32_t cols, int32_t rCenter, int32_t cCenter) { + const auto distance = [rCenter, cCenter](int32_t x, int32_t y) { + return std::abs(rCenter - x) + std::abs(cCenter - y); + }; + const auto max_distance = std::max( + {distance(0, 0), distance(0, cols - 1), distance(rows - 1, 0), distance(rows - 1, cols - 1)} + ); + vector> will_return{{rCenter, cCenter}}; + const auto in = [rows, cols, &will_return](int32_t x, int32_t y) { + const auto judge = (0 <= x && x < rows) && (0 <= y && y < cols); + if (judge) { + will_return.push_back({x, y}); + } + }; + for (int32_t i{1}; i <= max_distance; ++i) { + in(rCenter, cCenter + i); + in(rCenter, cCenter - i); + for (int32_t j{1}; j < i; ++j) { + const auto row{j}, col{i - j}; + in(rCenter + row, cCenter + col); + in(rCenter + row, cCenter - col); + in(rCenter - row, cCenter + col); + in(rCenter - row, cCenter - col); + } + in(rCenter + i, cCenter); + in(rCenter - i, cCenter); } - in(rCenter + i, cCenter); - in(rCenter - i, cCenter); + return will_return; } - return will_return; -} -vector> -leetcode_1030::allCellsDistOrderNLogN(int32_t rows, int32_t cols, int32_t rCenter, int32_t cCenter) { - struct point final { - int32_t x{0}, y{0}; + vector> allCellsDistOrderNLogN(int32_t rows, int32_t cols, int32_t rCenter, int32_t cCenter) { + struct point final { + int32_t x{0}, y{0}; - point(int32_t x, int32_t y) : x(x), y(y) {}; + point(int32_t x, int32_t y) : x(x), y(y) {}; - bool operator<(const point &p) const { - return abs(x) + abs(y) < abs(p.x) + abs(p.y); + bool operator<(const point &p) const { + return abs(x) + abs(y) < abs(p.x) + abs(p.y); + } + }; + vector pois; + vector> willreturn; + for (int32_t i{0}; i < rows; i++) { + for (int32_t j{0}; j < cols; j++) { + pois.emplace_back(i - rCenter, j - cCenter); + } } - }; - vector pois; - vector> willreturn; - for (int32_t i{0}; i < rows; i++) { - for (int32_t j{0}; j < cols; j++) { - pois.emplace_back(i - rCenter, j - cCenter); + sort(pois.begin(), pois.end(), std::less()); + for (size_t i{0}; i < pois.size(); i++) { + willreturn.emplace_back(vector{pois[i].x + rCenter, pois[i].y + cCenter}); } + return willreturn; } - sort(pois.begin(), pois.end(), std::less()); - for (size_t i{0}; i < pois.size(); i++) { - willreturn.emplace_back(vector{pois[i].x + rCenter, pois[i].y + cCenter}); - } - return willreturn; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1030_test.hpp b/algorithm/array/leetcode_1030_test.cpp similarity index 62% rename from algorithm/array/leetcode_1030_test.hpp rename to algorithm/array/leetcode_1030_test.cpp index c62128d0..cef046c6 100644 --- a/algorithm/array/leetcode_1030_test.hpp +++ b/algorithm/array/leetcode_1030_test.cpp @@ -1,31 +1,21 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag 排序 //@Tag 模拟 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1030_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1030_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1030_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1030_TEST_HPP #include #include #include #include +#include "leetcode_1030.cpp" namespace leetcode_1030 { using std::vector; -struct leetcode_1030 { - static vector> allCellsDistOrder(int32_t rows, int32_t cols, int32_t rCenter, int32_t cCenter); - - static vector> allCellsDistOrderNLogN(int32_t rows, int32_t cols, int32_t rCenter, int32_t cCenter); -}; - bool check(const vector> &input, int32_t rCenter, int32_t cCenter) { vector test{}; for (const auto &point: input) { @@ -36,58 +26,66 @@ bool check(const vector> &input, int32_t rCenter, int32_t cCente TEST_CASE("test case 3-2 {test_1030}", "{test_1030}") { static constexpr const auto rows{2}, cols{3}, rCenter{1}, cCenter{2}; - const vector> result{leetcode_1030::allCellsDistOrder(rows, cols, rCenter, cCenter)}; + Solution solution; + const vector> result{solution.allCellsDistOrder(rows, cols, rCenter, cCenter)}; CHECK(check(result, rCenter, cCenter)); CHECK(result.size() == rows * cols); } TEST_CASE("test case 3-1 {test_1030}", "{test_1030}") { static constexpr const auto rows{2}, cols{3}, rCenter{1}, cCenter{2}; - const vector> result{leetcode_1030::allCellsDistOrderNLogN(rows, cols, rCenter, cCenter)}; + Solution solution; + const vector> result{solution.allCellsDistOrderNLogN(rows, cols, rCenter, cCenter)}; CHECK(check(result, rCenter, cCenter)); CHECK(result.size() == rows * cols); } TEST_CASE("test case 2-2 {test_1030}", "{test_1030}") { static constexpr const auto rows{2}, cols{2}, rCenter{0}, cCenter{1}; - const vector> result{leetcode_1030::allCellsDistOrder(rows, cols, rCenter, cCenter)}; + Solution solution; + const vector> result{solution.allCellsDistOrder(rows, cols, rCenter, cCenter)}; CHECK(check(result, rCenter, cCenter)); CHECK(result.size() == rows * cols); } TEST_CASE("test case 2-1 {test_1030}", "{test_1030}") { static constexpr const auto rows{2}, cols{2}, rCenter{0}, cCenter{1}; - const vector> result{leetcode_1030::allCellsDistOrderNLogN(rows, cols, rCenter, cCenter)}; + Solution solution; + const vector> result{solution.allCellsDistOrderNLogN(rows, cols, rCenter, cCenter)}; CHECK(check(result, rCenter, cCenter)); CHECK(result.size() == rows * cols); } TEST_CASE("test case 1-2 {test_1030}", "{test_1030}") { static constexpr const auto rows{1}, cols{2}, rCenter{0}, cCenter{0}; - const vector> result{leetcode_1030::allCellsDistOrder(rows, cols, rCenter, cCenter)}; + Solution solution; + const vector> result{solution.allCellsDistOrder(rows, cols, rCenter, cCenter)}; CHECK(check(result, rCenter, cCenter)); CHECK(result.size() == rows * cols); } TEST_CASE("test case 1-1 {test_1030}", "{test_1030}") { static constexpr const auto rows{1}, cols{2}, rCenter{0}, cCenter{0}; - const vector> result{leetcode_1030::allCellsDistOrderNLogN(rows, cols, rCenter, cCenter)}; + Solution solution; + const vector> result{solution.allCellsDistOrderNLogN(rows, cols, rCenter, cCenter)}; CHECK(check(result, rCenter, cCenter)); CHECK(result.size() == rows * cols); } TEST_CASE("test case 4-2 {test_1030}", "{test_1030}") { static constexpr const auto rows{11}, cols{45}, rCenter{1}, cCenter{4}; - const vector> result{leetcode_1030::allCellsDistOrder(rows, cols, rCenter, cCenter)}; + Solution solution; + const vector> result{solution.allCellsDistOrder(rows, cols, rCenter, cCenter)}; CHECK(check(result, rCenter, cCenter)); CHECK(result.size() == rows * cols); } TEST_CASE("test case 4-1 {test_1030}", "{test_1030}") { static constexpr const auto rows{11}, cols{45}, rCenter{1}, cCenter{4}; - const vector> result{leetcode_1030::allCellsDistOrderNLogN(rows, cols, rCenter, cCenter)}; + Solution solution; + const vector> result{solution.allCellsDistOrderNLogN(rows, cols, rCenter, cCenter)}; CHECK(check(result, rCenter, cCenter)); CHECK(result.size() == rows * cols); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1030_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1030_TEST_HPP diff --git a/algorithm/array/leetcode_1051.cpp b/algorithm/array/leetcode_1051.cpp index 41985654..b57fa011 100644 --- a/algorithm/array/leetcode_1051.cpp +++ b/algorithm/array/leetcode_1051.cpp @@ -1,43 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1051_test.hpp" +#include #include namespace leetcode_1051 { +using std::vector; +#endif -int32_t leetcode_1051::heightChecker(const vector &heights) { - vector sorted{heights}; - std::sort(sorted.begin(), sorted.end()); - int32_t count{0}; - for (size_t i{0}; i < heights.size(); ++i) { - if (sorted[i] != heights[i]) { - count++; +class Solution { +public: + int32_t heightChecker(const vector &heights) { + vector sorted{heights}; + std::sort(sorted.begin(), sorted.end()); + int32_t count{0}; + for (size_t i{0}; i < heights.size(); ++i) { + if (sorted[i] != heights[i]) { + count++; + } } + return count; // because the size smaller than 100 } - return count; // because the size smaller than 100 -} -int leetcode_1051::heightCheckerSmall(const vector &heights) { - const auto h_size{128}; - vector sizes(128, 0); - for (const auto height: heights) { - sizes[height] += 1; - } - int32_t will_return{0}; - for (int32_t j{0}, loca{0}; j < h_size; ++j) { - for (int32_t i{0}; i < sizes[j]; ++i) { - if (j != heights[loca]) { - will_return += 1; + int32_t heightCheckerSmall(const vector &heights) { + const auto h_size{128}; + vector sizes(128, 0); + for (const auto height: heights) { + sizes[height] += 1; + } + int32_t will_return{0}; + for (int32_t j{0}, loca{0}; j < h_size; ++j) { + for (int32_t i{0}; i < sizes[j]; ++i) { + if (j != heights[loca]) { + will_return += 1; + } + loca += 1; } - loca += 1; } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1051_test.hpp b/algorithm/array/leetcode_1051_test.cpp similarity index 60% rename from algorithm/array/leetcode_1051_test.hpp rename to algorithm/array/leetcode_1051_test.cpp index b31abff4..09842ba4 100644 --- a/algorithm/array/leetcode_1051_test.hpp +++ b/algorithm/array/leetcode_1051_test.cpp @@ -1,44 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag 排序 //@Tag 小规模数据集 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1051_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1051_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1051_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1051_TEST_HPP #include #include #include #include +#include "leetcode_1051.cpp" namespace leetcode_1051 { using std::vector; -struct leetcode_1051 final { - static int heightChecker(const vector &heights); - - static int heightCheckerSmall(const vector &heights); -}; - - TEST_CASE("test case 1-1 {test_1051}", "{test_1051}") { const vector input{1, 1, 4, 5, 1, 4}; static constexpr const auto result{4}; - CHECK(result == leetcode_1051::heightChecker(input)); - CHECK(result == leetcode_1051::heightCheckerSmall(input)); + Solution solution; + CHECK(result == solution.heightChecker(input)); + CHECK(result == solution.heightCheckerSmall(input)); } TEST_CASE("test case 1-2 {test_1051}", "{test_1051}") { const vector input{5, 1, 2, 3, 4}; static constexpr const auto result{5}; - CHECK(result == leetcode_1051::heightChecker(input)); - CHECK(result == leetcode_1051::heightCheckerSmall(input)); + Solution solution; + CHECK(result == solution.heightChecker(input)); + CHECK(result == solution.heightCheckerSmall(input)); } TEST_CASE("test case 1-3 {test_1051}", "{test_1051}") { @@ -48,9 +39,10 @@ TEST_CASE("test case 1-3 {test_1051}", "{test_1051}") { 67, 28, 81, 84, 76, 88, 45, 42, 54, 59, 56, 20, 6, 56, 51, 72, 69, 6, 48, 67, 68, 6, 10, 93, 69, 4, 29, 28}; static constexpr const auto result{95}; - CHECK(result == leetcode_1051::heightChecker(input)); - CHECK(result == leetcode_1051::heightCheckerSmall(input)); + Solution solution; + CHECK(result == solution.heightChecker(input)); + CHECK(result == solution.heightCheckerSmall(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1051_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1051_TEST_HPP diff --git a/algorithm/array/leetcode_1089.cpp b/algorithm/array/leetcode_1089.cpp index b230cff5..590c144e 100644 --- a/algorithm/array/leetcode_1089.cpp +++ b/algorithm/array/leetcode_1089.cpp @@ -1,36 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1089_test.hpp" +#include #include namespace leetcode_1089 { +using std::vector; +#endif -void leetcode_1089::duplicateZeros(vector &arr) { - const auto arr_size{arr.size()}; - size_t left_pointer{0}, right_pointer{0}; - for (; left_pointer < arr_size && right_pointer < arr_size; left_pointer += 1, right_pointer += 1) { - if (arr[left_pointer] == 0) { - right_pointer += 1; - } - }// 先进行一次模拟step by step,之后反演 - // 不能只从左向右扫描0的个数,可能前面的会把后面的给"顶"出去 - for (; left_pointer > 0 && right_pointer > 0; left_pointer -= 1, right_pointer -= 1) { - const auto left_number{arr[left_pointer - 1]}; - if (left_number != 0) { - arr[right_pointer - 1] = arr[left_pointer - 1]; - } else { - right_pointer -= 1; - if (right_pointer < arr_size) [[unlikely]] { // max once - arr[right_pointer] = 0; +class Solution { +public: + void duplicateZeros(vector &arr) { + const auto arr_size{arr.size()}; + size_t left_pointer{0}, right_pointer{0}; + for (; left_pointer < arr_size && right_pointer < arr_size; left_pointer += 1, right_pointer += 1) { + if (arr[left_pointer] == 0) { + right_pointer += 1; + } + }// 先进行一次模拟step by step,之后反演 + // 不能只从左向右扫描0的个数,可能前面的会把后面的给"顶"出去 + for (; left_pointer > 0 && right_pointer > 0; left_pointer -= 1, right_pointer -= 1) { + const auto left_number{arr[left_pointer - 1]}; + if (left_number != 0) { + arr[right_pointer - 1] = arr[left_pointer - 1]; + } else { + right_pointer -= 1; + if (right_pointer < arr_size) [[unlikely]] { // max once + arr[right_pointer] = 0; + } + arr[right_pointer - 1] = 0; } - arr[right_pointer - 1] = 0; } } -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1089_test.hpp b/algorithm/array/leetcode_1089_test.cpp similarity index 51% rename from algorithm/array/leetcode_1089_test.hpp rename to algorithm/array/leetcode_1089_test.cpp index b80d9351..8229afcc 100644 --- a/algorithm/array/leetcode_1089_test.hpp +++ b/algorithm/array/leetcode_1089_test.cpp @@ -1,64 +1,57 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag 反演 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1089_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1089_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1089_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1089_TEST_HPP #include #include #include #include +#include "leetcode_1089.cpp" namespace leetcode_1089 { using std::vector; -struct leetcode_1089 final { - static void duplicateZeros(vector &arr); - - static vector duplicateZerosConst(const vector &arr) { - vector will_return{arr}; - duplicateZeros(will_return); - return will_return; - } -}; +vector duplicateZerosConst(const vector &arr) { + vector will_return{arr}; + Solution solution; + solution.duplicateZeros(will_return); + return will_return; +} using Catch::Matchers::Equals; TEST_CASE("test case 1-1 {test_1089}", "{test_1089}") { const vector input{1, 1, 4, 5, 1, 4}; const vector result{1, 1, 4, 5, 1, 4}; - CHECK_THAT(result, Equals(leetcode_1089::duplicateZerosConst(input))); + CHECK_THAT(result, Equals(duplicateZerosConst(input))); } TEST_CASE("test case 1-2 {test_1089}", "{test_1089}") { const vector input{1, 0, 2, 0, 3, 4, 0}; const vector result{1, 0, 0, 2, 0, 0, 3}; - CHECK_THAT(result, Equals(leetcode_1089::duplicateZerosConst(input))); + CHECK_THAT(result, Equals(duplicateZerosConst(input))); } TEST_CASE("test case 1-3 {test_1089}", "{test_1089}") { const vector input{1, 9, 1, 9, 8, 1, 0}; const vector result{1, 9, 1, 9, 8, 1, 0}; - CHECK_THAT(result, Equals(leetcode_1089::duplicateZerosConst(input))); + CHECK_THAT(result, Equals(duplicateZerosConst(input))); } TEST_CASE("test case 1-4 {test_1089}", "{test_1089}") { const vector input{8, 5, 0, 9, 0, 3, 4, 7}; const vector result{8, 5, 0, 0, 9, 0, 0, 3}; - CHECK_THAT(result, Equals(leetcode_1089::duplicateZerosConst(input))); + CHECK_THAT(result, Equals(duplicateZerosConst(input))); } TEST_CASE("test case 1-5 {test_1089}", "{test_1089}") { - const vector input{0, 1, 7, 6, 0, 2, 0,7}; + const vector input{0, 1, 7, 6, 0, 2, 0, 7}; const vector result{0, 0, 1, 7, 6, 0, 0, 2}; - CHECK_THAT(result, Equals(leetcode_1089::duplicateZerosConst(input))); + CHECK_THAT(result, Equals(duplicateZerosConst(input))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1089_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1089_TEST_HPP diff --git a/algorithm/array/leetcode_11.cpp b/algorithm/array/leetcode_11.cpp index 2110e788..d816844e 100644 --- a/algorithm/array/leetcode_11.cpp +++ b/algorithm/array/leetcode_11.cpp @@ -1,30 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_11_test.hpp" +#include +#include +#include namespace leetcode_11 { +using std::vector; +#endif -int leetcode_11::maxArea(const vector &height) { - int32_t left{0}, - right = static_cast(height.size() - 1); - const auto water = [& height](const auto lhs, const auto rhs) { - return (rhs - lhs) * std::min(height[lhs], height[rhs]); - }; - int32_t will_return = water(left, right); - while (left < right) { - if (height[left] >= height[right]) { - right--; - } else { - left++; +class Solution { +public: + int32_t maxArea(const vector &height) { + int32_t left{0}, + right = static_cast(height.size() - 1); + const auto water = [&height](const auto lhs, const auto rhs) { + return (rhs - lhs) * std::min(height[lhs], height[rhs]); + }; + int32_t will_return = water(left, right); + while (left < right) { + if (height[left] >= height[right]) { + right--; + } else { + left++; + } + will_return = std::max(will_return, water(left, right)); } - will_return = std::max(will_return, water(left, right)); + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1108.cpp b/algorithm/array/leetcode_1108.cpp index 4a6cab24..d4773ec7 100644 --- a/algorithm/array/leetcode_1108.cpp +++ b/algorithm/array/leetcode_1108.cpp @@ -1,42 +1,48 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1108_test.hpp" +#include +#include namespace leetcode_1108 { +using std::string; +#endif -string leetcode_1108::defangIPaddr(const string &address) { - const int8_t add_size{static_cast(address.size())}; - string will_return(add_size + 6, ' '); - std::array position{-1, 0, 0, 0, add_size}; - // .255.100.50.0. - for (int8_t i{0}, cnt{1}; i < add_size; ++i) { - if (address[i] == '.') { - position[cnt] = i; - cnt++; +class Solution { +public: + string defangIPaddr(const string &address) { + const int32_t add_size{static_cast(address.size())}; + string will_return(add_size + 6, ' '); + std::array position{-1, 0, 0, 0, add_size}; + // .255.100.50.0. + for (int32_t i{0}, cnt{1}; i < add_size; ++i) { + if (address[i] == '.') { + position[cnt] = i; + cnt++; + } } - } - auto iter = will_return.begin(); - for (size_t i{0}; i < 3; ++i) { - for (int8_t j = position[i] + static_cast(1); j < position[i + 1]; ++j) { + auto iter = will_return.begin(); + for (size_t i{0}; i < 3; ++i) { + for (int32_t j = position[i] + static_cast(1); j < position[i + 1]; ++j) { + (*iter) = address[j]; + ++iter; + } + (*iter) = '['; + ++iter; + (*iter) = '.'; + ++iter; + (*iter) = ']'; + ++iter; + } + for (int32_t j = position[3] + static_cast(1); j < position[4]; ++j) { (*iter) = address[j]; ++iter; } - (*iter) = '['; - ++iter; - (*iter) = '.'; - ++iter; - (*iter) = ']'; - ++iter; - } - for (int8_t j = position[3] + static_cast(1); j < position[4]; ++j) { - (*iter) = address[j]; - ++iter; + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1108_test.hpp b/algorithm/array/leetcode_1108_test.cpp similarity index 57% rename from algorithm/array/leetcode_1108_test.hpp rename to algorithm/array/leetcode_1108_test.cpp index 2cc8d0f6..d4d1c2ce 100644 --- a/algorithm/array/leetcode_1108_test.hpp +++ b/algorithm/array/leetcode_1108_test.cpp @@ -1,41 +1,38 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1108_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1108_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1108_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1108_TEST_HPP #include #include #include +#include +#include "leetcode_1108.cpp" namespace leetcode_1108 { - -struct leetcode_1108 final { - static string defangIPaddr(const string &address); -}; +using std::string; TEST_CASE("test case 1-1 {test_1108}", "{test_1108}") { static constexpr const char *const input{"1.1.1.1"}; static constexpr const char *const result{"1[.]1[.]1[.]1"}; - CHECK(result == leetcode_1108::defangIPaddr(input)); + Solution solution; + CHECK(result == solution.defangIPaddr(input)); } TEST_CASE("test case 1-2 {test_1108}", "{test_1108}") { static constexpr const char *const input{"255.100.50.0"}; static constexpr const char *const result{"255[.]100[.]50[.]0"}; - CHECK(result == leetcode_1108::defangIPaddr(input)); + Solution solution; + CHECK(result == solution.defangIPaddr(input)); } TEST_CASE("test case 1-3 {test_1108}", "{test_1108}") { static constexpr const char *const input{"114.141.91.8"}; static constexpr const char *const result{"114[.]141[.]91[.]8"}; - CHECK(result == leetcode_1108::defangIPaddr(input)); + Solution solution; + CHECK(result == solution.defangIPaddr(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1108_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1108_TEST_HPP diff --git a/algorithm/array/leetcode_1170.cpp b/algorithm/array/leetcode_1170.cpp index a3cffd4e..7414453e 100644 --- a/algorithm/array/leetcode_1170.cpp +++ b/algorithm/array/leetcode_1170.cpp @@ -1,46 +1,52 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1170_test.hpp" +#include +#include #include namespace leetcode_1170 { +using std::vector; +using std::string; using std::array; +#endif -vector leetcode_1170::numSmallerByFrequency(const vector &queries, const vector &words) { - static const auto minFunc = [](const string &word) { - std::array chars{0}; - for (const auto ch: word) { - chars[ch - 'a'] += 1; - } - for (size_t i{0}; i < 26; ++i) { - if (chars[i] != 0) { - return chars[i]; +class Solution { +public: + vector numSmallerByFrequency(const vector &queries, const vector &words) { + static const auto minFunc = [](const string &word) { + std::array chars{0}; + for (const auto ch: word) { + chars[ch - 'a'] += 1; } + for (size_t i{0}; i < 26; ++i) { + if (chars[i] != 0) { + return chars[i]; + } + } + return 0; + }; + vector nums(12, 0); + for (const auto &word: words) { + const auto minV = minFunc(word); + nums[minV]++; } - return 0; - }; - vector nums(12, 0); - for (const auto &word: words) { - const auto minV = minFunc(word); - nums[minV]++; - } - for (size_t i{1}; i < 12; ++i) { - nums[i] = nums[i] + nums[i - 1]; - } - vector will_return{}; - const auto words_size{words.size()}; - will_return.reserve(queries.size()); - for (const auto &query: queries) { - const auto minV = minFunc(query); - const auto value = nums[minV]; - will_return.push_back(words_size - value); + for (size_t i{1}; i < 12; ++i) { + nums[i] = nums[i] + nums[i - 1]; + } + vector will_return{}; + const auto words_size{words.size()}; + will_return.reserve(queries.size()); + for (const auto &query: queries) { + const auto minV = minFunc(query); + const auto value = nums[minV]; + will_return.push_back(words_size - value); + } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1170_test.hpp b/algorithm/array/leetcode_1170_test.cpp similarity index 67% rename from algorithm/array/leetcode_1170_test.hpp rename to algorithm/array/leetcode_1170_test.cpp index 7fb8abd0..b7fd3161 100644 --- a/algorithm/array/leetcode_1170_test.hpp +++ b/algorithm/array/leetcode_1170_test.cpp @@ -1,43 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1170_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1170_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1170_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1170_TEST_HPP #include #include #include #include #include +#include "leetcode_1170.cpp" namespace leetcode_1170 { using std::vector; using std::string; -struct leetcode_1170 final { - static vector numSmallerByFrequency(const vector &queries, const vector &words); -}; - using Catch::Matchers::Equals; TEST_CASE("test case 1-1 {test_1170}", "{test_1170}") { const vector queries{"cbd"}; const vector words{"tencent"}; const vector output{0}; - CHECK_THAT(output, Equals(leetcode_1170::numSmallerByFrequency(queries, words))); + Solution solution; + CHECK_THAT(output, Equals(solution.numSmallerByFrequency(queries, words))); } TEST_CASE("test case 1-2 {test_1170}", "{test_1170}") { const vector queries{"bbb", "cc"}; const vector words{"a", "aa", "aaa", "aaaa"}; const vector output{1, 2}; - CHECK_THAT(output, Equals(leetcode_1170::numSmallerByFrequency(queries, words))); + Solution solution; + CHECK_THAT(output, Equals(solution.numSmallerByFrequency(queries, words))); } TEST_CASE("test case 1-3 {test_1170}", "{test_1170}") { @@ -46,7 +40,8 @@ TEST_CASE("test case 1-3 {test_1170}", "{test_1170}") { const vector words{"aaabbb", "aab", "babbab", "babbbb", "b", "bbbbbbbbab", "a", "bbbbbbbbbb", "baaabbaab", "aa"}; const vector output{6, 1, 1, 2, 3, 3, 3, 1, 3, 2}; - CHECK_THAT(output, Equals(leetcode_1170::numSmallerByFrequency(queries, words))); + Solution solution; + CHECK_THAT(output, Equals(solution.numSmallerByFrequency(queries, words))); } TEST_CASE("test case 1-4 {test_1170}", "{test_1170}") { @@ -55,7 +50,8 @@ TEST_CASE("test case 1-4 {test_1170}", "{test_1170}") { const vector words{"b", "aaaba", "aaaabba", "aa", "aabaabab", "aabbaaabbb", "ababb", "bbb", "aabbbabb", "aab", "bbaaababba", "baaaaa"}; const vector output{6, 5, 0, 6, 11, 11, 11, 8, 11, 0, 6, 6}; - CHECK_THAT(output, Equals(leetcode_1170::numSmallerByFrequency(queries, words))); + Solution solution; + CHECK_THAT(output, Equals(solution.numSmallerByFrequency(queries, words))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1170_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1170_TEST_HPP diff --git a/algorithm/array/leetcode_1184.cpp b/algorithm/array/leetcode_1184.cpp index 95a3b55a..abf50ffd 100644 --- a/algorithm/array/leetcode_1184.cpp +++ b/algorithm/array/leetcode_1184.cpp @@ -1,31 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1184_test.hpp" +#include +#include namespace leetcode_1184 { +using std::vector; +#endif -int32_t leetcode_1184::distanceBetweenBusStops(const vector &distance, int32_t start, int32_t destination) { - if (start > destination) { - return distanceBetweenBusStops(distance, destination, start); - } - int32_t value1{0}, value2{0}; - const auto max_range{distance.size()}; - for (int32_t i{start}; i < destination; ++i) { - value1 += distance[i]; - } - for (size_t i = destination; i < max_range; ++i) { - value2 += distance[i]; +class Solution { +public: + int32_t distanceBetweenBusStops(const vector &distance, int32_t start, int32_t destination) { + if (start > destination) { + return distanceBetweenBusStops(distance, destination, start); + } + int32_t value1{0}, value2{0}; + const auto max_range{distance.size()}; + for (int32_t i{start}; i < destination; ++i) { + value1 += distance[i]; + } + for (size_t i = destination; i < max_range; ++i) { + value2 += distance[i]; + } + for (int32_t i{0}; i < start; ++i) { + value2 += distance[i]; + } + return std::min(value1, value2); } - for (int32_t i{0}; i < start; ++i) { - value2 += distance[i]; - } - return std::min(value1, value2); -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1184_test.hpp b/algorithm/array/leetcode_1184_test.cpp similarity index 56% rename from algorithm/array/leetcode_1184_test.hpp rename to algorithm/array/leetcode_1184_test.cpp index 4eb1dd68..6666465c 100644 --- a/algorithm/array/leetcode_1184_test.hpp +++ b/algorithm/array/leetcode_1184_test.cpp @@ -1,49 +1,44 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1184_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1184_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1184_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1184_TEST_HPP #include #include #include #include #include +#include "leetcode_1184.cpp" namespace leetcode_1184 { using std::vector; using std::string; -struct leetcode_1184 final { - static int32_t distanceBetweenBusStops(const vector &distance, int32_t start, int32_t destination); -}; - TEST_CASE("test case 1-1 {test_1184}", "{test_1184}") { const vector distance{1, 2, 3, 4}; static constexpr const auto from{0}, to{1}; static constexpr const auto result{1}; - CHECK(result == leetcode_1184::distanceBetweenBusStops(distance, from, to)); + Solution solution; + CHECK(result == solution.distanceBetweenBusStops(distance, from, to)); } TEST_CASE("test case 1-2 {test_1184}", "{test_1184}") { const vector distance{2, 2, 2, 2, 2}; static constexpr const auto from{0}, to{2}; static constexpr const auto result{4}; - CHECK(result == leetcode_1184::distanceBetweenBusStops(distance, from, to)); + Solution solution; + CHECK(result == solution.distanceBetweenBusStops(distance, from, to)); } TEST_CASE("test case 1-3 {test_1184}", "{test_1184}") { const vector distance{0, 0, 0, 0, 1}; static constexpr const auto from{0}, to{4}; static constexpr const auto result{0}; - CHECK(result == leetcode_1184::distanceBetweenBusStops(distance, from, to)); + Solution solution; + CHECK(result == solution.distanceBetweenBusStops(distance, from, to)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1184_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1184_TEST_HPP diff --git a/algorithm/array/leetcode_11_test.hpp b/algorithm/array/leetcode_11_test.cpp similarity index 67% rename from algorithm/array/leetcode_11_test.hpp rename to algorithm/array/leetcode_11_test.cpp index a5ff8893..8b166e88 100644 --- a/algorithm/array/leetcode_11_test.hpp +++ b/algorithm/array/leetcode_11_test.cpp @@ -1,36 +1,27 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_11_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_11_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_11_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_11_TEST_HPP +#include "leetcode_11.cpp" #include -#include -#include -#include namespace leetcode_11 { using std::vector; -struct leetcode_11 { - static int maxArea(const vector &height); -}; - TEST_CASE("test case 1 [test_11]", "[test_11]") { const vector vec{1, 8, 6, 2, 5, 4, 8, 3, 7}; - CHECK(leetcode_11::maxArea(vec) == 49); + auto clas = Solution(); + CHECK(clas.maxArea(vec) == 49); } TEST_CASE("test case 2 [test_11]", "[test_11]") { const vector vec{1, 1, 4, 5, 1, 4, 1, 9, 1, 9, 8, 1, 0}; - CHECK(leetcode_11::maxArea(vec) == 35); + auto clas = Solution(); + CHECK(clas.maxArea(vec) == 35); } TEST_CASE("test case 3 [test_11]", "[test_11]") { @@ -40,7 +31,8 @@ TEST_CASE("test case 3 [test_11]", "[test_11]") { 889, 864, 827, 562, 554, 304, 610, 216, 41, 776, 700, 601, 457, 256, 825, 110, 429, 399, 488, 358, 346, 674, 557, 884, 665, 36, 810, 689, 520, 760, 455, 573, 881, 865, 568, 225, 588, 283, 689, 792, 677, 312, 229, 665, 585, 417, 666}; - CHECK(leetcode_11::maxArea(vec) == 74004); + auto clas = Solution(); + CHECK(clas.maxArea(vec) == 74004); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_11_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_11_TEST_HPP diff --git a/algorithm/array/leetcode_1200.cpp b/algorithm/array/leetcode_1200.cpp index 2b8ddabb..3aea14d2 100644 --- a/algorithm/array/leetcode_1200.cpp +++ b/algorithm/array/leetcode_1200.cpp @@ -1,30 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1200_test.hpp" +#include +#include +#include namespace leetcode_1200 { +using std::vector; +#endif -vector> leetcode_1200::minimumAbsDifference(const vector &arr_) { - vector arr{arr_}; - std::sort(arr.begin(), arr.end()); - int32_t minDiff = std::numeric_limits::max() - 1; - vector> will_return{}; - for (auto fst = arr.cbegin(), snd = fst + 1; snd != arr.cend(); ++fst, ++snd) { - const auto diff = (*snd - *fst); - if (minDiff > diff) { - minDiff = diff; - will_return.clear(); - will_return.push_back({*fst, *snd}); - } else if (minDiff == diff) { - will_return.push_back({*fst, *snd}); +class Solution { +public: + vector> minimumAbsDifference(const vector &arr_) { + vector arr{arr_}; + std::sort(arr.begin(), arr.end()); + int32_t minDiff = std::numeric_limits::max() - 1; + vector> will_return{}; + for (auto fst = arr.cbegin(), snd = fst + 1; snd != arr.cend(); ++fst, ++snd) { + const auto diff = (*snd - *fst); + if (minDiff > diff) { + minDiff = diff; + will_return.clear(); + will_return.push_back({*fst, *snd}); + } else if (minDiff == diff) { + will_return.push_back({*fst, *snd}); + } } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1200_test.hpp b/algorithm/array/leetcode_1200_test.cpp similarity index 51% rename from algorithm/array/leetcode_1200_test.hpp rename to algorithm/array/leetcode_1200_test.cpp index 00496be7..ecdb394b 100644 --- a/algorithm/array/leetcode_1200_test.hpp +++ b/algorithm/array/leetcode_1200_test.cpp @@ -1,47 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1200_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1200_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1200_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1200_TEST_HPP #include #include #include #include #include +#include "leetcode_1200.cpp" namespace leetcode_1200 { using std::vector; using std::string; -namespace leetcode_1200 { -vector> minimumAbsDifference(const vector &arr_); -} - using Catch::Matchers::Equals; TEST_CASE("test case 1-1 {test_1200}", "{test_1200}") { const vector distance{1, 4, 5,}; const vector> output{{4, 5}}; - CHECK_THAT(output, Equals(leetcode_1200::minimumAbsDifference(distance))); + Solution solution; + CHECK_THAT(output, Equals(solution.minimumAbsDifference(distance))); } TEST_CASE("test case 1-2 {test_1200}", "{test_1200}") { const vector distance{1, 9, 8, 0}; - const vector> output{{0, 1}, {8, 9}}; - CHECK_THAT(output, Equals(leetcode_1200::minimumAbsDifference(distance))); + const vector> output{{0, 1}, + {8, 9}}; + Solution solution; + CHECK_THAT(output, Equals(solution.minimumAbsDifference(distance))); } TEST_CASE("test case 1-3 {test_1200}", "{test_1200}") { const vector distance{11, 45, 14, 191, 98, 10}; const vector> output{{10, 11}}; - CHECK_THAT(output, Equals(leetcode_1200::minimumAbsDifference(distance))); + Solution solution; + CHECK_THAT(output, Equals(solution.minimumAbsDifference(distance))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1200_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1200_TEST_HPP diff --git a/algorithm/array/leetcode_1217.cpp b/algorithm/array/leetcode_1217.cpp index c4eecdf9..b881e2d2 100644 --- a/algorithm/array/leetcode_1217.cpp +++ b/algorithm/array/leetcode_1217.cpp @@ -1,27 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1217_test.hpp" +#include +#include +#include namespace leetcode_1217 { +using std::vector; +#endif -int32_t leetcode_1217::minCostToMoveChips(const vector &position) { - if (position.empty() || position.size() == 1) { - return 0; - } - int32_t odd{0}, even{0}; - for (const auto num: position) { - if (num % 2 == 0) { - odd++; - } else { - even++; +class Solution { +public: + int minCostToMoveChips(const vector &position) { + if (position.empty() || position.size() == 1) { + return 0; } + int32_t odd{0}, even{0}; + for (const auto num: position) { + if (num % 2 == 0) { + odd++; + } else { + even++; + } + } + return std::min(even, odd); } - return std::min(even, odd); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1217_test.cpp b/algorithm/array/leetcode_1217_test.cpp new file mode 100644 index 00000000..d5f19bbf --- /dev/null +++ b/algorithm/array/leetcode_1217_test.cpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1217_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1217_TEST_HPP + +#include +#include +#include +#include +#include + +#include "leetcode_1217.cpp" + +namespace leetcode_1217 { +using std::vector; +using std::string; + +TEST_CASE("test case 1-1 {test_1217}", "{test_1217}") { + const vector input{1, 4, 5,}; + Solution solution; + const auto output = solution.minCostToMoveChips(input); + constexpr const auto result{1}; + CHECK(result == output); +} + +TEST_CASE("test case 1-2 {test_1217}", "{test_1217}") { + const vector input{1, 2, 3,}; + Solution solution; + const auto output = solution.minCostToMoveChips(input); + constexpr const auto result{1}; + CHECK(result == output); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1217_TEST_HPP diff --git a/algorithm/array/leetcode_1217_test.hpp b/algorithm/array/leetcode_1217_test.hpp deleted file mode 100644 index 2990939b..00000000 --- a/algorithm/array/leetcode_1217_test.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1217_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1217_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_1217 { -using std::vector; -using std::string; - -namespace leetcode_1217 { -int32_t minCostToMoveChips(const vector &position); -} - -TEST_CASE("test case 1-1 {test_1217}", "{test_1217}") { - const vector input{1, 4, 5,}; - const auto output = leetcode_1217::minCostToMoveChips(input); - constexpr const auto result{1}; - CHECK(result == output); -} - -TEST_CASE("test case 1-2 {test_1217}", "{test_1217}") { - const vector input{1, 2, 3,}; - const auto output = leetcode_1217::minCostToMoveChips(input); - constexpr const auto result{1}; - CHECK(result == output); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1217_TEST_HPP diff --git a/algorithm/array/leetcode_1329.cpp b/algorithm/array/leetcode_1329.cpp index cde90a7b..04799f40 100644 --- a/algorithm/array/leetcode_1329.cpp +++ b/algorithm/array/leetcode_1329.cpp @@ -1,13 +1,18 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds +#include +#include +#include +#include +#include -*/ -#include "leetcode_1329_test.hpp" +using std::vector; namespace leetcode_1329 { +#endif + namespace unstable { size_t matrixToLines(const vector> &mat) { @@ -70,11 +75,15 @@ vector> diagonalSort(vector> &mat) { } } -vector> leetcode_1329::diagonalSort(const vector> &mat) { - vector> will_return{mat}; - unstable::diagonalSort(will_return); - return will_return; -} - +class Solution { +public: + vector> diagonalSort(const vector> &mat) { + vector> will_return{mat}; + unstable::diagonalSort(will_return); + return will_return; + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1329_test.cpp b/algorithm/array/leetcode_1329_test.cpp new file mode 100644 index 00000000..db989d59 --- /dev/null +++ b/algorithm/array/leetcode_1329_test.cpp @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1329_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1329_TEST_HPP + +#include +#include +#include +#include +#include + +#include "leetcode_1329.cpp" + +using Catch::Matchers::Equals; + +namespace leetcode_1329 { +using std::vector; +using std::string; + +TEST_CASE("test case 1-1 {test_1329}", "{test_1329}") { + const vector> matrix{ + {5, 1, 4,}, + {1, 1, 4}, + {19, 19, 810,}, + }; + Solution solution; + const auto result = solution.diagonalSort(matrix); + const vector> output{ + {1, 1, 4}, + {1, 5, 4,}, + {19, 19, 810,}, + }; + CHECK_THAT(output, Equals(result)); + +} + +TEST_CASE("test case 1-2 {test_1329}", "{test_1329}") { + const vector> matrix{ + {1, 3, 2,}, + {4, 15, 6,}, + {4, 7, 6}, + }; + Solution solution; + const auto result = solution.diagonalSort(matrix); + const vector> output{ + {1, 3, 2,}, + {4, 6, 6,}, + {4, 7, 15}, + }; + CHECK_THAT(output, Equals(result)); +} + +TEST_CASE("test case 1-3 {test_1329}", "{test_1329}") { + const vector> matrix{{3, 3, 1, 1}, + {2, 2, 1, 2}, + {1, 1, 1, 2}}; + Solution solution; + const auto result = solution.diagonalSort(matrix); + const vector> output{{1, 1, 1, 1}, + {1, 2, 2, 2}, + {1, 2, 3, 3}}; + CHECK_THAT(output, Equals(result)); +} + +TEST_CASE("test case 1-4 {test_1329}", "{test_1329}") { + const vector> matrix{{11, 25, 66, 1, 69, 7}, + {23, 55, 17, 45, 15, 52}, + {75, 31, 36, 44, 58, 8}, + {22, 27, 33, 25, 68, 4}, + {84, 28, 14, 11, 5, 50}}; + Solution solution; + const auto result = solution.diagonalSort(matrix); + const vector> output{{5, 17, 4, 1, 52, 7}, + {11, 11, 25, 45, 8, 69}, + {14, 23, 25, 44, 58, 15}, + {22, 27, 31, 36, 50, 66}, + {84, 28, 75, 33, 55, 68}}; + CHECK_THAT(output, Equals(result)); +} + +TEST_CASE("test case 1-5 {test_1329}", "{test_1329}") { + const vector> matrix{{3, 9}, + {2, 4}, + {1, 2}, + {9, 8}, + {7, 3}}; + Solution solution; + const auto result = solution.diagonalSort(matrix); + const vector> output{{3, 9}, + {2, 4}, + {1, 2}, + {3, 8}, + {7, 9}}; + CHECK_THAT(output, Equals(result)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1329_TEST_HPP diff --git a/algorithm/array/leetcode_1329_test.hpp b/algorithm/array/leetcode_1329_test.hpp deleted file mode 100644 index 21d3c1c4..00000000 --- a/algorithm/array/leetcode_1329_test.hpp +++ /dev/null @@ -1,100 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1329_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1329_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_1329 { -using std::vector; -using std::string; - -namespace leetcode_1329 { -vector> diagonalSort(const vector> &mat); -} -using Catch::Matchers::Equals; -TEST_CASE("test case 1-1 {test_1329}", "{test_1329}") { - const vector> matrix{ - {5, 1, 4,}, - {1, 1, 4}, - {19, 19, 810,}, - }; - const auto result = leetcode_1329::diagonalSort(matrix); - const vector> output{ - {1, 1, 4}, - {1, 5, 4,}, - {19, 19, 810,}, - }; - CHECK_THAT(output, Equals(result)); - -} - -TEST_CASE("test case 1-2 {test_1329}", "{test_1329}") { - const vector> matrix{ - {1, 3, 2,}, - {4, 15, 6,}, - {4, 7, 6}, - }; - const auto result = leetcode_1329::diagonalSort(matrix); - const vector> output{ - {1, 3, 2,}, - {4, 6, 6,}, - {4, 7, 15}, - }; - CHECK_THAT(output, Equals(result)); -} - -TEST_CASE("test case 1-3 {test_1329}", "{test_1329}") { - const vector> matrix{{3, 3, 1, 1}, - {2, 2, 1, 2}, - {1, 1, 1, 2}}; - const auto result = leetcode_1329::diagonalSort(matrix); - const vector> output{{1, 1, 1, 1}, - {1, 2, 2, 2}, - {1, 2, 3, 3}}; - CHECK_THAT(output, Equals(result)); -} - -TEST_CASE("test case 1-4 {test_1329}", "{test_1329}") { - const vector> matrix{{11, 25, 66, 1, 69, 7}, - {23, 55, 17, 45, 15, 52}, - {75, 31, 36, 44, 58, 8}, - {22, 27, 33, 25, 68, 4}, - {84, 28, 14, 11, 5, 50}}; - const auto result = leetcode_1329::diagonalSort(matrix); - const vector> output{{5, 17, 4, 1, 52, 7}, - {11, 11, 25, 45, 8, 69}, - {14, 23, 25, 44, 58, 15}, - {22, 27, 31, 36, 50, 66}, - {84, 28, 75, 33, 55, 68}};; - CHECK_THAT(output, Equals(result)); -} - -TEST_CASE("test case 1-5 {test_1329}", "{test_1329}") { - const vector> matrix{{3, 9}, - {2, 4}, - {1, 2}, - {9, 8}, - {7, 3}}; - const auto result = leetcode_1329::diagonalSort(matrix); - const vector> output{{3, 9}, - {2, 4}, - {1, 2}, - {3, 8}, - {7, 9}};; - CHECK_THAT(output, Equals(result)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1329_TEST_HPP diff --git a/algorithm/array/leetcode_1360.cpp b/algorithm/array/leetcode_1360.cpp index 00f2668b..c5484daf 100644 --- a/algorithm/array/leetcode_1360.cpp +++ b/algorithm/array/leetcode_1360.cpp @@ -1,15 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1360_test.hpp" #include +#include +#include +#include +#include namespace leetcode_1360 { -namespace leetcode_1360 { +using std::string; +using std::array; +#endif static constexpr const std::array days_of_365{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 365}; static constexpr const std::array days_of_366{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 366}; @@ -21,28 +23,32 @@ std::array year_days(int32_t year) { return days_of_365; } -int32_t daysBetweenDates(const string &date1, const string &date2) { - const auto value = date1.compare(date2); - if (value > 0) { - return daysBetweenDates(date2, date1); - } - const auto yy1{std::stoi(date1.substr(0, 4))}, yy2{std::stoi(date2.substr(0, 4))}; - const auto mm1{std::stoi(date1.substr(5, 7))}, mm2{std::stoi(date2.substr(5, 7))}; - const auto dd1{std::stoi(date1.substr(8, 10))}, dd2{std::stoi(date2.substr(8, 10))}; - const auto days_of_year1{year_days(yy1)}, days_of_year2{year_days(yy2)}; - const auto days_of_begin1{dd1 + std::accumulate(days_of_year1.begin(), days_of_year1.begin() + mm1 - 1, 0)}; - const auto days_of_begin2{dd2 + std::accumulate(days_of_year2.begin(), days_of_year2.begin() + mm2 - 1, 0)}; - const auto days_between_years = [](int32_t begin, int32_t end) { - int32_t will_return{0}; - for (int32_t x{begin}; x < end; x++) { - will_return += year_days(x).back(); +class Solution { +public: + int32_t daysBetweenDates(const string &date1, const string &date2) { + const auto value = date1.compare(date2); + if (value > 0) { + return daysBetweenDates(date2, date1); } - return will_return; - }(yy1, yy2); - const auto days = days_between_years + days_of_begin2 - days_of_begin1; - // 先归零, 统一计算到1月1号有多少天, 然后计算间隔多少year - return days; -} + const auto yy1{std::stoi(date1.substr(0, 4))}, yy2{std::stoi(date2.substr(0, 4))}; + const auto mm1{std::stoi(date1.substr(5, 7))}, mm2{std::stoi(date2.substr(5, 7))}; + const auto dd1{std::stoi(date1.substr(8, 10))}, dd2{std::stoi(date2.substr(8, 10))}; + const auto days_of_year1{year_days(yy1)}, days_of_year2{year_days(yy2)}; + const auto days_of_begin1{dd1 + std::accumulate(days_of_year1.begin(), days_of_year1.begin() + mm1 - 1, 0)}; + const auto days_of_begin2{dd2 + std::accumulate(days_of_year2.begin(), days_of_year2.begin() + mm2 - 1, 0)}; + const auto days_between_years = [](int32_t begin, int32_t end) { + int32_t will_return{0}; + for (int32_t x{begin}; x < end; x++) { + will_return += year_days(x).back(); + } + return will_return; + }(yy1, yy2); + const auto days = days_between_years + days_of_begin2 - days_of_begin1; + // 先归零, 统一计算到1月1号有多少天, 然后计算间隔多少year + return days; + } +}; +#ifdef ALGORITHM_TEST_MACRO } -} +#endif diff --git a/algorithm/array/leetcode_1360_test.cpp b/algorithm/array/leetcode_1360_test.cpp new file mode 100644 index 00000000..5f5bd746 --- /dev/null +++ b/algorithm/array/leetcode_1360_test.cpp @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1360_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1360_TEST_HPP + +#include +#include "leetcode_1360.cpp" + +namespace leetcode_1360 { +using std::vector; +using std::string; + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1-1 {test_1360}", "{test_1360}") { + constexpr const char *const begin{"2019-06-29"}; + constexpr const char *const end{"2019-06-30"}; + constexpr const int value{1}; + Solution solution; + CHECK(value == solution.daysBetweenDates(begin, end)); +} + +TEST_CASE("test case 1-2 {test_1360}", "{test_1360}") { + constexpr const char *const begin{"2020-01-15"}; + constexpr const char *const end{"2019-12-31"}; + constexpr const int value{15}; + Solution solution; + CHECK(value == solution.daysBetweenDates(begin, end)); +} + +TEST_CASE("test case 1-3 {test_1360}", "{test_1360}") { + constexpr const char *const begin{"1971-06-29"}; + constexpr const char *const end{"2010-09-23"}; + constexpr const int value{14331}; + Solution solution; + CHECK(value == solution.daysBetweenDates(begin, end)); +} + +TEST_CASE("test case 1-4 {test_1360}", "{test_1360}") { + constexpr const char *const begin{"2009-08-18"}; + constexpr const char *const end{"2080-08-08"}; + constexpr const int value{25923}; + Solution solution; + CHECK(value == solution.daysBetweenDates(begin, end)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1360_TEST_HPP diff --git a/algorithm/array/leetcode_1360_test.hpp b/algorithm/array/leetcode_1360_test.hpp deleted file mode 100644 index ed3b9179..00000000 --- a/algorithm/array/leetcode_1360_test.hpp +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1360_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1360_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_1360 { -using std::vector; -using std::string; - -namespace leetcode_1360 { -int32_t daysBetweenDates(const string &date1, const string &date2); -} - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1-1 {test_1360}", "{test_1360}") { - constexpr const char *const begin{"2019-06-29"}; - constexpr const char *const end{"2019-06-30"}; - constexpr const int32_t value{1}; - CHECK(value == leetcode_1360::daysBetweenDates(begin, end)); -} - -TEST_CASE("test case 1-2 {test_1360}", "{test_1360}") { - constexpr const char *const begin{"2020-01-15"}; - constexpr const char *const end{"2019-12-31"}; - constexpr const int32_t value{15}; - CHECK(value == leetcode_1360::daysBetweenDates(begin, end)); -} - -TEST_CASE("test case 1-3 {test_1360}", "{test_1360}") { - constexpr const char *const begin{"1971-06-29"}; - constexpr const char *const end{"2010-09-23"}; - constexpr const int32_t value{14331}; - CHECK(value == leetcode_1360::daysBetweenDates(begin, end)); -} - -TEST_CASE("test case 1-4 {test_1360}", "{test_1360}") { - constexpr const char *const begin{"2009-08-18"}; - constexpr const char *const end{"2080-08-08"}; - constexpr const int32_t value{25923}; - CHECK(value == leetcode_1360::daysBetweenDates(begin, end)); -} - - - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1360_TEST_HPP diff --git a/algorithm/array/leetcode_1365.cpp b/algorithm/array/leetcode_1365.cpp index dd1b4d40..78597685 100644 --- a/algorithm/array/leetcode_1365.cpp +++ b/algorithm/array/leetcode_1365.cpp @@ -1,37 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2023 nanoseeds +#include +#include +#include +#include +#include -*/ -#include "leetcode_1365_test.hpp" +using std::vector; namespace leetcode_1365 { +#endif -vector leetcode_1365::smallerNumbersThanCurrent(const vector &nums) { - constexpr const auto max_num{100}; - const auto nums_size{nums.size()}; - for (const auto num: nums) { - assert(num >= 0); - assert(num <= max_num); - } - assert(nums_size >= 2); - assert(nums_size <= 500); - std::array arrs{0,}; - for (const auto num: nums) { - arrs[num] += 1; - } - for (int32_t i{1}; i < max_num + 1; i++) { - arrs[i] = arrs[i] + arrs[i - 1]; - } - vector will_return(nums_size, 0); - for (size_t i{0}; i < nums_size; i++) { - if (nums[i] != 0) { - will_return[i] = arrs[nums[i] - 1]; +class Solution { +public: + vector smallerNumbersThanCurrent(const vector &nums) { + constexpr const auto max_num{100}; + const auto nums_size{nums.size()}; + for (const auto num: nums) { + assert(num >= 0); + assert(num <= max_num); + } + assert(nums_size >= 2); + assert(nums_size <= 500); + std::array arrs{0,}; + for (const auto num: nums) { + arrs[num] += 1; } + for (int32_t i{1}; i < max_num + 1; i++) { + arrs[i] = arrs[i] + arrs[i - 1]; + } + vector will_return(nums_size, 0); + for (size_t i{0}; i < nums_size; i++) { + if (nums[i] != 0) { + will_return[i] = arrs[nums[i] - 1]; + } + } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1365_test.cpp b/algorithm/array/leetcode_1365_test.cpp new file mode 100644 index 00000000..e24cf928 --- /dev/null +++ b/algorithm/array/leetcode_1365_test.cpp @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1365_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1365_TEST_HPP + +#include +#include "leetcode_1365.cpp" + +namespace leetcode_1365 { +using std::vector; + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1-1 {test_1365}", "{test_1365}") { + const vector nums{8, 1, 2, 2, 3}; + const vector result{4, 0, 1, 1, 3}; + Solution solution; + CHECK_THAT(result, Equals(solution.smallerNumbersThanCurrent(nums))); +} + +TEST_CASE("test case 1-2 {test_1365}", "{test_1365}") { + const vector nums{6, 5, 4, 8}; + const vector result{2, 1, 0, 3}; + Solution solution; + CHECK_THAT(result, Equals(solution.smallerNumbersThanCurrent(nums))); +} + +TEST_CASE("test case 1-3 {test_1365}", "{test_1365}") { + const vector nums{7, 7, 7, 7}; + const vector result{0, 0, 0, 0}; + Solution solution; + CHECK_THAT(result, Equals(solution.smallerNumbersThanCurrent(nums))); +} + +TEST_CASE("test case 1-4 {test_1365}", "{test_1365}") { + const vector nums{0, 0, 0, 0}; + const vector result{0, 0, 0, 0}; + Solution solution; + CHECK_THAT(result, Equals(solution.smallerNumbersThanCurrent(nums))); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1365_TEST_HPP diff --git a/algorithm/array/leetcode_1365_test.hpp b/algorithm/array/leetcode_1365_test.hpp deleted file mode 100644 index 3ff2ee68..00000000 --- a/algorithm/array/leetcode_1365_test.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1365_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1365_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_1365 { -using std::vector; - -namespace leetcode_1365 { -vector smallerNumbersThanCurrent(const vector &nums); -} - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1-1 {test_1365}", "{test_1365}") { - const vector nums{8, 1, 2, 2, 3}; - const vector result{4, 0, 1, 1, 3}; - CHECK_THAT(result, Equals(leetcode_1365::smallerNumbersThanCurrent(nums))); -} - -TEST_CASE("test case 1-2 {test_1365}", "{test_1365}") { - const vector nums{6, 5, 4, 8}; - const vector result{2, 1, 0, 3}; - CHECK_THAT(result, Equals(leetcode_1365::smallerNumbersThanCurrent(nums))); -} - -TEST_CASE("test case 1-3 {test_1365}", "{test_1365}") { - const vector nums{7, 7, 7, 7}; - const vector result{0, 0, 0, 0}; - CHECK_THAT(result, Equals(leetcode_1365::smallerNumbersThanCurrent(nums))); -} -TEST_CASE("test case 1-4 {test_1365}", "{test_1365}") { - const vector nums{0, 0, 0, 0}; - const vector result{0, 0, 0, 0}; - CHECK_THAT(result, Equals(leetcode_1365::smallerNumbersThanCurrent(nums))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1365_TEST_HPP diff --git a/algorithm/array/leetcode_1371.cpp b/algorithm/array/leetcode_1371.cpp index c7820b55..48861194 100644 --- a/algorithm/array/leetcode_1371.cpp +++ b/algorithm/array/leetcode_1371.cpp @@ -1,41 +1,51 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2023 nanoseeds +#include +#include +#include +#include +#include -*/ -#include "leetcode_1371_test.hpp" +using std::string; namespace leetcode_1371 { -// 把寻找最长字串的问题, 转化成在[0,i)之间寻找一个点, [0,point), [0,i)上, 元音字母的odd/even相同 -// 经典的把O(N^2)的组合问题 拆分成O(N)的(0,N)之后两者作差 -int32_t leetcode_1371::findTheLongestSubstring(const string &s) { - constexpr const auto chnums{26}; - constexpr const std::array nums{ - 0b1, 0, 0, 0, 0b10, - 0, 0, 0, 0b100, 0, - 0, 0, 0, 0, 0b1000, - 0, 0, 0, 0, 0, - 0b10000, 0, 0, 0, 0, - 0 - }; - constexpr const auto specials{5}; - std::array map{-1,}; // key, even-odd值 - for (size_t i{1}; i < (1 << specials); ++i) { - map[i] = 0x3f3f3f3f; - } - // value latest prefix - int32_t distance{0}; - for (int32_t i{0}, count_num{0}; i < static_cast(s.size()); ++i) { - const auto ch{s[i]}; - count_num ^= (nums[ch - 'a']); - map[count_num] = std::min(map[count_num], i); // 把值赋给最早的 - if (map[count_num] != 0x3f3f3f3f) { - distance = std::max(distance, i - map[count_num]); +#endif + +class Solution { +public: + // 把寻找最长字串的问题, 转化成在[0,i)之间寻找一个点, [0,point), [0,i)上, 元音字母的odd/even相同 + // 经典的把O(N^2)的组合问题 拆分成O(N)的(0,N)之后两者作差 + int32_t findTheLongestSubstring(const string &s) { + constexpr const auto chnums{26}; + constexpr const std::array nums{ + 0b1, 0, 0, 0, 0b10, + 0, 0, 0, 0b100, 0, + 0, 0, 0, 0, 0b1000, + 0, 0, 0, 0, 0, + 0b10000, 0, 0, 0, 0, + 0 + }; + constexpr const auto specials{5}; + std::array map{-1,}; // key, even-odd值 + for (size_t i{1}; i < (1 << specials); ++i) { + map[i] = 0x3f3f3f3f; } + // value latest prefix + int32_t distance{0}; + for (int32_t i{0}, count_num{0}; i < static_cast(s.size()); ++i) { + const auto ch{s[i]}; + count_num ^= (nums[ch - 'a']); + map[count_num] = std::min(map[count_num], i); // 把值赋给最早的 + if (map[count_num] != 0x3f3f3f3f) { + distance = std::max(distance, i - map[count_num]); + } + } + return distance; } - return distance; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1371_test.cpp b/algorithm/array/leetcode_1371_test.cpp new file mode 100644 index 00000000..ab3fbcfd --- /dev/null +++ b/algorithm/array/leetcode_1371_test.cpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1371_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1371_TEST_HPP + +#include +#include +#include +#include +#include + +#include "leetcode_1371.cpp" + +namespace leetcode_1371 { +using std::vector; + +TEST_CASE("test case 1-1 {test_1371}", "{test_1371}") { + constexpr const char *const input{"leetcodeisgreat"}; + constexpr const auto output{5}; + Solution solution; + CHECK(output == solution.findTheLongestSubstring(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1371_TEST_HPP diff --git a/algorithm/array/leetcode_1371_test.hpp b/algorithm/array/leetcode_1371_test.hpp deleted file mode 100644 index 4187378b..00000000 --- a/algorithm/array/leetcode_1371_test.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1371_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1371_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_1371 { -using std::vector; - -namespace leetcode_1371 { -int32_t findTheLongestSubstring(const std::string &s); -} - -TEST_CASE("test case 1-1 {test_1371}", "{test_1371}") { - constexpr const char*const input{"leetcodeisgreat"}; - constexpr const auto output{5}; - CHECK(output == leetcode_1371::findTheLongestSubstring(input)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1371_TEST_HPP diff --git a/algorithm/array/leetcode_1391.cpp b/algorithm/array/leetcode_1391.cpp index 134d7ca3..c4a90107 100644 --- a/algorithm/array/leetcode_1391.cpp +++ b/algorithm/array/leetcode_1391.cpp @@ -1,13 +1,15 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2023 nanoseeds +#include +#include +#include -*/ -#include "leetcode_1391_test.hpp" +using std::vector; -namespace leetcode_1371 { +namespace leetcode_1391 { +#endif enum direction { left_to_right = 1, @@ -18,139 +20,144 @@ enum direction { up_to_right = 6, }; -// 他得有一个额外的变量记录方向, 从而决定下一步的方向. -bool leetcode_1371::hasValidPath(vector> &grid) { - const auto row = grid.size(); - if (row == 0) { - return true; - } - const auto col = grid[0].size(); - if (col == 0) { - return true; - } - if (grid[0][0] == direction::left_to_up) { - return false; - } else if (grid[0][0] == direction::down_to_right) { - grid[0][0] = direction::left_to_right; - const auto v1 = hasValidPath(grid); - if (v1) { +class Solution { +public: + // 他得有一个额外的变量记录方向, 从而决定下一步的方向. + bool hasValidPath(vector> &grid) { + const auto row = grid.size(); + if (row == 0) { return true; } - grid[0][0] = direction::up_to_down; - return hasValidPath(grid); - } - size_t i{0}, j{0}, direction{0};//0 to right, 1 to down, 2 to left,3 to up - switch (grid[0][0]) { - case direction::left_to_right: { - direction = 0; - break; - } - case direction::up_to_down: { - direction = 1; - break; - } - case direction::left_to_down: { - direction = 1; - break; - } - case direction::up_to_right: { - direction = 0; - break; - } - } - vector> vec(row, vector(col, 0)); - while (i < row && j < col) { - if (i == row - 1 && j == col - 1) { + const auto col = grid[0].size(); + if (col == 0) { return true; } - if (vec[i][j] == 1) { + if (grid[0][0] == direction::left_to_up) { return false; + } else if (grid[0][0] == direction::down_to_right) { + grid[0][0] = direction::left_to_right; + const auto v1 = hasValidPath(grid); + if (v1) { + return true; + } + grid[0][0] = direction::up_to_down; + return hasValidPath(grid); } - vec[i][j] = 1; - switch (direction) { - case 0: { - if (j + 1 < col) { - if (grid[i][j + 1] == direction::left_to_right) { - j += 1; - continue; - } else if (grid[i][j + 1] == direction::left_to_down) { - j += 1; - direction = 1; - continue; - } else if (grid[i][j + 1] == direction::left_to_up) { - j += 1; - direction = 3; - continue; + size_t i{0}, j{0}, direction{0};//0 to right, 1 to down, 2 to left,3 to up + switch (grid[0][0]) { + case direction::left_to_right: { + direction = 0; + break; + } + case direction::up_to_down: { + direction = 1; + break; + } + case direction::left_to_down: { + direction = 1; + break; + } + case direction::up_to_right: { + direction = 0; + break; + } + } + vector> vec(row, vector(col, 0)); + while (i < row && j < col) { + if (i == row - 1 && j == col - 1) { + return true; + } + if (vec[i][j] == 1) { + return false; + } + vec[i][j] = 1; + switch (direction) { + case 0: { + if (j + 1 < col) { + if (grid[i][j + 1] == direction::left_to_right) { + j += 1; + continue; + } else if (grid[i][j + 1] == direction::left_to_down) { + j += 1; + direction = 1; + continue; + } else if (grid[i][j + 1] == direction::left_to_up) { + j += 1; + direction = 3; + continue; + } else { + return false; + } } else { return false; } - } else { - return false; } - } - case 1: { - if (i + 1 < row) { - if (grid[i + 1][j] == direction::up_to_down) { - i += 1; - continue; - } else if (grid[i + 1][j] == direction::left_to_up) { - i += 1; - direction = 2; - continue; - } else if (grid[i + 1][j] == direction::up_to_right) { - i += 1; - direction = 0; - continue; + case 1: { + if (i + 1 < row) { + if (grid[i + 1][j] == direction::up_to_down) { + i += 1; + continue; + } else if (grid[i + 1][j] == direction::left_to_up) { + i += 1; + direction = 2; + continue; + } else if (grid[i + 1][j] == direction::up_to_right) { + i += 1; + direction = 0; + continue; + } else { + return false; + } } else { return false; } - } else { - return false; } - } - case 2: { - if (j > 0) { - if (grid[i][j - 1] == direction::left_to_right) { - j -= 1; - continue; - } else if (grid[i][j - 1] == direction::down_to_right) { - j -= 1; - direction = 1; - continue; - } else if (grid[i][j - 1] == direction::up_to_right) { - j -= 1; - direction = 3; - continue; + case 2: { + if (j > 0) { + if (grid[i][j - 1] == direction::left_to_right) { + j -= 1; + continue; + } else if (grid[i][j - 1] == direction::down_to_right) { + j -= 1; + direction = 1; + continue; + } else if (grid[i][j - 1] == direction::up_to_right) { + j -= 1; + direction = 3; + continue; + } else { + return false; + } } else { return false; } - } else { - return false; } - } - case 3: { - if (i > 0) { - if (grid[i - 1][j] == direction::up_to_down) { - i -= 1; - continue; - } else if (grid[i - 1][j] == direction::left_to_down) { - i -= 1; - direction = 2; - continue; - } else if (grid[i - 1][j] == direction::down_to_right) { - i -= 1; - direction = 0; - continue; + case 3: { + if (i > 0) { + if (grid[i - 1][j] == direction::up_to_down) { + i -= 1; + continue; + } else if (grid[i - 1][j] == direction::left_to_down) { + i -= 1; + direction = 2; + continue; + } else if (grid[i - 1][j] == direction::down_to_right) { + i -= 1; + direction = 0; + continue; + } else { + return false; + } } else { return false; } - } else { - return false; } } } + return false; } - return false; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1391_test.cpp b/algorithm/array/leetcode_1391_test.cpp new file mode 100644 index 00000000..055d63e9 --- /dev/null +++ b/algorithm/array/leetcode_1391_test.cpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1391_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1391_TEST_HPP + +#include +#include +#include +#include +#include + +#include "leetcode_1391.cpp" + +namespace leetcode_1391 { +using std::vector; + +TEST_CASE("test case 1-1 {test_1391}", "{test_1391}") { + vector> input{ + {2, 4, 3}, + {6, 5, 2}, + }; + Solution solution; + CHECK(solution.hasValidPath(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1391_TEST_HPP diff --git a/algorithm/array/leetcode_1391_test.hpp b/algorithm/array/leetcode_1391_test.hpp deleted file mode 100644 index 41263bbf..00000000 --- a/algorithm/array/leetcode_1391_test.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1391_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1391_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_1371 { -using std::vector; - -namespace leetcode_1371 { -bool hasValidPath(vector> &grid); -} - -TEST_CASE("test case 1-1 {test_1371}", "{test_1371}") { - vector> input{ - {2, 4, 3}, - {6, 5, 2}, - }; - CHECK(leetcode_1371::hasValidPath(input)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1391_TEST_HPP diff --git a/algorithm/array/leetcode_15.cpp b/algorithm/array/leetcode_15.cpp index abf9370f..92c8e000 100644 --- a/algorithm/array/leetcode_15.cpp +++ b/algorithm/array/leetcode_15.cpp @@ -1,44 +1,50 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_15_test.hpp" #include +#include +#include namespace leetcode_15 { +using std::vector; +#endif -vector> leetcode_15::threeSum(vector &nums) { - vector> will_return{}; - std::sort(std::begin(nums), std::end(nums)); - const auto nums_size = nums.size(); - if (nums_size < 3) { - return will_return; - } - const auto fst_right_range = nums_size - 2; - // 优化: next数组,提前计算好从左到右,右到左的跳跃步骤 - // 至少外层循坏可以节约时间 - for (size_t i{0}; i < fst_right_range;) { - const auto base = nums[i]; - // snd,一串序列的最左侧 - // trd,一串序列的最右侧 - for (auto snd = i + 1, trd = nums_size - 1; snd < trd;) { - const auto sums = base + nums[snd] + nums[trd]; - if (sums < 0) { - // 这样的话, snd 0) { - for (--trd; trd > snd && nums[trd] == nums[trd + 1]; --trd) {} - } else { - will_return.push_back(vector{base, nums[snd], nums[trd]}); - for (++snd; snd < trd && nums[snd] == nums[snd - 1]; ++snd) {} - for (--trd; trd > snd && nums[trd] == nums[trd + 1]; --trd) {} +class Solution { +public: + vector> threeSum(vector &nums) { + vector> will_return{}; + std::sort(std::begin(nums), std::end(nums)); + const auto nums_size = nums.size(); + if (nums_size < 3) { + return will_return; + } + const auto fst_right_range = nums_size - 2; + // 优化: next数组,提前计算好从左到右,右到左的跳跃步骤 + // 至少外层循坏可以节约时间 + for (size_t i{0}; i < fst_right_range;) { + const auto base = nums[i]; + // snd,一串序列的最左侧 + // trd,一串序列的最右侧 + for (auto snd = i + 1, trd = nums_size - 1; snd < trd;) { + const auto sums = base + nums[snd] + nums[trd]; + if (sums < 0) { + // 这样的话, snd 0) { + for (--trd; trd > snd && nums[trd] == nums[trd + 1]; --trd) {} + } else { + will_return.push_back(vector{base, nums[snd], nums[trd]}); + for (++snd; snd < trd && nums[snd] == nums[snd - 1]; ++snd) {} + for (--trd; trd > snd && nums[trd] == nums[trd + 1]; --trd) {} + } } + for (++i; i < fst_right_range && nums[i] == nums[i - 1]; ++i) {} } - for (++i; i < fst_right_range && nums[i] == nums[i - 1]; ++i) {} + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_15_test.hpp b/algorithm/array/leetcode_15_test.cpp similarity index 68% rename from algorithm/array/leetcode_15_test.hpp rename to algorithm/array/leetcode_15_test.cpp index 6b83b31c..ffdad248 100644 --- a/algorithm/array/leetcode_15_test.hpp +++ b/algorithm/array/leetcode_15_test.cpp @@ -1,33 +1,23 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_15_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_15_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_15_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_15_TEST_HPP +#include "leetcode_15.cpp" #include -#include -#include -#include namespace leetcode_15 { using std::vector; -struct leetcode_15 { - static vector> threeSum(vector &nums); -}; - using Catch::Matchers::UnorderedEquals; TEST_CASE("1 [test_15]", "[test_15]") { vector nums{-4, -1, -1, 0, 1, 2}; - auto output = leetcode_15::threeSum(nums); + auto clas = Solution(); + auto output = clas.threeSum(nums); const vector> results{{-1, 0, 1}, {-1, -1, 2}}; CHECK_THAT(output, UnorderedEquals(results)); @@ -35,28 +25,32 @@ TEST_CASE("1 [test_15]", "[test_15]") { TEST_CASE("2 [test_15]", "[test_15]") { vector nums{}; - auto output = leetcode_15::threeSum(nums); + auto clas = Solution(); + auto output = clas.threeSum(nums); const vector> results{}; CHECK_THAT(output, UnorderedEquals(results)); } TEST_CASE("3 [test_15]", "[test_15]") { vector nums{0}; - auto output = leetcode_15::threeSum(nums); + auto clas = Solution(); + auto output = clas.threeSum(nums); const vector> results{}; CHECK_THAT(output, UnorderedEquals(results)); } TEST_CASE("8 [test_15]", "[test_15]") { vector nums{0, 0, 0}; - auto output = leetcode_15::threeSum(nums); + auto clas = Solution(); + auto output = clas.threeSum(nums); const vector> results{{0, 0, 0}}; CHECK_THAT(output, UnorderedEquals(results)); } TEST_CASE("4 [test_15]", "[test_15]") { vector nums{-1, 0, 1, 2, -1, -4}; - auto output = leetcode_15::threeSum(nums); + auto clas = Solution(); + auto output = clas.threeSum(nums); const vector> results{{-1, 0, 1}, {-1, -1, 2}}; CHECK_THAT(output, UnorderedEquals(results)); @@ -64,23 +58,26 @@ TEST_CASE("4 [test_15]", "[test_15]") { TEST_CASE("5 [test_15]", "[test_15]") { vector nums{}; - auto output = leetcode_15::threeSum(nums); + auto clas = Solution(); + auto output = clas.threeSum(nums); const vector> results{}; CHECK_THAT(output, UnorderedEquals(results)); } TEST_CASE("6 [test_15]", "[test_15]") { vector nums{0}; - auto output = leetcode_15::threeSum(nums); + auto clas = Solution(); + auto output = clas.threeSum(nums); const vector> results{}; CHECK_THAT(output, UnorderedEquals(results)); } TEST_CASE("7 [test_15]", "[test_15]") { vector nums{0, 0, 0}; - auto output = leetcode_15::threeSum(nums); + auto clas = Solution(); + auto output = clas.threeSum(nums); const vector> results{{0, 0, 0}}; CHECK_THAT(output, UnorderedEquals(results)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_15_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_15_TEST_HPP diff --git a/algorithm/array/leetcode_16.cpp b/algorithm/array/leetcode_16.cpp index 99585793..210f6473 100644 --- a/algorithm/array/leetcode_16.cpp +++ b/algorithm/array/leetcode_16.cpp @@ -1,36 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_16_test.hpp" #include +#include +#include +#include namespace leetcode_16 { +using std::vector; +#endif -int leetcode_16::threeSumClosest(vector &nums, int target) { - std::sort(nums.begin(), nums.end()); - int32_t mindiff{std::numeric_limits::max()}, will_return{0}; - const auto nums_size = nums.size(); - for (size_t i{0}; i < nums_size; i++) { - const auto target_diff = target - nums[i]; - size_t left{i + 1}, right{nums_size - 1}; - while (left < right) { - const auto sum = nums[left] + nums[right]; - const auto diff = target_diff - sum; - if (diff < 0) { - right--; - } else { - left++; - } - if (mindiff > std::abs(diff)) { - mindiff = std::abs(diff); - will_return = sum + nums[i]; +class Solution { +public: + int32_t threeSumClosest(vector &nums, int32_t target) { + std::sort(nums.begin(), nums.end()); + int32_t mindiff{std::numeric_limits::max()}, will_return{0}; + const auto nums_size = nums.size(); + for (size_t i{0}; i < nums_size; i++) { + const auto target_diff = target - nums[i]; + size_t left{i + 1}, right{nums_size - 1}; + while (left < right) { + const auto sum = nums[left] + nums[right]; + const auto diff = target_diff - sum; + if (diff < 0) { + right--; + } else { + left++; + } + if (mindiff > std::abs(diff)) { + mindiff = std::abs(diff); + will_return = sum + nums[i]; + } } } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1606.cpp b/algorithm/array/leetcode_1606.cpp index 191901b3..11f79de0 100644 --- a/algorithm/array/leetcode_1606.cpp +++ b/algorithm/array/leetcode_1606.cpp @@ -1,18 +1,20 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1606_test.hpp" #include #include +#include +#include +#include using std::map; +using std::vector; using std::priority_queue; namespace leetcode_1606 { +#endif + struct server { int32_t order; int32_t finishTime; @@ -23,57 +25,62 @@ struct server { } }; +class Solution { +public: // 最简单的思路是模拟数组, 但是这样是O(N^2),需要优化 // 根源在于如果维护一个数组, 必须按顺序遍历数组内的元素,才能得到具体哪一个可用 // 这个过程中浪费了很多资源来过滤那些不可用的 // 所以需要将running的服务置于另一个容器中, 每次将本次可用的搬回来, 减少遍历复杂度 // 这样每次最坏O(N)就变成了每次最坏O1遍历 // 一个服务激活一次也只能重入一次 -vector leetcode_1606::busiestServers(int32_t k, const vector &arrival, const vector &load) { - const auto arr_size = arrival.size(); - map canUse{}; - for (int32_t i{0}; i < k; ++i) { - canUse.insert(std::pair{i, server{i, 0, 0}}); - } - priority_queue works{}; - int32_t max{-1}; - for (size_t i{0}; i < arr_size; ++i) { - while (!works.empty()) { - const auto head = works.top(); - if (head.finishTime <= arrival[i]) { - works.pop(); - canUse.insert(std::pair{head.order, head}); + vector busiestServers(int32_t k, const vector &arrival, const vector &load) { + const auto arr_size = arrival.size(); + map canUse{}; + for (int32_t i{0}; i < k; ++i) { + canUse.insert(std::pair{i, server{i, 0, 0}}); + } + priority_queue works{}; + int32_t max{-1}; + for (size_t i{0}; i < arr_size; ++i) { + while (!works.empty()) { + const auto head = works.top(); + if (head.finishTime <= arrival[i]) { + works.pop(); + canUse.insert(std::pair{head.order, head}); + } else { + break; + } + } + if (canUse.empty()) { + continue; + } + const auto iter = canUse.lower_bound(i % k); + if (iter != std::end(canUse)) { + works.push(server{iter->first, arrival[i] + load[i], iter->second.times + 1}); + max = std::max(max, iter->second.times + 1); + canUse.erase(iter); } else { - break; + const auto iter2 = std::begin(canUse); + const auto times = iter2->second.times + 1; + works.push(server{iter2->first, arrival[i] + load[i], times}); + max = std::max(max, times); + canUse.erase(iter2); } } - if (canUse.empty()) { - continue; + for (; !works.empty(); works.pop()) { + const auto top = works.top(); + canUse.insert(std::pair{top.order, top}); } - const auto iter = canUse.lower_bound(i % k); - if (iter != std::end(canUse)) { - works.push(server{iter->first, arrival[i] + load[i], iter->second.times + 1}); - max = std::max(max, iter->second.times + 1); - canUse.erase(iter); - } else { - const auto iter2 = std::begin(canUse); - const auto times = iter2->second.times + 1; - works.push(server{iter2->first, arrival[i] + load[i], times}); - max = std::max(max, times); - canUse.erase(iter2); - } - } - for (; !works.empty(); works.pop()) { - const auto top = works.top(); - canUse.insert(std::pair{top.order, top}); - } - vector will_return{}; - for (const auto[key, v]: canUse) { - if (v.times == max) { - will_return.push_back(key); + vector will_return{}; + for (const auto [key, v]: canUse) { + if (v.times == max) { + will_return.push_back(key); + } } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_1606_test.hpp b/algorithm/array/leetcode_1606_test.cpp similarity index 55% rename from algorithm/array/leetcode_1606_test.hpp rename to algorithm/array/leetcode_1606_test.cpp index c2da671e..c72b89d1 100644 --- a/algorithm/array/leetcode_1606_test.hpp +++ b/algorithm/array/leetcode_1606_test.cpp @@ -1,28 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag 暴力解法 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1606_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1606_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1606_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1606_TEST_HPP #include -#include -#include -#include +#include "leetcode_1606.cpp" namespace leetcode_1606 { using std::vector; -struct leetcode_1606 { - static vector busiestServers(int32_t k, const vector &arrival, const vector &load); -}; - using Catch::Matchers::UnorderedEquals; TEST_CASE("test case 1 {test_1606}", "{test_1606}") { @@ -30,7 +19,8 @@ TEST_CASE("test case 1 {test_1606}", "{test_1606}") { const vector arrival{1, 2, 3, 4, 5}; const vector load{5, 2, 3, 3, 3}; const vector result{1}; - CHECK_THAT(result, UnorderedEquals(leetcode_1606::busiestServers(k, arrival, load))); + leetcode_1606::Solution solution; + CHECK_THAT(result, UnorderedEquals(solution.busiestServers(k, arrival, load))); } TEST_CASE("test case 2 {test_1606}", "{test_1606}") { @@ -38,7 +28,8 @@ TEST_CASE("test case 2 {test_1606}", "{test_1606}") { const vector arrival{1, 2, 3}; const vector load{114514, 1, 114514}; const vector result{1}; - CHECK_THAT(result, UnorderedEquals(leetcode_1606::busiestServers(k, arrival, load))); + leetcode_1606::Solution solution; + CHECK_THAT(result, UnorderedEquals(solution.busiestServers(k, arrival, load))); } TEST_CASE("test case 3 {test_1606}", "{test_1606}") { @@ -46,7 +37,8 @@ TEST_CASE("test case 3 {test_1606}", "{test_1606}") { const vector arrival{1, 2, 3, 4, 8, 9, 10}; const vector load{5, 2, 10, 3, 1, 2, 2}; const vector result{1}; - CHECK_THAT(result, UnorderedEquals(leetcode_1606::busiestServers(k, arrival, load))); + leetcode_1606::Solution solution; + CHECK_THAT(result, UnorderedEquals(solution.busiestServers(k, arrival, load))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1606_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1606_TEST_HPP diff --git a/algorithm/array/leetcode_167.cpp b/algorithm/array/leetcode_167.cpp index 66f5ef4c..5f09f115 100644 --- a/algorithm/array/leetcode_167.cpp +++ b/algorithm/array/leetcode_167.cpp @@ -1,41 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_167_test.hpp" +#include #include +#include namespace leetcode_167 { +using std::vector; using std::unordered_map; +#endif -vector leetcode_167::twoSum(const vector &numbers, int32_t target) { - unordered_map umap; - for (size_t i{0}, nums_size{numbers.size()}; i < nums_size; i++) { - const auto iPlus = static_cast(i + 1); - if (umap.count(target - numbers[i]) != 0) { - return {umap[target - numbers[i]], iPlus}; - } else { - umap[numbers[i]] = iPlus; +class Solution { +public: + vector twoSum(const vector &numbers, int32_t target) { + unordered_map umap; + for (size_t i{0}, nums_size{numbers.size()}; i < nums_size; i++) { + const auto iPlus = static_cast(i + 1); + if (umap.count(target - numbers[i]) != 0) { + return {umap[target - numbers[i]], iPlus}; + } else { + umap[numbers[i]] = iPlus; + } } + return {-1, -1}; } - return {-1, -1}; -} -vector leetcode_167::twoSum2(const vector &numbers, int32_t target) { - int32_t begin{0}; - auto ends = static_cast(numbers.size() - 1); - int32_t sum{numbers[begin] + numbers[ends]}; - while (begin < ends && sum != target) { - if (sum > target) { - ends--; - } else if (sum < target) { - begin++; + vector twoSum2(const vector &numbers, int32_t target) { + int32_t begin{0}; + auto ends = static_cast(numbers.size() - 1); + int32_t sum{numbers[begin] + numbers[ends]}; + while (begin < ends && sum != target) { + if (sum > target) { + ends--; + } else if (sum < target) { + begin++; + } + sum = numbers[begin] + numbers[ends]; } - sum = numbers[begin] + numbers[ends]; + return {begin + 1, ends + 1}; } - return {begin + 1, ends + 1}; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_167_test.cpp b/algorithm/array/leetcode_167_test.cpp new file mode 100644 index 00000000..c245199a --- /dev/null +++ b/algorithm/array/leetcode_167_test.cpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 双指针 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_167_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_167_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_167.cpp" + +namespace leetcode_167 { +using std::vector; + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_167]", "[test_167]") { + const vector input{2, 7, 11, 15}; + static constexpr const auto target{9}; + const vector result{1, 2}; + Solution solution; + CHECK_THAT(solution.twoSum(input, target), Equals(result)); + CHECK_THAT(solution.twoSum2(input, target), Equals(result)); +} + +TEST_CASE("test case 2 [test_167]", "[test_167]") { + const vector input{2, 3, 4}; + static constexpr const auto target{6}; + const vector result{1, 3}; + Solution solution; + CHECK_THAT(solution.twoSum(input, target), Equals(result)); + CHECK_THAT(solution.twoSum2(input, target), Equals(result)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_167_TEST_HPP diff --git a/algorithm/array/leetcode_167_test.hpp b/algorithm/array/leetcode_167_test.hpp deleted file mode 100644 index d73a22a8..00000000 --- a/algorithm/array/leetcode_167_test.hpp +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 双指针 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_167_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_167_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_167 { -using std::vector; - -struct leetcode_167 { - static vector twoSum(const vector &numbers, int32_t target); - - static vector twoSum2(const vector &numbers, int32_t target); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_167]", "[test_167]") { - const vector input{2, 7, 11, 15}; - static constexpr const auto target{9}; - const vector result{1, 2}; - CHECK_THAT(leetcode_167::twoSum(input, target), Equals(result)); - CHECK_THAT(leetcode_167::twoSum2(input, target), Equals(result)); -} - -TEST_CASE("test case 2 [test_167]", "[test_167]") { - const vector input{2, 3, 4}; - static constexpr const auto target{6}; - const vector result{1, 3}; - CHECK_THAT(leetcode_167::twoSum(input, target), Equals(result)); - CHECK_THAT(leetcode_167::twoSum2(input, target), Equals(result)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_167_TEST_HPP diff --git a/algorithm/array/leetcode_16_test.cpp b/algorithm/array/leetcode_16_test.cpp new file mode 100644 index 00000000..0b4df472 --- /dev/null +++ b/algorithm/array/leetcode_16_test.cpp @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 双指针 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_16_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_16_TEST_HPP + +#include "leetcode_16.cpp" +#include + +namespace leetcode_16 { +using std::vector; + +TEST_CASE("1 [test_16]", "[test_16]") { + vector nums{-1, 2, 1, -4}; + auto clas = Solution(); + const auto output = clas.threeSumClosest(nums, 1); + CHECK(output == 2); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_16_TEST_HPP diff --git a/algorithm/array/leetcode_16_test.hpp b/algorithm/array/leetcode_16_test.hpp deleted file mode 100644 index cb4d1846..00000000 --- a/algorithm/array/leetcode_16_test.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 双指针 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_16_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_16_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_16 { -using std::vector; - -struct leetcode_16 { - static int32_t threeSumClosest(vector &nums, int32_t target); -}; - -TEST_CASE("1 [test_16]", "[test_16]") { - vector nums{-1, 2, 1, -4}; - const auto output = leetcode_16::threeSumClosest(nums, 1); - CHECK(output == 2); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_16_TEST_HPP diff --git a/algorithm/array/leetcode_17.cpp b/algorithm/array/leetcode_17.cpp index 7faa66e7..716b4685 100644 --- a/algorithm/array/leetcode_17.cpp +++ b/algorithm/array/leetcode_17.cpp @@ -1,38 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_17_test.hpp" +#include +#include namespace leetcode_17 { -vector leetcode_17::letterCombinations(const string &digits) { - if (digits.empty()) { - return {}; - } - const vector> chars{ - {}, - {'a', 'b', 'c'}, - {'d', 'e', 'f'}, - {'g', 'h', 'i'}, - {'j', 'k', 'l'}, - {'m', 'n', 'o'}, - {'p', 'q', 'r', 's'}, - {'t', 'u', 'v'}, - {'w', 'x', 'y', 'z'} - }; - vector will_return = {""}; - for (const char &digit: digits) { - vector temp; - for (const string &temp_str: will_return) { - for (const char &k: chars[digit - '1']) { - temp.emplace_back(temp_str + k); +using std::vector; +using std::string; +#endif + +class Solution { +public: + vector letterCombinations(const string &digits) { + if (digits.empty()) { + return {}; + } + const vector> chars{ + {}, + {'a', 'b', 'c'}, + {'d', 'e', 'f'}, + {'g', 'h', 'i'}, + {'j', 'k', 'l'}, + {'m', 'n', 'o'}, + {'p', 'q', 'r', 's'}, + {'t', 'u', 'v'}, + {'w', 'x', 'y', 'z'} + }; + vector will_return = {""}; + for (const char &digit: digits) { + vector temp; + for (const string &temp_str: will_return) { + for (const char &k: chars[digit - '1']) { + temp.emplace_back(temp_str + k); + } } + will_return = temp; } - will_return = temp; + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_17_test.cpp b/algorithm/array/leetcode_17_test.cpp new file mode 100644 index 00000000..5dd382d0 --- /dev/null +++ b/algorithm/array/leetcode_17_test.cpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 双指针 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_17_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_17_TEST_HPP + +#include "leetcode_17.cpp" +#include + +namespace leetcode_17 { +using std::vector; +using std::string; + +using Catch::Matchers::UnorderedEquals; + +TEST_CASE("test case 1 [test_17]", "[test_17]") { + auto clas = Solution(); + CHECK_THAT(clas.letterCombinations("23"), + UnorderedEquals({"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"})); +} + +TEST_CASE("test case 2 [test_17]", "[test_17]") { + auto clas = Solution(); + CHECK_THAT(clas.letterCombinations(""), + UnorderedEquals({})); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_17_TEST_HPP diff --git a/algorithm/array/leetcode_17_test.hpp b/algorithm/array/leetcode_17_test.hpp deleted file mode 100644 index 2d97460f..00000000 --- a/algorithm/array/leetcode_17_test.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 双指针 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_17_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_17_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_17 { -using std::vector; -using std::string; - -struct leetcode_17 { - static vector letterCombinations(const string &digits); -}; - -using Catch::Matchers::UnorderedEquals; - -TEST_CASE("test case 1 [test_17]", "[test_17]") { - CHECK_THAT(leetcode_17::letterCombinations("23"), - UnorderedEquals({"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"})); -} - -TEST_CASE("test case 2 [test_17]", "[test_17]") { - CHECK_THAT(leetcode_17::letterCombinations(""), - UnorderedEquals({})); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_17_TEST_HPP diff --git a/algorithm/array/leetcode_1_test.hpp b/algorithm/array/leetcode_1_test.cpp similarity index 58% rename from algorithm/array/leetcode_1_test.hpp rename to algorithm/array/leetcode_1_test.cpp index 37853bc7..3ebc4309 100644 --- a/algorithm/array/leetcode_1_test.hpp +++ b/algorithm/array/leetcode_1_test.cpp @@ -1,33 +1,24 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Plan 数据结构入门 Day2 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1_TEST_HPP #include -#include -#include -#include +#include "leetcode_1.cpp" namespace leetcode_1 { using std::vector; -struct leetcode_1 { - static vector twoSum(const vector &nums, int32_t target); -}; using Catch::Matchers::UnorderedEquals; TEST_CASE("basic tests [test_1]", "[test_1]") { const vector vec{2, 7, 11, 15}; - const auto result = leetcode_1::twoSum(vec, 9); + auto clas = Solution(); + const auto result = clas.twoSum(vec, 9); SECTION("size is always 2") { CHECK(result.size() == 2); }SECTION("test cases") { @@ -37,7 +28,8 @@ TEST_CASE("basic tests [test_1]", "[test_1]") { TEST_CASE("basic tests 2 [test_1]", "[test_1]") { const vector vec{3, 2, 4}; - const auto result = leetcode_1::twoSum(vec, 6); + auto clas = Solution(); + const auto result = clas.twoSum(vec, 6); SECTION("size is always 2") { CHECK(result.size() == 2); }SECTION("test cases") { @@ -46,4 +38,4 @@ TEST_CASE("basic tests 2 [test_1]", "[test_1]") { } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1_TEST_HPP diff --git a/algorithm/array/leetcode_219.cpp b/algorithm/array/leetcode_219.cpp index 3006071c..a8f90c2b 100644 --- a/algorithm/array/leetcode_219.cpp +++ b/algorithm/array/leetcode_219.cpp @@ -1,26 +1,31 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_219_test.hpp" +#include #include +#include namespace leetcode_219 { +using std::vector; using std::unordered_map; +#endif -bool leetcode_219::containsNearbyDuplicate(const vector &nums, int32_t k) { - unordered_map umap; - const int32_t nums_size{static_cast(nums.size())}; - for (int32_t i{0}; i < nums_size; i++) { - if (umap[nums[i]] != 0 && (i - umap[nums[i]]) < k) { - return true; +class Solution { +public: + bool containsNearbyDuplicate(const vector &nums, int32_t k) { + unordered_map umap; + const int32_t nums_size{static_cast(nums.size())}; + for (int32_t i{0}; i < nums_size; i++) { + if (umap[nums[i]] != 0 && (i - umap[nums[i]]) < k) { + return true; + } + umap[nums[i]] = i + 1; } - umap[nums[i]] = i + 1; + return false; } - return false; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_219_test.hpp b/algorithm/array/leetcode_219_test.cpp similarity index 53% rename from algorithm/array/leetcode_219_test.hpp rename to algorithm/array/leetcode_219_test.cpp index 5a42a4d0..f9aac1b6 100644 --- a/algorithm/array/leetcode_219_test.hpp +++ b/algorithm/array/leetcode_219_test.cpp @@ -1,44 +1,39 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag 哈希表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_219_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_219_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_219_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_219_TEST_HPP #include #include #include #include +#include "leetcode_219.cpp" namespace leetcode_219 { using std::vector; -struct leetcode_219 { - static bool containsNearbyDuplicate(const vector &nums, int32_t k); -}; - TEST_CASE("test case 1 [test_219]", "[test_219]") { const vector input{1, 2, 3, 1}; static constexpr const auto k{3}; - CHECK(leetcode_219::containsNearbyDuplicate(input, k)); + Solution solution; + CHECK(solution.containsNearbyDuplicate(input, k)); } TEST_CASE("test case 2 [test_219]", "[test_219]") { const vector input{1, 0, 1, 1}; static constexpr const auto k{1}; - CHECK(leetcode_219::containsNearbyDuplicate(input, k)); + Solution solution; + CHECK(solution.containsNearbyDuplicate(input, k)); } TEST_CASE("test case 3 [test_219]", "[test_219]") { const vector input{1, 2, 3, 1, 2, 3}; static constexpr const auto k{2}; - CHECK_FALSE(leetcode_219::containsNearbyDuplicate(input, k)); + Solution solution; + CHECK_FALSE(solution.containsNearbyDuplicate(input, k)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_219_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_219_TEST_HPP diff --git a/algorithm/array/leetcode_238.cpp b/algorithm/array/leetcode_238.cpp index 7ba20a27..1d829750 100644 --- a/algorithm/array/leetcode_238.cpp +++ b/algorithm/array/leetcode_238.cpp @@ -1,25 +1,31 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_238_test.hpp" +#include +#include namespace leetcode_238 { +using std::vector; +using std::size_t; +#endif -vector leetcode_238::productExceptSelf(const vector &nums) { - const auto nums_size{nums.size()}; - vector pre(nums_size, 1), post(nums_size, 1), mid(nums_size, 1); - for (size_t i{1}; i < nums_size; ++i) { - pre[i] = pre[i - 1] * nums[i - 1]; - post[nums_size - 1 - i] = post[nums_size - i] * nums[nums_size - i]; - } - for (size_t i{0}; i < nums_size; ++i) { - mid[i] = pre[i] * post[i]; +class Solution { +public: + vector productExceptSelf(const vector &nums) { + const auto nums_size{nums.size()}; + vector pre(nums_size, 1), post(nums_size, 1), mid(nums_size, 1); + for (size_t i{1}; i < nums_size; ++i) { + pre[i] = pre[i - 1] * nums[i - 1]; + post[nums_size - 1 - i] = post[nums_size - i] * nums[nums_size - i]; + } + for (size_t i{0}; i < nums_size; ++i) { + mid[i] = pre[i] * post[i]; + } + return mid; } - return mid; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_238_test.cpp b/algorithm/array/leetcode_238_test.cpp new file mode 100644 index 00000000..ca5c8bfe --- /dev/null +++ b/algorithm/array/leetcode_238_test.cpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 二分搜索 +//@Plan 数据结构基础 Day4 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_238_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_238_TEST_HPP + +#include + +#include "leetcode_238.cpp" + +namespace leetcode_238 { +using std::vector; + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 {test_238}", "{test_238}") { + const vector input{1, 4, 7, 11, 15}; + const vector result{4620, 1155, 660, 420, 308}; + Solution solution; + CHECK_THAT(result, Equals(solution.productExceptSelf(input))); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_238_TEST_HPP diff --git a/algorithm/array/leetcode_238_test.hpp b/algorithm/array/leetcode_238_test.hpp deleted file mode 100644 index e10c0ade..00000000 --- a/algorithm/array/leetcode_238_test.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 二分搜索 -//@Plan 数据结构基础 Day4 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_238_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_238_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_238 { -using std::vector; - -struct leetcode_238 { - static vector productExceptSelf(const vector &nums); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 {test_238}", "{test_238}") { - const vector input{1, 4, 7, 11, 15}; - const vector result{4620, 1155, 660, 420, 308}; - CHECK_THAT(result, Equals(leetcode_238::productExceptSelf(input))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_238_TEST_HPP diff --git a/algorithm/array/leetcode_240.cpp b/algorithm/array/leetcode_240.cpp index c6df2caf..76da1267 100644 --- a/algorithm/array/leetcode_240.cpp +++ b/algorithm/array/leetcode_240.cpp @@ -1,55 +1,61 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_240_test.hpp" +#include +#include +#include namespace leetcode_240 { +using std::vector; +#endif -bool leetcode_240::findNumberIn2DArray(const vector> &matrix, int32_t target) { - if (matrix.empty() || matrix.front().empty()) { - return false; - } - const size_t n = matrix.size(); - vector begins(n, 0); - vector ends(n, 0); - for (size_t i{0}; i < n; ++i) { - begins[i] = *matrix[i].begin(); - ends[i] = *(matrix[i].end() - 1); - } - const auto temp = std::upper_bound(begins.begin(), begins.end(), target) - begins.begin() - 1; - const auto temp2 = std::lower_bound(ends.begin(), ends.end(), target) - ends.begin(); - for (auto i{temp2}; i <= temp; ++i) { - if (std::binary_search(matrix[i].begin(), matrix[i].end(), target)) { - return true; +class Solution { +public: + bool findNumberIn2DArray(const vector> &matrix, int32_t target) { + if (matrix.empty() || matrix.front().empty()) { + return false; + } + const size_t n = matrix.size(); + vector begins(n, 0); + vector ends(n, 0); + for (size_t i{0}; i < n; ++i) { + begins[i] = *matrix[i].begin(); + ends[i] = *(matrix[i].end() - 1); + } + const auto temp = std::upper_bound(begins.begin(), begins.end(), target) - begins.begin() - 1; + const auto temp2 = std::lower_bound(ends.begin(), ends.end(), target) - ends.begin(); + for (auto i{temp2}; i <= temp; ++i) { + if (std::binary_search(matrix[i].begin(), matrix[i].end(), target)) { + return true; + } } - } - return false; -} - -bool leetcode_240::findNumberIn2DArrayZ(const vector> &matrix, int32_t target) { - const auto m = static_cast(matrix.size()); - if (m == 0) { - return false; - } - const auto n = static_cast(matrix.front().size()); - if (n == 0) { return false; } - for (int32_t x{0}, y = n - 1; x < m && y >= 0;) { - const auto find = matrix[x][y]; - if (find == target) { - return true; - } else if (find > target) { - y--; - } else { - x++; + + bool findNumberIn2DArrayZ(const vector> &matrix, int32_t target) { + const auto m = static_cast(matrix.size()); + if (m == 0) { + return false; } + const auto n = static_cast(matrix.front().size()); + if (n == 0) { + return false; + } + for (int32_t x{0}, y = n - 1; x < m && y >= 0;) { + const auto find = matrix[x][y]; + if (find == target) { + return true; + } else if (find > target) { + y--; + } else { + x++; + } + } + return false; } - return false; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_240_test.hpp b/algorithm/array/leetcode_240_test.cpp similarity index 55% rename from algorithm/array/leetcode_240_test.hpp rename to algorithm/array/leetcode_240_test.cpp index 9036a008..3b3e7903 100644 --- a/algorithm/array/leetcode_240_test.hpp +++ b/algorithm/array/leetcode_240_test.cpp @@ -1,30 +1,21 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag 二分搜索 //@Plan 剑指OfferII-I Day05 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_240_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_240_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_240_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_240_TEST_HPP #include #include #include #include +#include "leetcode_240.cpp" namespace leetcode_240 { using std::vector; -struct leetcode_240 { - static bool findNumberIn2DArray(const vector> &matrix, int32_t target); - static bool findNumberIn2DArrayZ(const vector> &matrix, int32_t target); -}; - TEST_CASE("test case 1 {test_240}", "{test_240}") { const vector> input{ {1, 4, 7, 11, 15}, @@ -34,8 +25,9 @@ TEST_CASE("test case 1 {test_240}", "{test_240}") { {18, 21, 23, 26, 30} }; static constexpr const auto k{5}; - CHECK(leetcode_240::findNumberIn2DArray(input, k)); - CHECK(leetcode_240::findNumberIn2DArrayZ(input, k)); + Solution solution; + CHECK(solution.findNumberIn2DArray(input, k)); + CHECK(solution.findNumberIn2DArrayZ(input, k)); } TEST_CASE("test case 2 {test_240}", "{test_240}") { @@ -47,8 +39,9 @@ TEST_CASE("test case 2 {test_240}", "{test_240}") { {18, 21, 23, 26, 30} }; static constexpr const auto k{20}; - CHECK_FALSE(leetcode_240::findNumberIn2DArray(input, k)); - CHECK_FALSE(leetcode_240::findNumberIn2DArrayZ(input, k)); + Solution solution; + CHECK_FALSE(solution.findNumberIn2DArray(input, k)); + CHECK_FALSE(solution.findNumberIn2DArrayZ(input, k)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_240_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_240_TEST_HPP diff --git a/algorithm/array/leetcode_26.cpp b/algorithm/array/leetcode_26.cpp index daa92a46..1d879cd8 100644 --- a/algorithm/array/leetcode_26.cpp +++ b/algorithm/array/leetcode_26.cpp @@ -1,26 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_26_test.hpp" +#include +#include namespace leetcode_26 { -int32_t leetcode_26::removeDuplicates(vector &nums) { - if (nums.empty()) { - return 0; - } - int32_t last{nums.front() - 1}, count{0}; - for (auto &num: nums) { - if (num != last) { - last = num; - nums[count] = num; - count++; +using std::vector; +#endif + +class Solution { +public: + int32_t removeDuplicates(vector &nums) { + if (nums.empty()) { + return 0; } + int32_t last{nums.front() - 1}, count{0}; + for (auto &num: nums) { + if (num != last) { + last = num; + nums[count] = num; + count++; + } + } + nums.resize(count); + return count; } - nums.resize(count); - return count; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_26_test.hpp b/algorithm/array/leetcode_26_test.cpp similarity index 59% rename from algorithm/array/leetcode_26_test.hpp rename to algorithm/array/leetcode_26_test.cpp index 4e4d8a0a..1060ced0 100644 --- a/algorithm/array/leetcode_26_test.hpp +++ b/algorithm/array/leetcode_26_test.cpp @@ -1,36 +1,25 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_26_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_26_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_26_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_26_TEST_HPP +#include "leetcode_26.cpp" #include -#include -#include -#include namespace leetcode_26 { using std::vector; -struct leetcode_26 { - static int removeDuplicates(vector &nums); - -}; - using Catch::Matchers::Equals; TEST_CASE("1 [test_26]", "[test_26]") { vector vec{1, 2}; const vector result{1, 2}; + auto clas = Solution(); THEN("then1 [test_26]") { - leetcode_26::removeDuplicates(vec); + clas.removeDuplicates(vec); } CHECK_THAT(vec, Equals(result)); } @@ -38,8 +27,9 @@ TEST_CASE("1 [test_26]", "[test_26]") { TEST_CASE("2 [test_26]", "[test_26]") { vector vec{1, 1, 2}; const vector result{1, 2}; + auto clas = Solution(); THEN("then3 [test_26]") { - leetcode_26::removeDuplicates(vec); + clas.removeDuplicates(vec); } CHECK_THAT(vec, Equals(result)); } @@ -47,11 +37,12 @@ TEST_CASE("2 [test_26]", "[test_26]") { TEST_CASE("3 [test_26]", "[test_26]") { vector vec{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}; const vector result{0, 1, 2, 3, 4}; + auto clas = Solution(); THEN("then5 [test_26]") { - leetcode_26::removeDuplicates(vec); + clas.removeDuplicates(vec); } CHECK_THAT(vec, Equals(result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_26_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_26_TEST_HPP diff --git a/algorithm/array/leetcode_27.cpp b/algorithm/array/leetcode_27.cpp index a2bbc1e4..7a8f5e16 100644 --- a/algorithm/array/leetcode_27.cpp +++ b/algorithm/array/leetcode_27.cpp @@ -1,29 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_27_test.hpp" +#include +#include +#include namespace leetcode_27 { +using std::vector; +#endif -int leetcode_27::removeElement(vector &vec, int32_t val) { - vec.erase(std::remove(vec.begin(), vec.end(), val), vec.end()); - return vec.size(); -} +class Solution { +public: + int32_t removeElement(vector &vec, int32_t val) { + vec.erase(std::remove(vec.begin(), vec.end(), val), vec.end()); + return vec.size(); + } -int leetcode_27::removeElement2(vector &vec, int32_t val) { - const size_t vec_size{vec.size()}; - int32_t order{0}; - for (size_t begin{0}; begin < vec_size; begin++) { - if (vec[begin] != val) { - vec[order] = vec[begin]; - order++; + int32_t removeElement2(vector &vec, int32_t val) { + const size_t vec_size{vec.size()}; + int32_t order{0}; + for (size_t begin{0}; begin < vec_size; begin++) { + if (vec[begin] != val) { + vec[order] = vec[begin]; + order++; + } } + vec.resize(order); + return order; } - vec.resize(order); - return order; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_27_test.cpp b/algorithm/array/leetcode_27_test.cpp new file mode 100644 index 00000000..1b550f75 --- /dev/null +++ b/algorithm/array/leetcode_27_test.cpp @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag STL + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_27_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_27_TEST_HPP + +#include "leetcode_27.cpp" +#include + +namespace leetcode_27 { +using std::vector; + +TEST_CASE("1 [test_27]", "[test_27]") { + static constexpr const int32_t test_result{5}; + vector vec1{0, 1, 2, 2, 3, 0, 4, 2}; + auto clas = Solution(); + THEN("1-1 [test_27]") { + CHECK(clas.removeElement(vec1, 2) == test_result); + }THEN("1-2 [test_27]") { + CHECK(clas.removeElement2(vec1, 2) == test_result); + } +} + +TEST_CASE("2 [test_27]", "[test_27]") { + vector vec1{3, 2, 2, 3}; + static constexpr const int32_t test_result{2}; + auto clas = Solution(); + THEN("2-1 [test_27]") { + CHECK(clas.removeElement(vec1, 2) == test_result); + }THEN("2-2 [test_27]") { + CHECK(clas.removeElement2(vec1, 2) == test_result); + } + +} + +TEST_CASE("3 [test_27]", "[test_27]") { + vector vec1{1}; + static constexpr const int32_t test_result{0}; + auto clas = Solution(); + THEN("3-1 [test_27]") { + CHECK(clas.removeElement(vec1, 1) == test_result); + }THEN("3-2 [test_27]") { + CHECK(clas.removeElement2(vec1, 1) == test_result); + } +} + +TEST_CASE("4 [test_27]", "[test_27]") { + static constexpr const int32_t test_result{0}; + vector vec1{}; + auto clas = Solution(); + THEN("4-1 [test_27]") { + CHECK(clas.removeElement(vec1, 0) == test_result); + }THEN("4-2 [test_27]") { + CHECK(clas.removeElement(vec1, 0) == test_result); + } +} + +TEST_CASE("5 [test_27]", "[test_27]") { + static constexpr const int32_t test_result{0}; + vector vec1{3, 3}; + auto clas = Solution(); + THEN("5-1 [test_27]") { + CHECK(clas.removeElement(vec1, 3) == test_result); + }THEN("5-2 [test_27]") { + CHECK(clas.removeElement(vec1, 3) == test_result); + } +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_27_TEST_HPP diff --git a/algorithm/array/leetcode_27_test.hpp b/algorithm/array/leetcode_27_test.hpp deleted file mode 100644 index 12952808..00000000 --- a/algorithm/array/leetcode_27_test.hpp +++ /dev/null @@ -1,81 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag STL - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_27_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_27_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_27 { -using std::vector; - -struct leetcode_27 { - static int removeElement(vector &vec, int32_t val); - - static int removeElement2(vector &vec, int32_t val); -}; - -TEST_CASE("1 [test_27]", "[test_27]") { - static constexpr const int32_t test_result{5}; - vector vec1{0, 1, 2, 2, 3, 0, 4, 2}; - THEN("1-1 [test_27]") { - CHECK(leetcode_27::removeElement(vec1, 2) == test_result); - }THEN("1-2 [test_27]") { - CHECK(leetcode_27::removeElement2(vec1, 2) == test_result); - } -} - -TEST_CASE("2 [test_27]", "[test_27]") { - vector vec1{3, 2, 2, 3}; - static constexpr const int32_t test_result{2}; - THEN("2-1 [test_27]") { - CHECK(leetcode_27::removeElement(vec1, 2) == test_result); - }THEN("2-2 [test_27]") { - CHECK(leetcode_27::removeElement2(vec1, 2) == test_result); - } - -} - -TEST_CASE("3 [test_27]", "[test_27]") { - vector vec1{1}; - static constexpr const int32_t test_result{0}; - THEN("3-1 [test_27]") { - CHECK(leetcode_27::removeElement(vec1, 1) == test_result); - }THEN("3-2 [test_27]") { - CHECK(leetcode_27::removeElement2(vec1, 1) == test_result); - } -} - -TEST_CASE("4 [test_27]", "[test_27]") { - static constexpr const int32_t test_result{0}; - vector vec1{}; - THEN("4-1 [test_27]") { - CHECK(leetcode_27::removeElement(vec1, 0) == test_result); - }THEN("4-2 [test_27]") { - CHECK(leetcode_27::removeElement(vec1, 0) == test_result); - } -} - -TEST_CASE("5 [test_27]", "[test_27]") { - static constexpr const int32_t test_result{0}; - vector vec1{3, 3}; - THEN("5-1 [test_27]") { - CHECK(leetcode_27::removeElement(vec1, 3) == test_result); - }THEN("5-2 [test_27]") { - CHECK(leetcode_27::removeElement(vec1, 3) == test_result); - } -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_27_TEST_HPP diff --git a/algorithm/array/leetcode_31.cpp b/algorithm/array/leetcode_31.cpp index e65c24f3..8bf7a546 100644 --- a/algorithm/array/leetcode_31.cpp +++ b/algorithm/array/leetcode_31.cpp @@ -1,36 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_31_test.hpp" +#include +#include +#include namespace leetcode_31 { +using std::vector; +#endif -void leetcode_31::nextPermutation(vector &nums) { - if (nums.size() <= 1) { - return; - } - size_t j{nums.size() - 1}; - for (; j > 0; j--) { - if (nums[j - 1] < nums[j]) { - break; +class Solution { +public: + void nextPermutation(vector &nums) { + if (nums.size() <= 1) { + return; } - } - if (j == 0) { - std::reverse(nums.begin(), nums.end()); - return; - } - for (size_t k = nums.size() - 1; k >= j; k--) { - if (nums[k] > nums[j - 1]) { - std::swap(nums[k], nums[j - 1]); - break; + size_t j{nums.size() - 1}; + for (; j > 0; j--) { + if (nums[j - 1] < nums[j]) { + break; + } } + if (j == 0) { + std::reverse(nums.begin(), nums.end()); + return; + } + for (size_t k = nums.size() - 1; k >= j; k--) { + if (nums[k] > nums[j - 1]) { + std::swap(nums[k], nums[j - 1]); + break; + } + } + std::reverse(nums.begin() + j, nums.end()); } - std::reverse(nums.begin() + j, nums.end()); -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_31_test.hpp b/algorithm/array/leetcode_31_test.cpp similarity index 65% rename from algorithm/array/leetcode_31_test.hpp rename to algorithm/array/leetcode_31_test.cpp index 256f302a..5725f560 100644 --- a/algorithm/array/leetcode_31_test.hpp +++ b/algorithm/array/leetcode_31_test.cpp @@ -1,70 +1,65 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_31_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_31_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_31_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_31_TEST_HPP +#include "leetcode_31.cpp" #include -#include -#include -#include namespace leetcode_31 { using std::vector; -struct leetcode_31 { - static void nextPermutation(vector &nums); -}; - using Catch::Matchers::Equals; TEST_CASE("basic test [test_31]", "[test_31]") { vector vec1{1, 2, 3}; const vector _vec1{1, 3, 2}; - leetcode_31::nextPermutation(vec1); + auto clas = Solution(); + clas.nextPermutation(vec1); CHECK_THAT(vec1, Equals(_vec1)); } TEST_CASE("test reverse [test_31]", "[test_31]") { vector vec1{3, 2, 1}; const vector _vec1{1, 2, 3}; - leetcode_31::nextPermutation(vec1); + auto clas = Solution(); + clas.nextPermutation(vec1); CHECK_THAT(vec1, Equals(_vec1)); } TEST_CASE("basic test 2 [test_31]", "[test_31]") { vector vec1{1, 1, 5}; const vector _vec1{1, 5, 1}; - leetcode_31::nextPermutation(vec1); + auto clas = Solution(); + clas.nextPermutation(vec1); CHECK_THAT(vec1, Equals(_vec1)); } TEST_CASE("complex test 1 [test_31]", "[test_31]") { vector vec1{1, 2, 1, 5, 4, 3, 3, 2, 1}; const vector _vec1{1, 2, 2, 1, 1, 3, 3, 4, 5}; - leetcode_31::nextPermutation(vec1); + auto clas = Solution(); + clas.nextPermutation(vec1); CHECK_THAT(vec1, Equals(_vec1)); } TEST_CASE("test same elements [test_31]", "[test_31]") { vector vec1{1, 1}; const vector _vec1{1, 1}; - leetcode_31::nextPermutation(vec1); + auto clas = Solution(); + clas.nextPermutation(vec1); CHECK_THAT(vec1, Equals(_vec1)); } TEST_CASE("test just one element [test_31]", "[test_31]") { vector vec1 = {1}; const vector _vec1 = {1}; - leetcode_31::nextPermutation(vec1); + auto clas = Solution(); + clas.nextPermutation(vec1); CHECK_THAT(vec1, Equals(_vec1)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_31_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_31_TEST_HPP diff --git a/algorithm/array/leetcode_334.cpp b/algorithm/array/leetcode_334.cpp index 4ee585e0..6e59ed78 100644 --- a/algorithm/array/leetcode_334.cpp +++ b/algorithm/array/leetcode_334.cpp @@ -1,33 +1,44 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_334_test.hpp" +#include +#include +#include +#include +#include namespace leetcode_334 { +using std::vector; +using std::int32_t; +#endif -bool leetcode_334::increasingTriplet(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size < 3) { - return false; - } - vector dp(nums_size, 0); - // dp[i]代表 第i个元素之前的最小元素 - // 此处可以发现其实只用到了dp[i],dp[i-1],可以做空间压缩 - dp[0] = std::numeric_limits::max(); // 第0个前面没有元素,所以置为int32_t的最大值 - int32_t maxMin{std::numeric_limits::max()}; - for (size_t i{1}; i + 1 < nums_size; ++i) { - dp[i] = std::min(dp[i - 1], nums[i - 1]); - if (nums[i] > dp[i]) { - maxMin = std::min(maxMin, nums[i]); +class Solution { +public: + bool increasingTriplet(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size < 3) { + return false; } - if (nums[i + 1] > maxMin) { - return true; + vector dp(nums_size, 0); + // dp[i]代表 第i个元素之前的最小元素 + // 此处可以发现其实只用到了dp[i],dp[i-1],可以做空间压缩 + dp[0] = std::numeric_limits::max(); // 第0个前面没有元素,所以置为int32_t的最大值 + int32_t maxMin{std::numeric_limits::max()}; + for (size_t i{1}; i + 1 < nums_size; ++i) { + dp[i] = std::min(dp[i - 1], nums[i - 1]); + if (nums[i] > dp[i]) { + maxMin = std::min(maxMin, nums[i]); + } + if (nums[i + 1] > maxMin) { + return true; + } } + return false; } - return false; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif + diff --git a/algorithm/array/leetcode_334_test.hpp b/algorithm/array/leetcode_334_test.cpp similarity index 50% rename from algorithm/array/leetcode_334_test.hpp rename to algorithm/array/leetcode_334_test.cpp index c861af63..72879118 100644 --- a/algorithm/array/leetcode_334_test.hpp +++ b/algorithm/array/leetcode_334_test.cpp @@ -1,49 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag DP //@Plan 数据结构基础 Day4 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_334_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_334_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_334_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_334_TEST_HPP #include -#include -#include -#include +#include "leetcode_334.cpp" namespace leetcode_334 { using std::vector; -struct leetcode_334 { - static bool increasingTriplet(const vector &nums); -}; - using Catch::Matchers::UnorderedEquals; TEST_CASE("test case 1 [test_334]", "[test_334]") { const vector input{1, 2, 3, 4, 5}; - CHECK(leetcode_334::increasingTriplet(input)); + Solution solution; + CHECK(solution.increasingTriplet(input)); } TEST_CASE("test case 2 [test_334]", "[test_334]") { const vector input{5, 4, 3, 2, 1}; - CHECK_FALSE(leetcode_334::increasingTriplet(input)); + Solution solution; + CHECK_FALSE(solution.increasingTriplet(input)); } TEST_CASE("test case 3 [test_334]", "[test_334]") { const vector input{1, 1, 4, 5, 1, 4}; - CHECK(leetcode_334::increasingTriplet(input)); + Solution solution; + CHECK(solution.increasingTriplet(input)); } TEST_CASE("test case 4 [test_334]", "[test_334]") { const vector input{5, 1, 6}; - CHECK_FALSE(leetcode_334::increasingTriplet(input)); + Solution solution; + CHECK_FALSE(solution.increasingTriplet(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_334_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_334_TEST_HPP diff --git a/algorithm/array/leetcode_350.cpp b/algorithm/array/leetcode_350.cpp index 4f360d85..f04f8d93 100644 --- a/algorithm/array/leetcode_350.cpp +++ b/algorithm/array/leetcode_350.cpp @@ -1,36 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_350_test.hpp" +#include #include +#include namespace leetcode_350 { +using std::vector; using std::unordered_map; +#endif -vector leetcode_350::intersect(const vector &nums1, const vector &nums2) { - const auto *nums1Ref = &nums1; - const auto *nums2Ref = &nums2; - const auto nums1_size{nums1.size()}, nums2_size{nums2.size()}; - if (nums1_size >= nums2_size) { - std::swap(nums1Ref, nums2Ref); - } - // nums1.size() < nums2.size() - unordered_map umap1; - for (const auto i: *nums1Ref) { - umap1[i]++; - } - vector will_return; - will_return.reserve(nums2_size); - for (const auto i: *nums2Ref) { - if (umap1[i] > 0) { - umap1[i]--; - will_return.push_back(i); +class Solution { +public: + vector intersect(const vector &nums1, const vector &nums2) { + const auto *nums1Ref = &nums1; + const auto *nums2Ref = &nums2; + const auto nums1_size{nums1.size()}, nums2_size{nums2.size()}; + if (nums1_size >= nums2_size) { + std::swap(nums1Ref, nums2Ref); + } + // nums1.size() < nums2.size() + unordered_map umap1; + for (const auto i: *nums1Ref) { + umap1[i]++; } + vector will_return; + will_return.reserve(nums2_size); + for (const auto i: *nums2Ref) { + if (umap1[i] > 0) { + umap1[i]--; + will_return.push_back(i); + } + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_350_test.hpp b/algorithm/array/leetcode_350_test.cpp similarity index 52% rename from algorithm/array/leetcode_350_test.hpp rename to algorithm/array/leetcode_350_test.cpp index 10927f4d..45fda780 100644 --- a/algorithm/array/leetcode_350_test.hpp +++ b/algorithm/array/leetcode_350_test.cpp @@ -1,42 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag 哈希表 //@Plan 数据结构入门 Day3 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_350_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_350_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_350_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_350_TEST_HPP #include #include #include #include +#include "leetcode_350.cpp" namespace leetcode_350 { using std::vector; -struct leetcode_350 { - static vector intersect(const vector &nums1, const vector &nums2); -}; - using Catch::Matchers::UnorderedEquals; TEST_CASE("test case 1 [test_350]", "[test_350]") { const vector input1{1, 2, 2, 1}, input2{2, 2}; const vector result{2, 2}; - CHECK_THAT(result, UnorderedEquals(leetcode_350::intersect(input1, input2))); + Solution solution; + CHECK_THAT(result, UnorderedEquals(solution.intersect(input1, input2))); } TEST_CASE("test case 2 [test_350]", "[test_350]") { const vector input1{4, 9, 5}, input2{9, 4, 9, 8, 4}; const vector result{4, 9}; - CHECK_THAT(result, UnorderedEquals(leetcode_350::intersect(input1, input2))); + Solution solution; + CHECK_THAT(result, UnorderedEquals(solution.intersect(input1, input2))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_350_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_350_TEST_HPP diff --git a/algorithm/array/leetcode_36.cpp b/algorithm/array/leetcode_36.cpp index c090762d..56531a86 100644 --- a/algorithm/array/leetcode_36.cpp +++ b/algorithm/array/leetcode_36.cpp @@ -1,56 +1,63 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_36_test.hpp" #include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_36 { +#endif + using std::unordered_set; -static constexpr const int32_t sizes_36{9}, block_36{3}; - -bool isValidSudoku_block(const vector> &board, - const int left, const int up) { - unordered_set uset; - for (int32_t i{0}; i < sizes_36; i++) { - if (uset.count(board[left + i / block_36][up + i % block_36]) == 1) { - return false; - } - if (board[left + i / block_36][up + i % block_36] != '.') { - uset.insert(board[left + i / block_36][up + i % block_36]); +using std::vector; + +class Solution { + static constexpr const int32_t sizes_36{9}, block_36{3}; + + static bool isValidSudoku_block(const vector> &board, + const int left, const int up) { + unordered_set uset; + for (int32_t i{0}; i < sizes_36; i++) { + if (uset.count(board[left + i / block_36][up + i % block_36]) == 1) { + return false; + } + if (board[left + i / block_36][up + i % block_36] != '.') { + uset.insert(board[left + i / block_36][up + i % block_36]); + } } + return true; } - return true; -} -bool isValidSudoku_corss_line(const vector> &board, const int32_t number) { - unordered_set uset1, uset2; - for (int32_t i{0}; i < sizes_36; i++) { - if (uset1.count(board[number][i]) == 1 || (uset2.count(board[i][number]) == 1)) { - return false; - } - if (board[number][i] != '.') { - uset1.insert(board[number][i]); - } - if (board[i][number] != '.') { - uset2.insert(board[i][number]); + + static bool isValidSudoku_corss_line(const vector> &board, const int32_t number) { + unordered_set uset1, uset2; + for (int32_t i{0}; i < sizes_36; i++) { + if (uset1.count(board[number][i]) == 1 || (uset2.count(board[i][number]) == 1)) { + return false; + } + if (board[number][i] != '.') { + uset1.insert(board[number][i]); + } + if (board[i][number] != '.') { + uset2.insert(board[i][number]); + } } + return true; } - return true; -} -bool leetcode_36::isValidSudoku(const vector> &board) { - for (int32_t i{0}; i < sizes_36; i++) { - if (!isValidSudoku_corss_line(board, i) || - !isValidSudoku_block(board, (i / block_36) * block_36, (i % block_36) * block_36)) { - return false; +public: + bool isValidSudoku(const vector> &board) { + for (int32_t i{0}; i < sizes_36; i++) { + if (!isValidSudoku_corss_line(board, i) || + !isValidSudoku_block(board, (i / block_36) * block_36, (i % block_36) * block_36)) { + return false; + } } + return true; } - return true; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_36_test.hpp b/algorithm/array/leetcode_36_test.cpp similarity index 76% rename from algorithm/array/leetcode_36_test.hpp rename to algorithm/array/leetcode_36_test.cpp index bd779bbe..e13f2e15 100644 --- a/algorithm/array/leetcode_36_test.hpp +++ b/algorithm/array/leetcode_36_test.cpp @@ -1,28 +1,20 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Plan 数据结构入门 Day5 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_36_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_36_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_36_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_36_TEST_HPP #include -#include + +#include "leetcode_36.cpp" #include #include namespace leetcode_36 { using std::vector; -struct leetcode_36 { - static bool isValidSudoku(const vector> &board); -}; - TEST_CASE("basic test [test_36]", "[test_36]") { const vector> vec1{ {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, @@ -34,7 +26,9 @@ TEST_CASE("basic test [test_36]", "[test_36]") { {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}}; - CHECK(leetcode_36::isValidSudoku(vec1)); + Solution solution; + CHECK(solution.isValidSudoku(vec1)); + } TEST_CASE("test reverse [test_36]", "[test_36]") { @@ -48,8 +42,9 @@ TEST_CASE("test reverse [test_36]", "[test_36]") { {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}}; - CHECK_FALSE(leetcode_36::isValidSudoku(vec1)); + Solution solution; + CHECK_FALSE(solution.isValidSudoku(vec1)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_36_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_36_TEST_HPP diff --git a/algorithm/array/leetcode_39.cpp b/algorithm/array/leetcode_39.cpp index ac1ac69a..002ed15b 100644 --- a/algorithm/array/leetcode_39.cpp +++ b/algorithm/array/leetcode_39.cpp @@ -1,14 +1,14 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_39_test.hpp" +#include #include +#include namespace leetcode_39 { +using std::vector; +#endif void combinSumTrace(vector> &combinations, const vector &candidates, vector &combination, @@ -31,12 +31,18 @@ combinSumTrace(vector> &combinations, const vector &can combinSumTrace(combinations, candidates, combination, target, index + 1); } -vector> leetcode_39::combinationSum(const vector &candidates, int32_t target) { - vector candidates_back{candidates}; - std::sort(candidates_back.begin(), candidates_back.end()); - vector> combinations; - vector combination; - combinSumTrace(combinations, candidates_back, combination, target, static_cast(0)); - return combinations; -} +class Solution { +public: + vector> combinationSum(const vector &candidates, int32_t target) { + vector candidates_back{candidates}; + std::sort(candidates_back.begin(), candidates_back.end()); + vector> combinations; + vector combination; + combinSumTrace(combinations, candidates_back, combination, target, static_cast(0)); + return combinations; + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_39_test.cpp b/algorithm/array/leetcode_39_test.cpp new file mode 100644 index 00000000..70703301 --- /dev/null +++ b/algorithm/array/leetcode_39_test.cpp @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_39_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_39_TEST_HPP + +#include +#include "leetcode_39.cpp" + +namespace leetcode_39 { + +using Catch::Matchers::UnorderedEquals; + +TEST_CASE("basic test [test_39]", "[test_39]") { + vector candidates{2, 3, 6, 7}; + const static constexpr auto target{7}; + const vector> results{{7}, + {2, 2, 3}}; + Solution solution; + CHECK_THAT(solution.combinationSum(candidates, target), UnorderedEquals(results)); +} + +TEST_CASE("basic test 2[test_39]", "[test_39]") { + vector candidates{2, 3, 5}; + const static constexpr auto target{8}; + const vector> results{{2, 3, 3}, + {2, 2, 2, 2}, + {3, 5}}; + Solution solution; + CHECK_THAT(solution.combinationSum(candidates, target), UnorderedEquals(results)); +} + +TEST_CASE("basic test 3[test_39]", "[test_39]") { + vector candidates{2}; + const static constexpr auto target{1}; + const vector> results{}; + Solution solution; + CHECK_THAT(solution.combinationSum(candidates, target), UnorderedEquals(results)); +} + +TEST_CASE("basic test 4[test_39]", "[test_39]") { + vector candidates{1}; + const static constexpr auto target{1}; + const vector> results{{1}}; + Solution solution; + CHECK_THAT(solution.combinationSum(candidates, target), UnorderedEquals(results)); +} + +TEST_CASE("basic test 5[test_39]", "[test_39]") { + vector candidates{1}; + const static constexpr auto target{2}; + const vector> results{{1, 1}}; + Solution solution; + CHECK_THAT(solution.combinationSum(candidates, target), UnorderedEquals(results)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_39_TEST_HPP diff --git a/algorithm/array/leetcode_39_test.hpp b/algorithm/array/leetcode_39_test.hpp deleted file mode 100644 index 4573097c..00000000 --- a/algorithm/array/leetcode_39_test.hpp +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_39_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_39_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_39 { -using std::vector; - -struct leetcode_39 { - static vector> combinationSum(const vector &candidates, int target); -}; - -using Catch::Matchers::UnorderedEquals; - -TEST_CASE("basic test [test_39]", "[test_39]") { - const vector candidates{2, 3, 6, 7}; - const static constexpr auto target{7}; - const vector> results{{7}, - {2, 2, 3}}; - CHECK_THAT(results, UnorderedEquals(leetcode_39::combinationSum(candidates, target))); -} - -TEST_CASE("basic test 2[test_39]", "[test_39]") { - const vector candidates{2, 3, 5}; - const static constexpr auto target{8}; - const vector> results{{2, 3, 3}, - {2, 2, 2, 2}, - {3, 5}}; - CHECK_THAT(results, UnorderedEquals(leetcode_39::combinationSum(candidates, target))); -} - -TEST_CASE("basic test 3[test_39]", "[test_39]") { - const vector candidates{2}; - const static constexpr auto target{1}; - const vector> results{}; - CHECK_THAT(results, UnorderedEquals(leetcode_39::combinationSum(candidates, target))); -} - -TEST_CASE("basic test 4[test_39]", "[test_39]") { - const vector candidates{1}; - const static constexpr auto target{1}; - const vector> results{{1}}; - CHECK_THAT(results, UnorderedEquals(leetcode_39::combinationSum(candidates, target))); -} - -TEST_CASE("basic test 5[test_39]", "[test_39]") { - const vector candidates{1}; - const static constexpr auto target{2}; - const vector> results{{1, 1}}; - CHECK_THAT(results, UnorderedEquals(leetcode_39::combinationSum(candidates, target))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_39_TEST_HPP diff --git a/algorithm/array/leetcode_40.cpp b/algorithm/array/leetcode_40.cpp index 24970548..8a6fb8aa 100644 --- a/algorithm/array/leetcode_40.cpp +++ b/algorithm/array/leetcode_40.cpp @@ -1,16 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_40_test.hpp" +#include #include #include +#include namespace leetcode_40 { +using std::vector; using std::map; +#endif + struct pair final { int32_t number; int32_t times; @@ -41,20 +42,25 @@ void combinSumTrace(vector> &combinations, const vector &c } } -vector> leetcode_40::combinationSum2(const vector &candidates, int32_t target) { - map umap; - for (const auto candidate: candidates) { - umap[candidate]++; - } - vector pairs; - pairs.reserve(umap.size()); - for (const auto[k, v]: umap) { - pairs.push_back(pair{k, v}); +class Solution { +public: + vector> combinationSum2(const vector &candidates, int32_t target) { + map umap; + for (const auto candidate: candidates) { + umap[candidate]++; + } + vector pairs; + pairs.reserve(umap.size()); + for (const auto [k, v]: umap) { + pairs.push_back(pair{k, v}); + } + vector> combinations; + vector combination; + combinSumTrace(combinations, pairs, combination, target, static_cast(0)); + return combinations; } - vector> combinations; - vector combination; - combinSumTrace(combinations, pairs, combination, target, static_cast(0)); - return combinations; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_40_test.hpp b/algorithm/array/leetcode_40_test.cpp similarity index 71% rename from algorithm/array/leetcode_40_test.hpp rename to algorithm/array/leetcode_40_test.cpp index ebf9f5fc..d0c5e61f 100644 --- a/algorithm/array/leetcode_40_test.hpp +++ b/algorithm/array/leetcode_40_test.cpp @@ -1,29 +1,20 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_40_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_40_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_40_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_40_TEST_HPP #include #include #include #include +#include "leetcode_40.cpp" namespace leetcode_40 { using std::vector; -struct leetcode_40 { - static vector> combinationSum2(const vector &candidates, int target); -}; - - using Catch::Matchers::Equals; using Catch::Matchers::UnorderedEquals; using Catch::Matchers::Contains; @@ -35,7 +26,8 @@ TEST_CASE("basic test [test_40]", "[test_40]") { {1, 2, 5}, {1, 7}, {2, 6}}; - CHECK_THAT(results, UnorderedEquals(leetcode_40::combinationSum2(candidates, target))); + Solution solution; + CHECK_THAT(solution.combinationSum2(candidates, target), UnorderedEquals(results)); } TEST_CASE("basic test 2[test_40]", "[test_40]") { @@ -43,7 +35,8 @@ TEST_CASE("basic test 2[test_40]", "[test_40]") { const static constexpr auto target{5}; const vector> results{{1, 2, 2}, {5}}; - CHECK_THAT(results, UnorderedEquals(leetcode_40::combinationSum2(candidates, target))); + Solution solution; + CHECK_THAT(solution.combinationSum2(candidates, target), UnorderedEquals(results)); } TEST_CASE("basic test 3[test_40]", "[test_40]") { @@ -54,7 +47,8 @@ TEST_CASE("basic test 3[test_40]", "[test_40]") { const static constexpr auto target{30}; const vector> results{{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,}}; - CHECK_THAT(results, UnorderedEquals(leetcode_40::combinationSum2(candidates, target))); + Solution solution; + CHECK_THAT(solution.combinationSum2(candidates, target), UnorderedEquals(results)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_40_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_40_TEST_HPP diff --git a/algorithm/array/leetcode_41.cpp b/algorithm/array/leetcode_41.cpp index 81e41812..241ef88a 100644 --- a/algorithm/array/leetcode_41.cpp +++ b/algorithm/array/leetcode_41.cpp @@ -1,50 +1,56 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_41_test.hpp" +#include +#include +#include namespace leetcode_41 { +using std::vector; +#endif -int leetcode_41::firstMissingPositive(vector &nums) { - const auto nums_size{static_cast(nums.size())}; - for (auto &value: nums) { - if (value <= 0) { - value = nums_size + 1; +class Solution { +public: + int32_t firstMissingPositive(vector &nums) { + const auto nums_size{static_cast(nums.size())}; + for (auto &value: nums) { + if (value <= 0) { + value = nums_size + 1; + } } - } - for (const auto &value: nums) { - const auto absV{std::abs(value) - 1}; - if (0 <= absV && absV < nums_size) { - nums[absV] = -1 * std::abs(nums[absV]); + for (const auto &value: nums) { + const auto absV{std::abs(value) - 1}; + if (0 <= absV && absV < nums_size) { + nums[absV] = -1 * std::abs(nums[absV]); + } } - } - nums.push_back(nums_size + 1); - for (int32_t i{0}; i < nums_size + 1; i++) { - if (0 < nums[i]) { - return (i + 1); + nums.push_back(nums_size + 1); + for (int32_t i{0}; i < nums_size + 1; i++) { + if (0 < nums[i]) { + return (i + 1); + } } + return -1; } - return -1; -} -int leetcode_41::firstMissingPositive2(vector &nums) { - const size_t maxv{nums.size()}; - vector num(nums.size() + 1, 0); - for (size_t i{0}; i < nums.size(); i++) { - if (0 < nums[i] && nums[i] <= static_cast(maxv)) { - num[nums[i] - 1] = nums[i]; + int32_t firstMissingPositive2(vector &nums) { + const size_t maxv{nums.size()}; + vector num(nums.size() + 1, 0); + for (size_t i{0}; i < nums.size(); i++) { + if (0 < nums[i] && nums[i] <= static_cast(maxv)) { + num[nums[i] - 1] = nums[i]; + } } - } - for (size_t i{0}; i < num.size(); i++) { - if (num[i] == 0) { - return static_cast(i + 1); + for (size_t i{0}; i < num.size(); i++) { + if (num[i] == 0) { + return static_cast(i + 1); + } } + return -1; } - return -1; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_41_test.hpp b/algorithm/array/leetcode_41_test.cpp similarity index 52% rename from algorithm/array/leetcode_41_test.hpp rename to algorithm/array/leetcode_41_test.cpp index 7b5bb2a2..22b355e9 100644 --- a/algorithm/array/leetcode_41_test.hpp +++ b/algorithm/array/leetcode_41_test.cpp @@ -1,68 +1,63 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_41_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_41_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_41_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_41_TEST_HPP #include #include #include #include +#include "leetcode_41.cpp" namespace leetcode_41 { using std::vector; -struct leetcode_41 { - static int firstMissingPositive(vector &nums); - - static int firstMissingPositive2(vector &nums); -}; - TEST_CASE("basic test [test_41]", "[test_41]") { const vector cinput{1, 2, 0}; vector input{cinput}, input2{cinput}; const static constexpr auto result{3}; - CHECK(result == leetcode_41::firstMissingPositive(input)); - CHECK(result == leetcode_41::firstMissingPositive2(input2)); + Solution solution; + CHECK(result == solution.firstMissingPositive(input)); + CHECK(result == solution.firstMissingPositive2(input2)); } TEST_CASE("basic test 2 [test_41]", "[test_41]") { const vector cinput{3, 4, -1, 1}; vector input{cinput}, input2{cinput}; const static constexpr auto result{2}; - CHECK(result == leetcode_41::firstMissingPositive(input)); - CHECK(result == leetcode_41::firstMissingPositive2(input2)); + Solution solution; + CHECK(result == solution.firstMissingPositive(input)); + CHECK(result == solution.firstMissingPositive2(input2)); } TEST_CASE("basic test 3 [test_41]", "[test_41]") { const vector cinput{7, 8, 9, 11, 12}; vector input{cinput}, input2{cinput}; const static constexpr auto result{1}; - CHECK(result == leetcode_41::firstMissingPositive(input)); - CHECK(result == leetcode_41::firstMissingPositive2(input2)); + Solution solution; + CHECK(result == solution.firstMissingPositive(input)); + CHECK(result == solution.firstMissingPositive2(input2)); } TEST_CASE("basic test 4 [test_41]", "[test_41]") { const vector cinput{1}; vector input{cinput}, input2{cinput}; const static constexpr auto result{2}; - CHECK(result == leetcode_41::firstMissingPositive(input)); - CHECK(result == leetcode_41::firstMissingPositive2(input2)); + Solution solution; + CHECK(result == solution.firstMissingPositive(input)); + CHECK(result == solution.firstMissingPositive2(input2)); } TEST_CASE("basic test 6 [test_41]", "[test_41]") { const vector cinput{0, 1, 2}; vector input{cinput}, input2{cinput}; const static constexpr auto result{3}; - CHECK(result == leetcode_41::firstMissingPositive(input)); - CHECK(result == leetcode_41::firstMissingPositive2(input2)); + Solution solution; + CHECK(result == solution.firstMissingPositive(input)); + CHECK(result == solution.firstMissingPositive2(input2)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_41_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_41_TEST_HPP diff --git a/algorithm/array/leetcode_448.cpp b/algorithm/array/leetcode_448.cpp index afd43db5..22fcf40e 100644 --- a/algorithm/array/leetcode_448.cpp +++ b/algorithm/array/leetcode_448.cpp @@ -1,27 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_448_test.hpp" +#include +#include +#include namespace leetcode_448 { +using std::vector; +#endif -vector leetcode_448::findDisappearedNumbers(const vector &nums) { - vector res, num{nums}; - const auto nums_size{nums.size()}; - for (size_t i{0}; i < nums_size; i++) { - const int32_t m = abs(num[i]) - 1; // index start from 0 - num[m] = num[m] > 0 ? -num[m] : num[m]; - } - for (size_t i{0}; i < nums_size; i++) { - if (num[i] > 0) { - res.push_back(static_cast(i + 1)); +class Solution { +public: + vector findDisappearedNumbers(const vector &nums) { + vector res, num{nums}; + const auto nums_size{nums.size()}; + for (size_t i{0}; i < nums_size; i++) { + const int32_t m = abs(num[i]) - 1; // index start from 0 + num[m] = num[m] > 0 ? -num[m] : num[m]; } + for (size_t i{0}; i < nums_size; i++) { + if (num[i] > 0) { + res.push_back(static_cast(i + 1)); + } + } + return res; } - return res; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_448_test.hpp b/algorithm/array/leetcode_448_test.cpp similarity index 50% rename from algorithm/array/leetcode_448_test.hpp rename to algorithm/array/leetcode_448_test.cpp index 9b4051f3..ac50f6da 100644 --- a/algorithm/array/leetcode_448_test.hpp +++ b/algorithm/array/leetcode_448_test.cpp @@ -1,41 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag 哈希表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_448_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_448_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_448_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_448_TEST_HPP #include #include #include #include +#include "leetcode_448.cpp" namespace leetcode_448 { using std::vector; -struct leetcode_448 { - static vector findDisappearedNumbers(const vector &nums); -}; - using Catch::Matchers::UnorderedEquals; TEST_CASE("test case 1 [test_448]", "[test_448]") { const vector input{4, 3, 2, 7, 8, 2, 3, 1}; const vector result{5, 6}; - CHECK_THAT(result, UnorderedEquals(leetcode_448::findDisappearedNumbers(input))); + Solution solution; + CHECK_THAT(solution.findDisappearedNumbers(input), UnorderedEquals(result)); } TEST_CASE("test case 2 [test_448]", "[test_448]") { const vector input{1, 1}; const vector result{2}; - CHECK_THAT(result, UnorderedEquals(leetcode_448::findDisappearedNumbers(input))); + Solution solution; + CHECK_THAT(solution.findDisappearedNumbers(input), UnorderedEquals(result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_448_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_448_TEST_HPP diff --git a/algorithm/array/leetcode_48.cpp b/algorithm/array/leetcode_48.cpp index 425bffca..c4dd8ef1 100644 --- a/algorithm/array/leetcode_48.cpp +++ b/algorithm/array/leetcode_48.cpp @@ -1,30 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_48_test.hpp" +#include +#include +#include namespace leetcode_48 { +using std::vector; +#endif -void leetcode_48::rotate(vector> &matrix) { - const auto lines = matrix.size(); - const size_t actions = lines / 2; - for (size_t i{0}; i < actions; ++i) { - const auto right_end{lines - 1 - i}; - for (size_t j{i}; j < right_end; ++j) { - const auto fst = matrix[i][j]; // 观察法罢了 - const auto snd = matrix[lines - j - 1][i]; - const auto trd = matrix[lines - 1 - i][lines - 1 - j]; - const auto fth = matrix[j][lines - i - 1]; - matrix[i][j] = snd; - matrix[lines - j - 1][i] = trd; - matrix[lines - 1 - i][lines - 1 - j] = fth; - matrix[j][lines - i - 1] = fst; +class Solution { +public: + void rotate(vector> &matrix) { + const auto lines = matrix.size(); + const size_t actions = lines / 2; + for (size_t i{0}; i < actions; ++i) { + const auto right_end{lines - 1 - i}; + for (size_t j{i}; j < right_end; ++j) { + const auto fst = matrix[i][j]; // 观察法罢了 + const auto snd = matrix[lines - j - 1][i]; + const auto trd = matrix[lines - 1 - i][lines - 1 - j]; + const auto fth = matrix[j][lines - i - 1]; + matrix[i][j] = snd; + matrix[lines - j - 1][i] = trd; + matrix[lines - 1 - i][lines - 1 - j] = fth; + matrix[j][lines - i - 1] = fst; + } } } -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_485.cpp b/algorithm/array/leetcode_485.cpp index 55366d75..dce531b3 100644 --- a/algorithm/array/leetcode_485.cpp +++ b/algorithm/array/leetcode_485.cpp @@ -1,25 +1,31 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_485_test.hpp" +#include +#include +#include namespace leetcode_485 { +using std::vector; +#endif -int32_t leetcode_485::findMaxConsecutiveOnes(const vector &nums) { - int32_t val{0}, willreturn{-1}; - for (const auto i: nums) { - if (i != 0) { - val++; - } else { - willreturn = std::max(val, willreturn); - val = 0; +class Solution { +public: + int32_t findMaxConsecutiveOnes(const vector &nums) { + int32_t val{0}, willreturn{-1}; + for (const auto i: nums) { + if (i != 0) { + val++; + } else { + willreturn = std::max(val, willreturn); + val = 0; + } } + return std::max(val, willreturn);; } - return std::max(val, willreturn);; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_485_test.hpp b/algorithm/array/leetcode_485_test.cpp similarity index 53% rename from algorithm/array/leetcode_485_test.hpp rename to algorithm/array/leetcode_485_test.cpp index 36d9bfe7..e9e36430 100644 --- a/algorithm/array/leetcode_485_test.hpp +++ b/algorithm/array/leetcode_485_test.cpp @@ -1,43 +1,38 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_485_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_485_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_485_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_485_TEST_HPP #include #include #include #include +#include "leetcode_485.cpp" namespace leetcode_485 { using std::vector; -struct leetcode_485 { - static int32_t findMaxConsecutiveOnes(const vector &nums); -}; - TEST_CASE("test case 1 [test_485]", "[test_485]") { const vector input{1, 0, 1, 1, 0, 1}; static constexpr const auto result{2}; - CHECK(result == leetcode_485::findMaxConsecutiveOnes(input)); + Solution solution; + CHECK(result == solution.findMaxConsecutiveOnes(input)); } TEST_CASE("test case 2 [test_485]", "[test_485]") { const vector input{1, 1, 0, 1, 1, 1}; static constexpr const auto result{3}; - CHECK(result == leetcode_485::findMaxConsecutiveOnes(input)); + Solution solution; + CHECK(result == solution.findMaxConsecutiveOnes(input)); } TEST_CASE("test case 3 [test_485]", "[test_485]") { const vector input{1}; static constexpr const auto result{1}; - CHECK(result == leetcode_485::findMaxConsecutiveOnes(input)); + Solution solution; + CHECK(result == solution.findMaxConsecutiveOnes(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_485_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_485_TEST_HPP diff --git a/algorithm/array/leetcode_48_test.cpp b/algorithm/array/leetcode_48_test.cpp new file mode 100644 index 00000000..f40bb3af --- /dev/null +++ b/algorithm/array/leetcode_48_test.cpp @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_48_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_48_TEST_HPP + +#include + +#include "leetcode_48.cpp" + +namespace leetcode_48 { +using std::vector; + +using Catch::Matchers::Equals; + +TEST_CASE("basic test [test_48]", "[test_48]") { + vector> input{ + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + const vector> result{ + {7, 4, 1}, + {8, 5, 2}, + {9, 6, 3} + }; + Solution solution; + solution.rotate(input); + CHECK_THAT(result, Equals(input)); +} + +TEST_CASE("basic test 2 [test_48]", "[test_48]") { + vector> input{ + {5, 1, 9, 11}, + {2, 4, 8, 10}, + {13, 3, 6, 7}, + {15, 14, 12, 16} + }; + const vector> result{ + {15, 13, 2, 5}, + {14, 3, 4, 1}, + {12, 6, 8, 9}, + {16, 7, 10, 11} + }; + Solution solution; + solution.rotate(input); + CHECK_THAT(result, Equals(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_48_TEST_HPP diff --git a/algorithm/array/leetcode_48_test.hpp b/algorithm/array/leetcode_48_test.hpp deleted file mode 100644 index c37343aa..00000000 --- a/algorithm/array/leetcode_48_test.hpp +++ /dev/null @@ -1,65 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_48_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_48_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_48 { -using std::vector; - -struct leetcode_48 { - static vector> rotate_(const vector> &matrix) { - vector> mut{matrix}; - rotate(mut); - return mut; - } - - static void rotate(vector> &matrix); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("basic test [test_48]", "[test_48]") { - const vector> input{ - {1, 2, 3}, - {4, 5, 6}, - {7, 8, 9} - }; - const vector> result{ - {7, 4, 1}, - {8, 5, 2}, - {9, 6, 3} - }; - CHECK_THAT(result, Equals(leetcode_48::rotate_(input))); -} - -TEST_CASE("basic test 2 [test_48]", "[test_48]") { - const vector> input{ - {5, 1, 9, 11}, - {2, 4, 8, 10}, - {13, 3, 6, 7}, - {15, 14, 12, 16} - }; - const vector> result{ - {15, 13, 2, 5}, - {14, 3, 4, 1}, - {12, 6, 8, 9}, - {16, 7, 10, 11} - }; - CHECK_THAT(result, Equals(leetcode_48::rotate_(input))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_48_TEST_HPP diff --git a/algorithm/array/leetcode_500.cpp b/algorithm/array/leetcode_500.cpp index 84823a83..9ed899b5 100644 --- a/algorithm/array/leetcode_500.cpp +++ b/algorithm/array/leetcode_500.cpp @@ -1,38 +1,45 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_500_test.hpp" +#include +#include +#include +#include namespace leetcode_500 { +using std::vector; +using std::string; +using std::array; +#endif + -vector leetcode_500::findWords(const vector &words) { - static constexpr const array chars = { - 2, 3, 3, 2, 1, 2, 2, 2, 1, 2, - 2, 2, 3, 3, 1, 1, 1, 1, 2, 1, - 1, 3, 1, 3, 1, 3, - 0, 0, 0, 0, 0, 0, - 2, 3, 3, 2, 1, 2, 2, 2, 1, 2, - 2, 2, 3, 3, 1, 1, 1, 1, 2, 1, - 1, 3, 1, 3, 1, 3}; - const auto words_size{words.size()}; - vector willreturn; - for (size_t i{0}; i < words_size; i++) { - bool judge = true; - for (size_t j{0}, size2{words[i].size() - 1}; j < size2; j++) { - if (chars[words[i][j] - 65] != chars[words[i][j + 1] - 65]) { - judge = false; - break; +class Solution { +public: + vector findWords(const vector &words) { + static constexpr const array chars = { + 2, 3, 3, 2, 1, 2, 2, 2, 1, 2, + 2, 2, 3, 3, 1, 1, 1, 1, 2, 1, + 1, 3, 1, 3, 1, 3, + 0, 0, 0, 0, 0, 0, + 2, 3, 3, 2, 1, 2, 2, 2, 1, 2, + 2, 2, 3, 3, 1, 1, 1, 1, 2, 1, + 1, 3, 1, 3, 1, 3}; + const auto words_size{words.size()}; + vector willreturn; + for (size_t i{0}; i < words_size; i++) { + bool judge = true; + for (size_t j{0}, size2{words[i].size() - 1}; j < size2; j++) { + if (chars[words[i][j] - 65] != chars[words[i][j + 1] - 65]) { + judge = false; + break; + } + } + if (judge) { + willreturn.push_back(words[i]); } } - if (judge) { - willreturn.push_back(words[i]); - } + return willreturn; } - return willreturn; -} - +}; } diff --git a/algorithm/array/leetcode_500_test.cpp b/algorithm/array/leetcode_500_test.cpp new file mode 100644 index 00000000..8c20158a --- /dev/null +++ b/algorithm/array/leetcode_500_test.cpp @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 暴力枚举 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_500_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_500_TEST_HPP + +#include "leetcode_500.cpp" +#include + +namespace leetcode_500 { +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_500]", "[test_500]") { + auto sol = Solution(); + static constexpr const std::array input{"Metal", "Gear", "Soild", "Venom", "Phantom", "Pain"}; + const std::vector result{}; + CHECK_THAT(result, Equals(sol.findWords({std::cbegin(input), std::cend(input)}))); +} + +TEST_CASE("test case 2 [test_500]", "[test_500]") { + auto sol = Solution(); + static constexpr const std::array input{"Hello", "Alaska", "Dad", "Peace"}; + const std::vector result{"Alaska", "Dad"}; + CHECK_THAT(result, Equals(sol.findWords({std::cbegin(input), std::cend(input)}))); +} + +TEST_CASE("test case 3 [test_500]", "[test_500]") { + auto sol = Solution(); + static constexpr const std::array input{"omk", "adsdf", "sfd"}; + const std::vector result{"adsdf", "sfd"}; + CHECK_THAT(result, Equals(sol.findWords({std::cbegin(input), std::cend(input)}))); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_500_TEST_HPP diff --git a/algorithm/array/leetcode_500_test.hpp b/algorithm/array/leetcode_500_test.hpp deleted file mode 100644 index 16e42125..00000000 --- a/algorithm/array/leetcode_500_test.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 暴力枚举 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_500_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_500_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_500 { -using std::array; -using std::vector; - -struct leetcode_500 { - static vector findWords(const vector &words); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_500]", "[test_500]") { - static constexpr const std::array input{"Metal", "Gear", "Soild", "Venom", "Phantom", - "Pain"}; - - const vector result{}; - CHECK_THAT(result, Equals(leetcode_500::findWords({std::cbegin(input), std::cend(input)}))); -} - -TEST_CASE("test case 2 [test_500]", "[test_500]") { - static constexpr const std::array input{"Hello", "Alaska", "Dad", "Peace"}; - - const vector result{"Alaska", "Dad"}; - CHECK_THAT(result, Equals(leetcode_500::findWords({std::cbegin(input), std::cend(input)}))); -} - -TEST_CASE("test case 3 [test_500]", "[test_500]") { - static constexpr const std::array input{"omk", "adsdf", "sfd"}; - - const vector result{"adsdf", "sfd"}; - CHECK_THAT(result, Equals(leetcode_500::findWords({std::cbegin(input), std::cend(input)}))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_500_TEST_HPP diff --git a/algorithm/array/leetcode_532.cpp b/algorithm/array/leetcode_532.cpp index 05965640..15402c55 100644 --- a/algorithm/array/leetcode_532.cpp +++ b/algorithm/array/leetcode_532.cpp @@ -1,34 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_532_test.hpp" +#include #include #include +#include namespace leetcode_532 { +using std::vector; using std::unordered_map; -int32_t leetcode_532::findPairs(const vector &nums, int32_t k) { - if (k < 0) { - return 0; - } - unordered_map umap; - int count = 0; - for (const auto num: nums) { - umap[num]++; - } - if (k == 0) { - return std::accumulate(umap.cbegin(), umap.cend(), 0, - [](const auto base, const auto value) { return base + (value.second > 1); }); - } - for (auto i: umap) { - count += (umap.count(i.first + k) > 0); +#endif + + +class Solution { +public: + int32_t findPairs(const vector &nums, int32_t k) { + if (k < 0) { + return 0; + } + unordered_map umap; + int32_t count = 0; + for (const auto num: nums) { + umap[num]++; + } + if (k == 0) { + return std::accumulate(umap.cbegin(), umap.cend(), 0, + [](const auto base, const auto value) { return base + (value.second > 1); }); + } + for (auto i: umap) { + count += (umap.count(i.first + k) > 0); + } + return count; } - return count; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif + diff --git a/algorithm/array/leetcode_532_test.cpp b/algorithm/array/leetcode_532_test.cpp new file mode 100644 index 00000000..8e47ddb0 --- /dev/null +++ b/algorithm/array/leetcode_532_test.cpp @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 暴力枚举 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_532_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_532_TEST_HPP + +#include "leetcode_532.cpp" +#include + +namespace leetcode_532 { + +TEST_CASE("test case 1 [test_532]", "[test_532]") { + auto sol = Solution(); + std::vector input{3, 1, 4, 1, 5}; + static constexpr const auto k{2}, result{2}; + CHECK(result == sol.findPairs(input, k)); +} + +TEST_CASE("test case 2 [test_532]", "[test_532]") { + auto sol = Solution(); + std::vector input{3, 1, 4, 2, 5}; + static constexpr const auto k{1}, result{4}; + CHECK(result == sol.findPairs(input, k)); +} + +TEST_CASE("test case 3 [test_532]", "[test_532]") { + auto sol = Solution(); + std::vector input{1, 3, 1, 5, 4}; + static constexpr const auto k{0}, result{1}; + CHECK(result == sol.findPairs(input, k)); +} + +TEST_CASE("test case 4 [test_532]", "[test_532]") { + auto sol = Solution(); + std::vector input{1, 2, 4, 4, 3, 3, 0, 9, 2, 3}; + static constexpr const auto k{3}, result{2}; + CHECK(result == sol.findPairs(input, k)); +} + +TEST_CASE("test case 5 [test_532]", "[test_532]") { + auto sol = Solution(); + std::vector input{-1, -2, -3}; + static constexpr const auto k{1}, result{2}; + CHECK(result == sol.findPairs(input, k)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_532_TEST_HPP diff --git a/algorithm/array/leetcode_532_test.hpp b/algorithm/array/leetcode_532_test.hpp deleted file mode 100644 index fb1aa99c..00000000 --- a/algorithm/array/leetcode_532_test.hpp +++ /dev/null @@ -1,57 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 暴力枚举 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_532_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_532_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_532 { -using std::vector; - -struct leetcode_532 { - static int32_t findPairs(const vector &nums, int32_t k); -}; - -TEST_CASE("test case 1 [test_532]", "[test_532]") { - const vector input{3, 1, 4, 1, 5}; - static constexpr const auto k{2}, result{2}; - CHECK(result == leetcode_532::findPairs(input, k)); -} - -TEST_CASE("test case 2 [test_532]", "[test_532]") { - const vector input{3, 1, 4, 2, 5}; - static constexpr const auto k{1}, result{4}; - CHECK(result == leetcode_532::findPairs(input, k)); -} - -TEST_CASE("test case 3 [test_532]", "[test_532]") { - const vector input{1, 3, 1, 5, 4}; - static constexpr const auto k{0}, result{1}; - CHECK(result == leetcode_532::findPairs(input, k)); -} - -TEST_CASE("test case 4 [test_532]", "[test_532]") { - const vector input{1, 2, 4, 4, 3, 3, 0, 9, 2, 3}; - static constexpr const auto k{3}, result{2}; - CHECK(result == leetcode_532::findPairs(input, k)); -} - -TEST_CASE("test case 5 [test_532]", "[test_532]") { - const vector input{-1, -2, -3}; - static constexpr const auto k{1}, result{2}; - CHECK(result == leetcode_532::findPairs(input, k)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_532_TEST_HPP diff --git a/algorithm/array/leetcode_56.cpp b/algorithm/array/leetcode_56.cpp index 5e434a39..35cd998c 100644 --- a/algorithm/array/leetcode_56.cpp +++ b/algorithm/array/leetcode_56.cpp @@ -1,35 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_56_test.hpp" +#include +#include +#include namespace leetcode_56 { +using std::vector; +#endif -vector> leetcode_56::merge(const vector> &intervals) { - vector> nums{intervals}; - const size_t nums_size{nums.size()}; - if (nums_size <= 1) { - return nums; - } - std::sort(std::begin(nums), std::end(nums), [](const auto &v1, const auto &v2) { - return v1[0] < v2[0]; - }); - vector> will_return; - int32_t begin{nums[0][0]}, end{nums[0][1]}; - for (size_t order{1}; order < nums_size; order++) { - if (end >= nums[order][0]) { - end = std::max(end, nums[order][1]); - } else { - will_return.push_back({begin, end}); - begin = nums[order][0]; - end = nums[order][1]; +class Solution { +public: + vector> merge(const vector> &intervals) { + vector> nums{intervals}; + const size_t nums_size{nums.size()}; + if (nums_size <= 1) { + return nums; + } + std::sort(std::begin(nums), std::end(nums), [](const auto &v1, const auto &v2) { + return v1[0] < v2[0]; + }); + vector> will_return; + int32_t begin{nums[0][0]}, end{nums[0][1]}; + for (size_t order{1}; order < nums_size; order++) { + if (end >= nums[order][0]) { + end = std::max(end, nums[order][1]); + } else { + will_return.push_back({begin, end}); + begin = nums[order][0]; + end = nums[order][1]; + } } + will_return.push_back({begin, end}); + return will_return; } - will_return.push_back({begin, end}); - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_560.cpp b/algorithm/array/leetcode_560.cpp index 1306addb..66303c4a 100644 --- a/algorithm/array/leetcode_560.cpp +++ b/algorithm/array/leetcode_560.cpp @@ -1,32 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_560_test.hpp" +#include #include namespace leetcode_560 { +using std::vector; using std::unordered_map; +#endif -int32_t leetcode_560::subarraySum(const vector &nums, int32_t k) { - const auto nums_size{nums.size()}; - int32_t will_return{0}; - if (nums_size == 0) { +class Solution { +public: + int32_t subarraySum(const vector &nums, int32_t k) { + const auto nums_size{nums.size()}; + int32_t will_return{0}; + if (nums_size == 0) { + return will_return; + } + // map里存的不是[x,y]的值,而是前缀和的值 + unordered_map umap{}; + int32_t pre{0}; + for (const auto num: nums) { + pre = pre + num; + will_return += umap[pre - k]; // [0,i] - k == [0,?] + will_return += (pre == k); // 不需要计算前缀和,自身就是 + umap[pre] += 1; + } return will_return; } - // map里存的不是[x,y]的值,而是前缀和的值 - unordered_map umap{}; - int32_t pre{0}; - for (const auto num: nums) { - pre = pre + num; - will_return += umap[pre - k]; // [0,i] - k == [0,?] - will_return += (pre == k); // 不需要计算前缀和,自身就是 - umap[pre] += 1; - } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_560_test.hpp b/algorithm/array/leetcode_560_test.cpp similarity index 98% rename from algorithm/array/leetcode_560_test.hpp rename to algorithm/array/leetcode_560_test.cpp index 320cdadc..d044344e 100644 --- a/algorithm/array/leetcode_560_test.hpp +++ b/algorithm/array/leetcode_560_test.cpp @@ -1,54 +1,51 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 //@Plan 数据结构基础 Day4 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_560_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_560_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_560_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_560_TEST_HPP #include #include #include #include -namespace leetcode_560 { -using std::vector; - -struct leetcode_560 { - static int32_t subarraySum(const vector &nums, int32_t k); -}; +#include "leetcode_560.cpp" +namespace leetcode_560 { using Catch::Matchers::Equals; + TEST_CASE("test case 5 [test_560]", "[test_560]") { const vector input{1}; static constexpr const auto k{0}; static constexpr const auto result{0}; - CHECK(result == leetcode_560::subarraySum(input, k)); + Solution solution; + CHECK(result == solution.subarraySum(input, k)); } + TEST_CASE("test case 1 [test_560]", "[test_560]") { const vector input{1, 1, 1}; static constexpr const auto k{2}; static constexpr const auto result{2}; - CHECK(result == leetcode_560::subarraySum(input, k)); + Solution solution; + CHECK(result == solution.subarraySum(input, k)); } TEST_CASE("test case 2 [test_560]", "[test_560]") { const vector input{1, 2, 3}; static constexpr const auto k{3}; static constexpr const auto result{2}; - CHECK(result == leetcode_560::subarraySum(input, k)); + Solution solution; + CHECK(result == solution.subarraySum(input, k)); } TEST_CASE("test case 3 [test_560]", "[test_560]") { const vector input{1, 1, 4, 5, 1, 4}; static constexpr const auto k{9}; static constexpr const auto result{1}; - CHECK(result == leetcode_560::subarraySum(input, k)); + Solution solution; + CHECK(result == solution.subarraySum(input, k)); } TEST_CASE("test case 4 [test_560]", "[test_560]") { @@ -562,11 +559,13 @@ TEST_CASE("test case 4 [test_560]", "[test_560]") { 497, 919, 26, 609, 815, -411, -973, -698, -880, 821, -486, -173, 183, -294, 658, 6, 214, -321, 766, -524, -93, -125, -389, 311, -147, 84, 393, 480, 884, -959, -120, -848, 83, -499, 904, 43, 654, 150, 494, 199, -681, 516, -744, 950, 871, 60, 75, -705, 893, 545, 485, -997, -52, 820, 417, -899, 561, -593, -593, 909, - -942, 649, -893, -990, 972, -698, 363, 164, 404, -240, -747, 743, 461, -82, 292, 176, 290}; // TODO, transfer it to a .test.in file + -942, 649, -893, -990, 972, -698, 363, 164, 404, -240, -747, 743, 461, -82, 292, 176, + 290}; // TODO, transfer it to a .test.in file static constexpr const auto k{-93}; static constexpr const auto result{1025}; - CHECK(result == leetcode_560::subarraySum(input, k)); + Solution solution; + CHECK(result == solution.subarraySum(input, k)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_560_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_560_TEST_HPP diff --git a/algorithm/array/leetcode_561.cpp b/algorithm/array/leetcode_561.cpp index 76004a04..59a13ab0 100644 --- a/algorithm/array/leetcode_561.cpp +++ b/algorithm/array/leetcode_561.cpp @@ -1,23 +1,29 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_561_test.hpp" +#include +#include +#include namespace leetcode_561 { +using std::vector; +#endif -int32_t leetcode_561::arrayPairSum(const vector &nums) { - const size_t nums_size{nums.size()}; - vector input{nums}; - std::sort(input.begin(), input.end()); - int32_t temp{0}; - for (size_t i{0}; i < nums_size; i += 2) { - temp += input[i]; +class Solution { +public: + int32_t arrayPairSum(std::vector &nums) { + const size_t nums_size{nums.size()}; + std::sort(nums.begin(), nums.end()); + int32_t temp{0}; + for (size_t i{0}; i < nums_size; i += 2) { + temp += nums[i]; + } + return temp; } - return temp; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_561_test.cpp b/algorithm/array/leetcode_561_test.cpp new file mode 100644 index 00000000..b242b90c --- /dev/null +++ b/algorithm/array/leetcode_561_test.cpp @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_561_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_561_TEST_HPP + +#include +#include "leetcode_561.cpp" + +namespace leetcode_561 { +TEST_CASE("test case 1 [test_561]", "[test_561]") { + std::vector input{1, 1, 4, 5, 1, 4}; + static constexpr const auto result{6}; + Solution solution; + CHECK(result == solution.arrayPairSum(input)); +} + +TEST_CASE("test case 2 [test_561]", "[test_561]") { + std::vector input{1, 4, 3, 2}; + static constexpr const auto result{4}; + Solution solution; + CHECK(result == solution.arrayPairSum(input)); +} + +TEST_CASE("test case 3 [test_561]", "[test_561]") { + std::vector input{6, 2, 6, 5, 1, 2}; + static constexpr const auto result{9}; + Solution solution; + CHECK(result == solution.arrayPairSum(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_561_TEST_HPP diff --git a/algorithm/array/leetcode_561_test.hpp b/algorithm/array/leetcode_561_test.hpp deleted file mode 100644 index 4cea5646..00000000 --- a/algorithm/array/leetcode_561_test.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_561_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_561_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_561 { -using std::vector; - -struct leetcode_561 { - static int32_t arrayPairSum(const vector &nums); -}; - -TEST_CASE("test case 1 [test_561]", "[test_561]") { - const vector input{1, 1, 4, 5, 1, 4}; - static constexpr const auto result{6}; - CHECK(result == leetcode_561::arrayPairSum(input)); -} - -TEST_CASE("test case 2 [test_561]", "[test_561]") { - const vector input{1, 4, 3, 2}; - static constexpr const auto result{4}; - CHECK(result == leetcode_561::arrayPairSum(input)); -} - -TEST_CASE("test case 3 [test_561]", "[test_561]") { - const vector input{6, 2, 6, 5, 1, 2}; - static constexpr const auto result{9}; - CHECK(result == leetcode_561::arrayPairSum(input)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_561_TEST_HPP diff --git a/algorithm/array/leetcode_566.cpp b/algorithm/array/leetcode_566.cpp index ee8414b0..0697e42c 100644 --- a/algorithm/array/leetcode_566.cpp +++ b/algorithm/array/leetcode_566.cpp @@ -1,27 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_566_test.hpp" +#include +#include namespace leetcode_566 { +using std::vector; +#endif -vector> leetcode_566::matrixReshape(const vector> &mat, int32_t r, int32_t c) { - const auto lev1{mat.size()}, lev2{mat.front().size()}; - if (r * c - lev1 * lev2 != 0) { - return vector>{mat}; - } - vector> willreturn(r, vector(c)); - for (int32_t i{0}, sum{0}; i < r; i++) { - for (int32_t j{0}; j < c; j++, sum++) { - willreturn[i][j] = mat[sum / lev2][sum % lev2]; +class Solution { +public: + vector> matrixReshape(const vector> &mat, int32_t r, int32_t c) { + const auto lev1{mat.size()}, lev2{mat.front().size()}; + if (r * c - lev1 * lev2 != 0) { + return vector>{mat}; + } + vector> willreturn(r, vector(c)); + for (int32_t i{0}, sum{0}; i < r; i++) { + for (int32_t j{0}; j < c; j++, sum++) { + willreturn[i][j] = mat[sum / lev2][sum % lev2]; + } } + return willreturn; } - return willreturn; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_566_test.cpp b/algorithm/array/leetcode_566_test.cpp new file mode 100644 index 00000000..2de8069a --- /dev/null +++ b/algorithm/array/leetcode_566_test.cpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Plan 数据结构入门 Day4 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_566_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_566_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_566.cpp" + +namespace leetcode_566 { +using std::vector; + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_566]", "[test_566]") { + vector> input{{1, 2}, + {3, 4}}; + static constexpr const auto r{1}, c{4}; + const vector> result{{1, 2, 3, 4}}; + Solution solution; + CHECK_THAT(solution.matrixReshape(input, r, c), Equals(result)); +} + +TEST_CASE("test case 2 [test_566]", "[test_566]") { + vector> input{{1, 2}, + {3, 4}}; + static constexpr const auto r{2}, c{4}; + const vector> result{input}; + Solution solution; + CHECK_THAT(solution.matrixReshape(input, r, c), Equals(result)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_566_TEST_HPP diff --git a/algorithm/array/leetcode_566_test.hpp b/algorithm/array/leetcode_566_test.hpp deleted file mode 100644 index 64617103..00000000 --- a/algorithm/array/leetcode_566_test.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Plan 数据结构入门 Day4 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_566_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_566_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_566 { -using std::vector; - -struct leetcode_566 { - static vector> matrixReshape(const vector> &mat, int32_t r, int32_t c); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_566]", "[test_566]") { - const vector> input{{1, 2}, - {3, 4}}; - static constexpr const auto r{1}, c{4}; - const vector> result{{1, 2, 3, 4}}; - CHECK_THAT(result, Equals(leetcode_566::matrixReshape(input, r, c))); -} - -TEST_CASE("test case 2 [test_566]", "[test_566]") { - const vector> input{{1, 2}, - {3, 4}}; - static constexpr const auto r{2}, c{4}; - const vector> result{input}; - CHECK_THAT(result, Equals(leetcode_566::matrixReshape(input, r, c))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_566_TEST_HPP diff --git a/algorithm/array/leetcode_56_test.hpp b/algorithm/array/leetcode_56_test.cpp similarity index 60% rename from algorithm/array/leetcode_56_test.hpp rename to algorithm/array/leetcode_56_test.cpp index d1c7d6c3..c14eecb5 100644 --- a/algorithm/array/leetcode_56_test.hpp +++ b/algorithm/array/leetcode_56_test.cpp @@ -1,28 +1,20 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_56_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_56_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_56_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_56_TEST_HPP #include #include #include #include +#include "leetcode_56.cpp" namespace leetcode_56 { using std::vector; -struct leetcode_56 { - static vector> merge(const vector> &intervals); -}; - using Catch::Matchers::Equals; TEST_CASE("1 {test_56}", "{test_56}") { @@ -31,14 +23,16 @@ TEST_CASE("1 {test_56}", "{test_56}") { {8, 10}, {15, 18}}; const vector> result{{{1, 6}, {8, 10}, {15, 18}}}; - CHECK_THAT(leetcode_56::merge(inputs), Equals(result)); + Solution solution; + CHECK_THAT(solution.merge(inputs), Equals(result)); } TEST_CASE("2 {test_56}", "{test_56}") { const vector> inputs{{1, 4}, {4, 5}}; const vector> result{{{1, 5}}}; - CHECK_THAT(leetcode_56::merge(inputs), Equals(result)); + Solution solution; + CHECK_THAT(solution.merge(inputs), Equals(result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_56_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_56_TEST_HPP diff --git a/algorithm/array/leetcode_581.cpp b/algorithm/array/leetcode_581.cpp index d5af157d..2589d517 100644 --- a/algorithm/array/leetcode_581.cpp +++ b/algorithm/array/leetcode_581.cpp @@ -1,43 +1,55 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_581_test.hpp" #include +#include +#include +#include namespace leetcode_581 { +using std::vector; +using std::unordered_map; -int32_t leetcode_581::findUnsortedSubarray(const vector &nums) { - const auto nums_size{nums.size()}; - vector nums2{nums}; - std::sort(nums2.begin(), nums2.end()); - size_t left{0}, right{nums.size()}; - for (size_t i{0}; i < nums_size && nums2[i] == nums[i]; i++, left++) {} - for (size_t i{nums_size}; i > 0 && nums2[i - 1] == nums[i - 1]; i--, right--) {} - return std::max(0, static_cast(right - left)); -} +#endif -int32_t leetcode_581::findUnsortedSubarray2(const vector &nums) { - const auto nums_size{nums.size()}; - size_t left{nums.size() - 1}, right{0}; - int32_t maxV{std::numeric_limits::min()}, minV{std::numeric_limits::max()}; - for (size_t i{0}; i < nums_size; i++) { - if (nums[i] >= maxV) { - maxV = nums[i]; - } else { - right = i; +class Solution { +public: + int32_t findUnsortedSubarray(const vector &nums) { + const auto nums_size{nums.size()}; + vector nums2{nums}; + std::sort(nums2.begin(), nums2.end()); + size_t left{0}, right{nums.size()}; + for (size_t i{0}; i < nums_size && nums2[i] == nums[i]; i++, left++) { + } + for (size_t i{nums_size}; i > 0 && nums2[i - 1] == nums[i - 1]; i--, right--) { } + return std::max(0, static_cast(right - left)); } - for (size_t i{nums_size}; i > 0; i--) { - if (nums[i - 1] <= minV) { - minV = nums[i - 1]; - } else { - left = i - 1; + + int32_t findUnsortedSubarray2(const vector &nums) { + const auto nums_size{nums.size()}; + size_t left{nums.size() - 1}, right{0}; + int32_t maxV{std::numeric_limits::min()}, minV{std::numeric_limits::max()}; + for (size_t i{0}; i < nums_size; i++) { + if (nums[i] >= maxV) { + maxV = nums[i]; + } else { + right = i; + } } + for (size_t i{nums_size}; i > 0; i--) { + if (nums[i - 1] <= minV) { + minV = nums[i - 1]; + } else { + left = i - 1; + } + } + return right == 0 ? 0 : right - left + 1; } - return right == 0 ? 0 : right - left + 1; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_581_test.cpp b/algorithm/array/leetcode_581_test.cpp new file mode 100644 index 00000000..83320a2e --- /dev/null +++ b/algorithm/array/leetcode_581_test.cpp @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_581_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_581_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_581.cpp" + +namespace leetcode_581 { +using std::vector; + +TEST_CASE("test case 1 [test_581]", "[test_581]") { + vector input{1, 1, 4, 5, 1, 4}; + static constexpr const auto result{4}; + Solution solution; + CHECK(result == solution.findUnsortedSubarray(input)); + CHECK(result == solution.findUnsortedSubarray2(input)); +} + +TEST_CASE("test case 2 [test_581]", "[test_581]") { + vector input{2, 6, 4, 8, 10, 9, 15}; + static constexpr const auto result{5}; + Solution solution; + CHECK(result == solution.findUnsortedSubarray(input)); + CHECK(result == solution.findUnsortedSubarray2(input)); +} + +TEST_CASE("test case 3 [test_581]", "[test_581]") { + vector input{1, 2, 3, 4}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.findUnsortedSubarray(input)); + CHECK(result == solution.findUnsortedSubarray2(input)); +} + +TEST_CASE("test case 4 [test_581]", "[test_581]") { + vector input{1}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.findUnsortedSubarray(input)); + CHECK(result == solution.findUnsortedSubarray2(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_581_TEST_HPP diff --git a/algorithm/array/leetcode_581_test.hpp b/algorithm/array/leetcode_581_test.hpp deleted file mode 100644 index 8e0aa1b3..00000000 --- a/algorithm/array/leetcode_581_test.hpp +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_581_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_581_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_581 { -using std::vector; - -struct leetcode_581 { - static int32_t findUnsortedSubarray(const vector &nums); - - static int32_t findUnsortedSubarray2(const vector &nums); -}; - -TEST_CASE("test case 1 [test_581]", "[test_581]") { - const vector input{1, 1, 4, 5, 1, 4}; - static constexpr const auto result{4}; - CHECK(result == leetcode_581::findUnsortedSubarray(input)); - CHECK(result == leetcode_581::findUnsortedSubarray2(input)); -} - -TEST_CASE("test case 2 [test_581]", "[test_581]") { - const vector input{2, 6, 4, 8, 10, 9, 15}; - static constexpr const auto result{5}; - CHECK(result == leetcode_581::findUnsortedSubarray(input)); - CHECK(result == leetcode_581::findUnsortedSubarray2(input)); -} - -TEST_CASE("test case 3 [test_581]", "[test_581]") { - const vector input{1, 2, 3, 4}; - static constexpr const auto result{0}; - CHECK(result == leetcode_581::findUnsortedSubarray(input)); - CHECK(result == leetcode_581::findUnsortedSubarray2(input)); -} - -TEST_CASE("test case 4 [test_581]", "[test_581]") { - const vector input{1}; - static constexpr const auto result{0}; - CHECK(result == leetcode_581::findUnsortedSubarray(input)); - CHECK(result == leetcode_581::findUnsortedSubarray2(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_581_TEST_HPP diff --git a/algorithm/array/leetcode_59.cpp b/algorithm/array/leetcode_59.cpp index b4cf4179..2fac0aba 100644 --- a/algorithm/array/leetcode_59.cpp +++ b/algorithm/array/leetcode_59.cpp @@ -1,40 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_59_test.hpp" +#include +#include +#include namespace leetcode_59 { +using std::vector; +#endif -vector> leetcode_59::generateMatrix(int32_t n) { - vector> will_return(n, vector(n, 0)); - int32_t counter{1}; - using func_type = std::function(size_t, size_t, int32_t)>; - const func_type rightDown = [&will_return, &counter] - (size_t x, size_t y, int32_t steps) -> std::pair { - will_return[x][y] = counter; - for (int32_t step{0}; step < steps; ++counter, ++y, will_return[x][y] = counter, ++step) {} - for (int32_t step{0}; step < steps; ++counter, ++x, will_return[x][y] = counter, ++step) {} - counter++; - return {x, y - 1}; // 到达右下角,左移一位 - }; - const func_type leftup = [&will_return, &counter] - (size_t x, size_t y, int32_t steps) -> std::pair { - will_return[x][y] = counter; - for (int32_t step{0}; step < steps; ++counter, --y, will_return[x][y] = counter, ++step) {} - for (int32_t step{0}; step < steps; ++counter, --x, will_return[x][y] = counter, ++step) {} - counter++; - return {x, y + 1}; // 到达左上角,右移一位 - }; - for (int32_t i{0}, x{0}, y{0}; i < n; ++i) { - const auto func = (i % 2 == 0) ? rightDown : leftup; - const auto next = func(x, y, n - i - 1); - x = next.first, y = next.second; +class Solution { +public: + vector> generateMatrix(int32_t n) { + vector> will_return(n, vector(n, 0)); + int32_t counter{1}; + using func_type = std::function(size_t, size_t, int32_t)>; + const func_type rightDown = [&will_return, &counter] + (size_t x, size_t y, int32_t steps) -> std::pair { + will_return[x][y] = counter; + for (int32_t step{0}; step < steps; ++counter, ++y, will_return[x][y] = counter, ++step) {} + for (int32_t step{0}; step < steps; ++counter, ++x, will_return[x][y] = counter, ++step) {} + counter++; + return {x, y - 1}; // 到达右下角,左移一位 + }; + const func_type leftup = [&will_return, &counter] + (size_t x, size_t y, int32_t steps) -> std::pair { + will_return[x][y] = counter; + for (int32_t step{0}; step < steps; ++counter, --y, will_return[x][y] = counter, ++step) {} + for (int32_t step{0}; step < steps; ++counter, --x, will_return[x][y] = counter, ++step) {} + counter++; + return {x, y + 1}; // 到达左上角,右移一位 + }; + for (int32_t i{0}, x{0}, y{0}; i < n; ++i) { + const auto func = (i % 2 == 0) ? rightDown : leftup; + const auto next = func(x, y, n - i - 1); + x = next.first, y = next.second; + } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_59_test.hpp b/algorithm/array/leetcode_59_test.cpp similarity index 78% rename from algorithm/array/leetcode_59_test.hpp rename to algorithm/array/leetcode_59_test.cpp index c3acd662..eb756477 100644 --- a/algorithm/array/leetcode_59_test.hpp +++ b/algorithm/array/leetcode_59_test.cpp @@ -1,28 +1,20 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_59_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_59_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_59_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_59_TEST_HPP #include #include #include #include +#include "leetcode_59.cpp" namespace leetcode_59 { using std::vector; -struct leetcode_59 { - static vector> generateMatrix(int32_t n); -}; - using Catch::Matchers::Equals; TEST_CASE("2 {test_59}", "{test_59}") { @@ -31,8 +23,8 @@ TEST_CASE("2 {test_59}", "{test_59}") { {8, 9, 4}, {7, 6, 5} }; - - CHECK_THAT(result, Equals(leetcode_59::generateMatrix(input))); + Solution solution; + CHECK_THAT(solution.generateMatrix(input), Equals(result)); } TEST_CASE("1 {test_59}", "{test_59}") { @@ -47,7 +39,7 @@ TEST_CASE("1 {test_59}", "{test_59}") { {22, 21, 20, 19, 18, 17, 16, 15}}; const vector> result2{{1, 2, 3, 4, 5, 6, 7, 9}, {0, 29, 30, 31, 32, 33, 35, 10}, - {0, 28, 49, 50, 51, 53,36, 11}, + {0, 28, 49, 50, 51, 53, 36, 11}, {0, 27, 48, 61, 63, 54, 37, 12}, {0, 26, 47, 60, 64, 55, 38, 13 }, @@ -55,8 +47,9 @@ TEST_CASE("1 {test_59}", "{test_59}") { {0, 24, 45, 43, 42, 41, 40, 15}, {0, 23, 21, 20, 19, 18, 17, 16}}; - CHECK_THAT(result, Equals(leetcode_59::generateMatrix(input))); + Solution solution; + CHECK_THAT(solution.generateMatrix(input), Equals(result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_59_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_59_TEST_HPP diff --git a/algorithm/array/leetcode_605.cpp b/algorithm/array/leetcode_605.cpp index 6bb6a973..0a8cfdcf 100644 --- a/algorithm/array/leetcode_605.cpp +++ b/algorithm/array/leetcode_605.cpp @@ -1,50 +1,55 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_605_test.hpp" +#include +#include namespace leetcode_605 { +using std::vector; +#endif -// 虽然是种花问题,但是也可以映射到其他问题上,比如一个很常见的问题...... - -bool leetcode_605::canPlaceFlowers(const vector &urinal_immutable, int32_t n) { - vector urinal{urinal_immutable}; - const auto urinal_size{urinal.size()}; - if (n == 0) { - return true; - } else if ((urinal_size + 1) / 2 < static_cast(n)) { - return false; - } else if (urinal_size == 1) { - return urinal[0] != 1; - } else if (urinal_size == 2) { - return urinal[0] != 1 && urinal[1] != 1; - } - if (urinal[0] == 0 && urinal[1] == 0) { - urinal[0] = 1; - n--; - } - if (urinal[urinal_size - 1] == 0 && urinal[urinal_size - 2] == 0) { - urinal[urinal_size - 1] = 1; - n--; - } - for (size_t i{1}, temp{1}; n > 0; temp = i) { - for (; i < urinal_size; i++) { - if (urinal[i - 1] == 0 && urinal[i] == 0 && urinal[i + 1] == 0) { - urinal[i] = 1; - i += 2; - n--; - break; - } - } - if (temp == i) { +class Solution { +public: + // 虽然是种花问题,但是也可以映射到其他问题上,比如一个很常见的问题...... + bool canPlaceFlowers(const vector &urinal_immutable, int32_t n) { + vector urinal{urinal_immutable}; + const auto urinal_size{urinal.size()}; + if (n == 0) { + return true; + } else if ((urinal_size + 1) / 2 < static_cast(n)) { return false; + } else if (urinal_size == 1) { + return urinal[0] != 1; + } else if (urinal_size == 2) { + return urinal[0] != 1 && urinal[1] != 1; } + if (urinal[0] == 0 && urinal[1] == 0) { + urinal[0] = 1; + n--; + } + if (urinal[urinal_size - 1] == 0 && urinal[urinal_size - 2] == 0) { + urinal[urinal_size - 1] = 1; + n--; + } + for (size_t i{1}, temp{1}; n > 0; temp = i) { + for (; i < urinal_size; i++) { + if (urinal[i - 1] == 0 && urinal[i] == 0 && urinal[i + 1] == 0) { + urinal[i] = 1; + i += 2; + n--; + break; + } + } + if (temp == i) { + return false; + } + } + return true; } - return true; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_605_test.cpp b/algorithm/array/leetcode_605_test.cpp new file mode 100644 index 00000000..272a3014 --- /dev/null +++ b/algorithm/array/leetcode_605_test.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_605_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_605_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_605.cpp" + +namespace leetcode_605 { +using std::vector; + +TEST_CASE("test case 1 [test_605]", "[test_605]") { + vector input{1, 0, 0, 0, 1}; + static constexpr const auto n{1}; + Solution solution; + CHECK(solution.canPlaceFlowers(input, n)); +} + +TEST_CASE("test case 2 [test_605]", "[test_605]") { + vector input{1, 0, 0, 0, 1}; + static constexpr const auto n{2}; + Solution solution; + CHECK_FALSE(solution.canPlaceFlowers(input, n)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_605_TEST_HPP diff --git a/algorithm/array/leetcode_605_test.hpp b/algorithm/array/leetcode_605_test.hpp deleted file mode 100644 index 1950b829..00000000 --- a/algorithm/array/leetcode_605_test.hpp +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_605_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_605_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_605 { -using std::vector; - -struct leetcode_605 { - static bool canPlaceFlowers(const vector &urinal, int32_t n); -}; - -TEST_CASE("test case 1 [test_605]", "[test_605]") { - const vector input{1, 0, 0, 0, 1}; - static constexpr const auto n{1}; - CHECK(leetcode_605::canPlaceFlowers(input, n)); -} - -TEST_CASE("test case 2 [test_605]", "[test_605]") { - const vector input{1, 0, 0, 0, 1}; - static constexpr const auto n{2}; - CHECK_FALSE(leetcode_605::canPlaceFlowers(input, n)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_605_TEST_HPP diff --git a/algorithm/array/leetcode_661.cpp b/algorithm/array/leetcode_661.cpp index f5f32610..0dd53f07 100644 --- a/algorithm/array/leetcode_661.cpp +++ b/algorithm/array/leetcode_661.cpp @@ -1,85 +1,86 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_661_test.hpp" +#include +#include namespace leetcode_661 { +using std::vector; +#endif -vector> leetcode_661::imageSmoother(const vector> &M) { - const auto sizes{M.size()}, sizes_in{M[0].size()}; - vector> willreturn(sizes, vector(sizes_in, 0)); - if (sizes == 1) { - if (sizes_in == 1) { - return M; - } else if (sizes_in == 2) { - return {{(M[0][0] + M[0][1]) / 2, (M[0][0] + M[0][1]) / 2}}; - } else { - willreturn[0][0] = (M[0][0] + M[0][1]) / 2; - willreturn[0][sizes_in - 1] = (M[0][sizes_in - 2] + M[0][sizes_in - 1]) / 2; - for (size_t i{1}; i < sizes_in - 1; i++) { - willreturn[0][i] = ( - M[0][i - 1] + M[0][i] + M[0][i + 1]) / 3; +class Solution { +public: + vector> imageSmoother(const vector> &M) { + const auto sizes{M.size()}, sizes_in{M[0].size()}; + vector> willreturn(sizes, vector(sizes_in, 0)); + if (sizes == 1) { + if (sizes_in == 1) { + return M; + } else if (sizes_in == 2) { + return {{(M[0][0] + M[0][1]) / 2, (M[0][0] + M[0][1]) / 2}}; + } else { + willreturn[0][0] = (M[0][0] + M[0][1]) / 2; + willreturn[0][sizes_in - 1] = (M[0][sizes_in - 2] + M[0][sizes_in - 1]) / 2; + for (size_t i{1}; i < sizes_in - 1; i++) { + willreturn[0][i] = (M[0][i - 1] + M[0][i] + M[0][i + 1]) / 3; + } + return willreturn; } - return willreturn; - } - } else if (sizes_in == 1) { - if (sizes == 2) { - return {{(M[0][0] + M[1][0]) / 2}, - {(M[0][0] + M[1][0]) / 2}}; - } else { - willreturn[0][0] = (M[0][0] + M[1][0]) / 2; - willreturn[sizes - 1][0] = (M[sizes - 1][0] - + M[sizes - 2][0]) / 2; - for (size_t i{1}; i < sizes - 1; i++) { - willreturn[i][0] = ( - M[i - 1][0] + M[i][0] + M[i + 1][0]) / 3; + } else if (sizes_in == 1) { + if (sizes == 2) { + return {{(M[0][0] + M[1][0]) / 2}, + {(M[0][0] + M[1][0]) / 2}}; + } else { + willreturn[0][0] = (M[0][0] + M[1][0]) / 2; + willreturn[sizes - 1][0] = (M[sizes - 1][0] + M[sizes - 2][0]) / 2; + for (size_t i{1}; i < sizes - 1; i++) { + willreturn[i][0] = (M[i - 1][0] + M[i][0] + M[i + 1][0]) / 3; + } + return willreturn; } - return willreturn; } - } - willreturn[0][0] = - (M[0][0] + M[0][1] + - M[1][0] + M[1][1]) / 4; - willreturn[sizes - 1][0] = - (M[sizes - 1][0] + M[sizes - 2][0] + - M[sizes - 2][1] + M[sizes - 1][1]) / 4; - willreturn[0][sizes_in - 1] = ( - M[0][sizes_in - 1] + M[1][sizes_in - 1] + - M[1][sizes_in - 2] + M[0][sizes_in - 2] - ) / 4; - willreturn[sizes - 1][sizes_in - 1] = ( - M[sizes - 1][sizes_in - 1] + M[sizes - 1][sizes_in - 2] + - M[sizes - 2][sizes_in - 1] + M[sizes - 2][sizes_in - 2] - ) / 4; - for (size_t i{1}; i < sizes_in - 1; i++) { - willreturn[0][i] = ( - M[0][i - 1] + M[0][i] + M[0][i + 1] + - M[1][i - 1] + M[1][i] + M[1][i + 1]) / 6; - willreturn[sizes - 1][i] = ( - M[sizes - 2][i - 1] + M[sizes - 2][i] + M[sizes - 2][i + 1] + - M[sizes - 1][i - 1] + M[sizes - 1][i] + M[sizes - 1][i + 1]) / 6; - } - for (size_t i{1}; i < sizes - 1; i++) { - willreturn[i][0] = ( - M[i - 1][0] + M[i][0] + M[i + 1][0] + - M[i - 1][1] + M[i][1] + M[i + 1][1] - ) / 6; - willreturn[i][sizes_in - 1] = ( - M[i - 1][sizes_in - 1] + M[i][sizes_in - 1] + M[i + 1][sizes_in - 1] + - M[i - 1][sizes_in - 2] + M[i][sizes_in - 2] + M[i + 1][sizes_in - 2] - ) / 6; - for (size_t j{1}; j < sizes_in - 1; j++) { - willreturn[i][j] = ( - M[i - 1][j - 1] + M[i][j - 1] + M[i + 1][j - 1] + - M[i - 1][j] + M[i][j] + M[i + 1][j] + - M[i - 1][j + 1] + M[i][j + 1] + M[i + 1][j + 1] - ) / 9; + willreturn[0][0] = + (M[0][0] + M[0][1] + + M[1][0] + M[1][1]) / + 4; + willreturn[sizes - 1][0] = + (M[sizes - 1][0] + M[sizes - 2][0] + + M[sizes - 2][1] + M[sizes - 1][1]) / + 4; + willreturn[0][sizes_in - 1] = (M[0][sizes_in - 1] + M[1][sizes_in - 1] + + M[1][sizes_in - 2] + M[0][sizes_in - 2]) / + 4; + willreturn[sizes - 1][sizes_in - 1] = (M[sizes - 1][sizes_in - 1] + M[sizes - 1][sizes_in - 2] + + M[sizes - 2][sizes_in - 1] + M[sizes - 2][sizes_in - 2]) / + 4; + for (size_t i{1}; i < sizes_in - 1; i++) { + willreturn[0][i] = (M[0][i - 1] + M[0][i] + M[0][i + 1] + + M[1][i - 1] + M[1][i] + M[1][i + 1]) / + 6; + willreturn[sizes - 1][i] = (M[sizes - 2][i - 1] + M[sizes - 2][i] + M[sizes - 2][i + 1] + + M[sizes - 1][i - 1] + M[sizes - 1][i] + M[sizes - 1][i + 1]) / + 6; } + for (size_t i{1}; i < sizes - 1; i++) { + willreturn[i][0] = (M[i - 1][0] + M[i][0] + M[i + 1][0] + + M[i - 1][1] + M[i][1] + M[i + 1][1]) / + 6; + willreturn[i][sizes_in - 1] = (M[i - 1][sizes_in - 1] + M[i][sizes_in - 1] + M[i + 1][sizes_in - 1] + + M[i - 1][sizes_in - 2] + M[i][sizes_in - 2] + M[i + 1][sizes_in - 2]) / + 6; + for (size_t j{1}; j < sizes_in - 1; j++) { + willreturn[i][j] = (M[i - 1][j - 1] + M[i][j - 1] + M[i + 1][j - 1] + + M[i - 1][j] + M[i][j] + M[i + 1][j] + + M[i - 1][j + 1] + M[i][j + 1] + M[i + 1][j + 1]) / + 9; + } + } + return willreturn; } - return willreturn; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_661_test.cpp b/algorithm/array/leetcode_661_test.cpp new file mode 100644 index 00000000..e28c372b --- /dev/null +++ b/algorithm/array/leetcode_661_test.cpp @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 暴力解法 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_661_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_661_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_661.cpp" + +namespace leetcode_661 { +using std::vector; + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_661]", "[test_661]") { + vector> input{{1, 1, 1}, + {1, 0, 1}, + {1, 1, 1},}; + const vector> result{{0, 0, 0}, + {0, 0, 0}, + {0, 0, 0},}; + Solution solution; + CHECK_THAT(solution.imageSmoother(input), Equals(result)); +} + +TEST_CASE("test case 2 [test_661]", "[test_661]") { + vector> input{{1, 1, 1},}; + const vector> result{{1, 1, 1},}; + Solution solution; + CHECK_THAT(solution.imageSmoother(input), Equals(result)); +} + +TEST_CASE("test case 3 [test_661]", "[test_661]") { + vector> input{{1}, + {1}, + {1},}; + const vector> result{{1}, + {1}, + {1},}; + Solution solution; + CHECK_THAT(solution.imageSmoother(input), Equals(result)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_661_TEST_HPP diff --git a/algorithm/array/leetcode_661_test.hpp b/algorithm/array/leetcode_661_test.hpp deleted file mode 100644 index 9aac642c..00000000 --- a/algorithm/array/leetcode_661_test.hpp +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 暴力解法 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_661_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_661_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_661 { -using std::vector; - -struct leetcode_661 { - static vector> imageSmoother(const vector> &M); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_661]", "[test_661]") { - const vector> input{{1, 1, 1}, - {1, 0, 1}, - {1, 1, 1},}; - const vector> result{{0, 0, 0}, - {0, 0, 0}, - {0, 0, 0},}; - CHECK_THAT(result, Equals(leetcode_661::imageSmoother(input))); -} - -TEST_CASE("test case 2 [test_661]", "[test_661]") { - const vector> input{{1, 1, 1},}; - const vector> result{{1, 1, 1},}; - CHECK_THAT(result, Equals(leetcode_661::imageSmoother(input))); -} - -TEST_CASE("test case 3 [test_661]", "[test_661]") { - const vector> input{{1}, - {1}, - {1},}; - const vector> result{{1}, - {1}, - {1},}; - CHECK_THAT(result, Equals(leetcode_661::imageSmoother(input))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_661_TEST_HPP diff --git a/algorithm/array/leetcode_665.cpp b/algorithm/array/leetcode_665.cpp index 71092a49..5a421784 100644 --- a/algorithm/array/leetcode_665.cpp +++ b/algorithm/array/leetcode_665.cpp @@ -1,48 +1,55 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_665_test.hpp" +#include +#include namespace leetcode_665 { +using std::vector; +#endif -bool leetcode_665::checkPossibility(const vector &nums) { - int count{0}; - size_t position{0}; - for (size_t i{0}; i < nums.size() - 1; i++) { - if (nums[i] - nums[i + 1] > 0) { - count++; - position = i; +class Solution { +public: + bool checkPossibility(const vector &nums) { + int32_t count{0}; + size_t position{0}; + for (size_t i{0}; i < nums.size() - 1; i++) { + if (nums[i] - nums[i + 1] > 0) { + count++; + position = i; + } } - } - if (count > 1) { - return false; - } - if (position == 0 || position == nums.size() - 1) { - return true; - } - bool first{true}, second{true}; - if (nums[position - 1] > nums[position + 1]) { - first = false; - } - for (size_t i = position + 1; i < nums.size() - 1; i++) { - if (nums[i] > nums[i + 1]) { - first = false; + if (count > 1) { + return false; } - } - if (position < nums.size() - 2) { - if (nums[position] > nums[position + 2]) { - return first; + if (position == 0 || position == nums.size() - 1) { + return true; + } + bool first{true}, second{true}; + if (nums[position - 1] > nums[position + 1]) { + first = false; } for (size_t i = position + 1; i < nums.size() - 1; i++) { if (nums[i] > nums[i + 1]) { + first = false; + } + } + if (position < nums.size() - 2) { + if (nums[position] > nums[position + 2]) { return first; } + for (size_t i = position + 1; i < nums.size() - 1; i++) { + if (nums[i] > nums[i + 1]) { + return first; + } + } } + return first || second; } - return first || second; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_665_test.cpp b/algorithm/array/leetcode_665_test.cpp new file mode 100644 index 00000000..f28f07f1 --- /dev/null +++ b/algorithm/array/leetcode_665_test.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 暴力解法 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_665_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_665_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_665.cpp" + +namespace leetcode_665 { +using std::vector; + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_665]", "[test_665]") { + vector input{4, 2, 3}; + Solution solution; + CHECK(solution.checkPossibility(input)); +} + +TEST_CASE("test case 2 [test_665]", "[test_665]") { + vector input{4, 2, 1}; + Solution solution; + CHECK_FALSE(solution.checkPossibility(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_665_TEST_HPP diff --git a/algorithm/array/leetcode_665_test.hpp b/algorithm/array/leetcode_665_test.hpp deleted file mode 100644 index edff3d23..00000000 --- a/algorithm/array/leetcode_665_test.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 暴力解法 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_665_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_665_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_665 { -using std::vector; - -struct leetcode_665 { - static bool checkPossibility(const vector &nums); -}; - - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_665]", "[test_665]") { - const vector input{4, 2, 3}; - CHECK(leetcode_665::checkPossibility(input)); -} - -TEST_CASE("test case 2 [test_665]", "[test_665]") { - const vector input{4, 2, 1}; - CHECK_FALSE(leetcode_665::checkPossibility(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_665_TEST_HPP diff --git a/algorithm/array/leetcode_674.cpp b/algorithm/array/leetcode_674.cpp index fcd5b8dd..61b6d32b 100644 --- a/algorithm/array/leetcode_674.cpp +++ b/algorithm/array/leetcode_674.cpp @@ -1,21 +1,28 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_674_test.hpp" +#include +#include +#include namespace leetcode_674 { +using std::vector; +#endif -int leetcode_674::findLengthOfLCIS(const vector &nums) { - int32_t will_Return{!nums.empty()}, maxv{1}; - for (size_t i{1}, size{nums.size()}; i < size; ++i) { - maxv = (nums[i] > nums[i - 1]) ? (maxv + 1) : 1; - will_Return = std::max(will_Return, maxv); +class Solution { +public: + int32_t findLengthOfLCIS(const vector &nums) { + int32_t will_Return{!nums.empty()}, maxv{1}; + for (size_t i{1}, size{nums.size()}; i < size; ++i) { + maxv = (nums[i] > nums[i - 1]) ? (maxv + 1) : 1; + will_Return = std::max(will_Return, maxv); + } + return will_Return; } - return will_Return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_674_test.cpp b/algorithm/array/leetcode_674_test.cpp new file mode 100644 index 00000000..4b4befe0 --- /dev/null +++ b/algorithm/array/leetcode_674_test.cpp @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 暴力解法 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_674_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_674_TEST_HPP + +#include + +#include "leetcode_674.cpp" + +namespace leetcode_674 { +using std::vector; + +TEST_CASE("test case 1 [test_674]", "[test_674]") { + vector input{4, 2, 3}; + static constexpr const auto result{2}; + Solution solution; + CHECK(result == solution.findLengthOfLCIS(input)); +} + +TEST_CASE("test case 2 [test_674]", "[test_674]") { + vector input{1, 3, 5, 4, 7}; + static constexpr const auto result{3}; + Solution solution; + CHECK(result == solution.findLengthOfLCIS(input)); +} + +TEST_CASE("test case 3 [test_674]", "[test_674]") { + vector input{2, 2, 2, 2, 2}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.findLengthOfLCIS(input)); +} + +TEST_CASE("test case 4 [test_674]", "[test_674]") { + vector input{1}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.findLengthOfLCIS(input)); +} + +TEST_CASE("test case 5 [test_674]", "[test_674]") { + vector input{}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.findLengthOfLCIS(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_674_TEST_HPP diff --git a/algorithm/array/leetcode_674_test.hpp b/algorithm/array/leetcode_674_test.hpp deleted file mode 100644 index 3aa03ad4..00000000 --- a/algorithm/array/leetcode_674_test.hpp +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 暴力解法 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_674_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_674_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_674 { -using std::vector; - -struct leetcode_674 { - static int findLengthOfLCIS(const vector &nums); -}; - -TEST_CASE("test case 1 [test_674]", "[test_674]") { - const vector input{4, 2, 3}; - static constexpr const auto result{2}; - CHECK(result == leetcode_674::findLengthOfLCIS(input)); -} - -TEST_CASE("test case 2 [test_674]", "[test_674]") { - const vector input{1, 3, 5, 4, 7}; - static constexpr const auto result{3}; - CHECK(result == leetcode_674::findLengthOfLCIS(input)); -} - -TEST_CASE("test case 3 [test_674]", "[test_674]") { - const vector input{2, 2, 2, 2, 2}; - static constexpr const auto result{1}; - CHECK(result == leetcode_674::findLengthOfLCIS(input)); -} - -TEST_CASE("test case 4 [test_674]", "[test_674]") { - const vector input{1}; - static constexpr const auto result{1}; - CHECK(result == leetcode_674::findLengthOfLCIS(input)); -} - -TEST_CASE("test case 5 [test_674]", "[test_674]") { - const vector input{}; - static constexpr const auto result{0}; - CHECK(result == leetcode_674::findLengthOfLCIS(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_674_TEST_HPP diff --git a/algorithm/array/leetcode_697.cpp b/algorithm/array/leetcode_697.cpp index 537d08e0..70e95475 100644 --- a/algorithm/array/leetcode_697.cpp +++ b/algorithm/array/leetcode_697.cpp @@ -1,37 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_697_test.hpp" -#include +#include +#include namespace leetcode_697 { -using std::unordered_map; +using std::vector; +#endif -int32_t leetcode_697::findShortestSubArray(const vector &nums) { - if (nums.empty()) { - return 0; - } - unordered_map times, begin; - int32_t max{0}, will_return{0}; - const auto nums_size{static_cast(nums.size())}; - for (int32_t i{0}; i < nums_size; i++) { - const auto num{nums[i]}; - ++times[num]; - if (times[num] == 1) { - begin[num] = i; - } else { - if (times[num] > max) { - max = times[num]; - will_return = i - begin[num]; - } else if (times[num] == max) { - will_return = std::min(will_return, i - begin[num]); +class Solution { +public: + int32_t findShortestSubArray(std::vector &nums) { + if (nums.empty()) { + return 0; + } + std::unordered_map times, begin; + int32_t max{0}, will_return{0}; + const auto nums_size{static_cast(nums.size())}; + for (int32_t i{0}; i < nums_size; i++) { + const auto num{nums[i]}; + ++times[num]; + if (times[num] == 1) { + begin[num] = i; + } else { + if (times[num] > max) { + max = times[num]; + will_return = i - begin[num]; + } else if (times[num] == max) { + will_return = std::min(will_return, i - begin[num]); + } } } + return will_return + 1; } - return will_return + 1; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/array/leetcode_697_test.cpp b/algorithm/array/leetcode_697_test.cpp new file mode 100644 index 00000000..b4607f37 --- /dev/null +++ b/algorithm/array/leetcode_697_test.cpp @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 暴力解法 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_697_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_697_TEST_HPP + +#include + +#include "leetcode_697.cpp" + +namespace leetcode_697 { +using std::vector; + +TEST_CASE("test case 1 [test_697]", "[test_697]") { + vector input{1, 2, 2, 3, 1}; + static constexpr const auto result{2}; + Solution solution; + CHECK(result == solution.findShortestSubArray(input)); +} + +TEST_CASE("test case 2 [test_697]", "[test_697]") { + vector input{1, 2, 2, 3, 1, 4, 2}; + static constexpr const auto result{6}; + Solution solution; + CHECK(result == solution.findShortestSubArray(input)); +} + +TEST_CASE("test case 3 [test_697]", "[test_697]") { + vector input{2, 1}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.findShortestSubArray(input)); +} + +TEST_CASE("test case 4 [test_697]", "[test_697]") { + vector input{}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.findShortestSubArray(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_697_TEST_HPP diff --git a/algorithm/array/leetcode_697_test.hpp b/algorithm/array/leetcode_697_test.hpp deleted file mode 100644 index 9c5a6a4a..00000000 --- a/algorithm/array/leetcode_697_test.hpp +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 暴力解法 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_697_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_697_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_697 { -using std::vector; - -struct leetcode_697 { - static int32_t findShortestSubArray(const vector &nums); -}; - -TEST_CASE("test case 1 [test_697]", "[test_697]") { - const vector input{1, 2, 2, 3, 1}; - static constexpr const auto result{2}; - CHECK(result == leetcode_697::findShortestSubArray(input)); -} - -TEST_CASE("test case 2 [test_697]", "[test_697]") { - const vector input{1, 2, 2, 3, 1, 4, 2}; - static constexpr const auto result{6}; - CHECK(result == leetcode_697::findShortestSubArray(input)); -} - -TEST_CASE("test case 3 [test_697]", "[test_697]") { - const vector input{2, 1}; - static constexpr const auto result{1}; - CHECK(result == leetcode_697::findShortestSubArray(input)); -} - -TEST_CASE("test case 4 [test_697]", "[test_697]") { - const vector input{}; - static constexpr const auto result{0}; - CHECK(result == leetcode_697::findShortestSubArray(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_697_TEST_HPP diff --git a/algorithm/array/leetcode_7.cpp b/algorithm/array/leetcode_7.cpp index 4f837c93..baa47e9a 100644 --- a/algorithm/array/leetcode_7.cpp +++ b/algorithm/array/leetcode_7.cpp @@ -1,93 +1,96 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_7_test.hpp" #include #include #include +#include namespace leetcode_7 { using std::vector; using std::array; +#endif -int leetcode_7::reverse(int32_t x) { - if (x == std::numeric_limits::min()) { - return 0; - } else if (x < 0) { - return -reverse3(-x); - } - std::array nums{0}; - int32_t count{0}; - while (x > 0) { - nums[count] = x % 10; - x /= 10; - count++; - } - int32_t i{0}; - while (i < count && nums[i] == 0) { - i++; - } - int32_t will_return = 0; - for (; i < count; i++) { - if (will_return > (std::numeric_limits::max() - nums[i]) / 10) { + +class Solution { +public: + int32_t reverse(int32_t x) { + if (x == std::numeric_limits::min()) { return 0; + } else if (x < 0) { + return -reverse3(-x); + } + std::array nums{0}; + int32_t count{0}; + while (x > 0) { + nums[count] = x % 10; + x /= 10; + count++; } - will_return = will_return * 10 + nums[i]; + int32_t i{0}; + while (i < count && nums[i] == 0) { + i++; + } + int32_t will_return = 0; + for (; i < count; i++) { + if (will_return > (std::numeric_limits::max() - nums[i]) / 10) { + return 0; + } + will_return = will_return * 10 + nums[i]; + } + return static_cast(will_return); + // 不用64bit版 } - return static_cast(will_return); - // 不用64bit版 -} - -int leetcode_7::reverse2(int x) { - if (x == std::numeric_limits::min()) { - return 0; - } else if (x < 0) { - return -1 * reverse3(-x); - } - vector nums; - while (x > 0) { - nums.push_back(x % 10); - x /= 10; - } - int32_t i{0}; - while (i < static_cast(nums.size()) && nums[i] == 0) { - i++; - } - long will_return = 0; - for (; i < static_cast(nums.size()); i++) { - will_return = will_return * 10 + nums[i]; - if (will_return > std::numeric_limits::max()) { + int32_t reverse2(int32_t x) { + if (x == std::numeric_limits::min()) { return 0; + } else if (x < 0) { + return -1 * reverse3(-x); + } + vector nums; + while (x > 0) { + nums.push_back(x % 10); + x /= 10; + } + int32_t i{0}; + while (i < static_cast(nums.size()) && nums[i] == 0) { + i++; } + long will_return = 0; + for (; i < static_cast(nums.size()); i++) { + will_return = will_return * 10 + nums[i]; + if (will_return > std::numeric_limits::max()) { + return 0; + } + } + return static_cast(will_return); } - return static_cast(will_return); -} - -int leetcode_7::reverse3(int x) { - if (x == std::numeric_limits::min()) { - return 0; - } else if (x < 0) { - return -reverse3(-x); - } - vector vec; - vec.reserve(32); - while (x > 0) { - vec.push_back(x % 10); - x /= 10; - } - int32_t will_return = 0; - for (const auto &i: vec) { - if (will_return > std::numeric_limits::max() / 10) { + int32_t reverse3(int32_t x) { + if (x == std::numeric_limits::min()) { return 0; + } else if (x < 0) { + return -reverse3(-x); + } + vector vec; + vec.reserve(32); + while (x > 0) { + vec.push_back(x % 10); + x /= 10; } - will_return = 10 * will_return + i; + int32_t will_return = 0; + for (const auto &i: vec) { + if (will_return > std::numeric_limits::max() / 10) { + return 0; + } + will_return = 10 * will_return + i; + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_717.cpp b/algorithm/array/leetcode_717.cpp index c24684cf..f4e02d5b 100644 --- a/algorithm/array/leetcode_717.cpp +++ b/algorithm/array/leetcode_717.cpp @@ -1,25 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_717_test.hpp" +#include +#include namespace leetcode_717 { +using std::vector; +#endif -bool leetcode_717::isOneBitCharacter(const vector &bits) { - const size_t size{bits.size()}; - if (size < 2 || bits[size - 2] == 0) { - return true; +class Solution { +public: + bool isOneBitCharacter(vector &bits) { + const size_t size{bits.size()}; + if (size < 2 || bits[size - 2] == 0) { + return true; + } + // sizes == 2 is the same with sizes >2 + // it means, test the string before the last one is over or not + size_t i{0}; + for (; i + 1 < size; ++i) { + i += bits[i]; + } + return i + 1 == size; } - // sizes == 2 is the same with sizes >2 - // it means, test the string before the last one is over or not - size_t i{0}; - for (; i + 1 < size; ++i) { - i += bits[i]; - } - return i + 1 == size; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_717_test.cpp b/algorithm/array/leetcode_717_test.cpp new file mode 100644 index 00000000..168778ab --- /dev/null +++ b/algorithm/array/leetcode_717_test.cpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 暴力解法 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_717_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_717_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_717.cpp" + +namespace leetcode_717 { +using std::vector; + +TEST_CASE("test case 1 [test_717]", "[test_717]") { + vector input{1, 0, 0}; + Solution solution; + CHECK(solution.isOneBitCharacter(input)); +} + +TEST_CASE("test case 2 [test_717]", "[test_717]") { + vector input{1, 1, 1, 0}; + Solution solution; + CHECK_FALSE(solution.isOneBitCharacter(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_717_TEST_HPP diff --git a/algorithm/array/leetcode_717_test.hpp b/algorithm/array/leetcode_717_test.hpp deleted file mode 100644 index ca9fe128..00000000 --- a/algorithm/array/leetcode_717_test.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 暴力解法 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_717_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_717_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_717 { -using std::vector; - -struct leetcode_717 { - static bool isOneBitCharacter(const vector &bits); -}; - -TEST_CASE("test case 1 [test_717]", "[test_717]") { - const vector input{1, 0, 0}; - CHECK(leetcode_717::isOneBitCharacter(input)); -} - -TEST_CASE("test case 2 [test_717]", "[test_717]") { - const vector input{1, 1, 1, 0}; - CHECK_FALSE(leetcode_717::isOneBitCharacter(input)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_717_TEST_HPP diff --git a/algorithm/array/leetcode_724.cpp b/algorithm/array/leetcode_724.cpp index e419b484..599f7459 100644 --- a/algorithm/array/leetcode_724.cpp +++ b/algorithm/array/leetcode_724.cpp @@ -1,28 +1,34 @@ - // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_724_test.hpp" +#include +#include namespace leetcode_724 { -int32_t leetcode_724::pivotIndex(const vector &nums) { - const auto nums_size{nums.size()}; - vector accu(nums_size + 2, 0); - for (size_t i{1}; i <= nums_size; ++i) { - accu[i] = nums[i - 1]; - accu[i] += accu[i - 1]; - } - accu[nums_size + 1] = accu[nums_size]; - for (size_t i{1}; i <= nums_size; ++i) { - if (accu[i - 1] + accu[i] == accu.back()) { // 可见此处可优化 - return static_cast(i) - 1; +using std::vector; +#endif + +class Solution { +public: + int32_t pivotIndex(vector &nums) { + const auto nums_size{nums.size()}; + vector accu(nums_size + 2, 0); + for (size_t i{1}; i <= nums_size; ++i) { + accu[i] = nums[i - 1]; + accu[i] += accu[i - 1]; } + accu[nums_size + 1] = accu[nums_size]; + for (size_t i{1}; i <= nums_size; ++i) { + if (accu[i - 1] + accu[i] == accu.back()) { // 可见此处可优化 + return static_cast(i) - 1; + } + } + return -1; } - return -1; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_724_test.cpp b/algorithm/array/leetcode_724_test.cpp new file mode 100644 index 00000000..628aa167 --- /dev/null +++ b/algorithm/array/leetcode_724_test.cpp @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 暴力解法 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_724_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_724_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_724.cpp" + +namespace leetcode_724 { +using std::vector; + +TEST_CASE("test case 1 [test_724]", "[test_724]") { + vector input{1, 7, 3, 6, 5, 6}; + static constexpr const auto result{3}; + Solution solution; + CHECK(result == solution.pivotIndex(input)); +} + +TEST_CASE("test case 2 [test_724]", "[test_724]") { + vector input{1, 1, 4, 5, 1, 4}; + static constexpr const auto result{-1}; + Solution solution; + CHECK(result == solution.pivotIndex(input)); +} + +TEST_CASE("test case 3 [test_724]", "[test_724]") { + vector input{2, 1, -1}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.pivotIndex(input)); +} + +TEST_CASE("test case 4 [test_724]", "[test_724]") { + vector input{2, 3, -1, 8, 4}; + static constexpr const auto result{3}; + Solution solution; + CHECK(result == solution.pivotIndex(input)); +} + +TEST_CASE("test case 5 [test_724]", "[test_724]") { + vector input{1, -1, 4}; + static constexpr const auto result{2}; + Solution solution; + CHECK(result == solution.pivotIndex(input)); +} + +TEST_CASE("test case 6 [test_724]", "[test_724]") { + vector input{2, 5, 0}; + static constexpr const auto result{-1}; + Solution solution; + CHECK(result == solution.pivotIndex(input)); +} + +TEST_CASE("test case 7 [test_724]", "[test_724]") { + vector input{1}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.pivotIndex(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_724_TEST_HPP diff --git a/algorithm/array/leetcode_724_test.hpp b/algorithm/array/leetcode_724_test.hpp deleted file mode 100644 index c7c1c12b..00000000 --- a/algorithm/array/leetcode_724_test.hpp +++ /dev/null @@ -1,68 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 暴力解法 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_724_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_724_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_724 { -using std::vector; - -struct leetcode_724 { - static int32_t pivotIndex(const vector &nums); -}; - -TEST_CASE("test case 1 [test_724]", "[test_724]") { - const vector input{1, 7, 3, 6, 5, 6}; - static constexpr const auto result{3}; - CHECK(result == leetcode_724::pivotIndex(input)); -} - -TEST_CASE("test case 2 [test_724]", "[test_724]") { - const vector input{1, 1, 4, 5, 1, 4}; - static constexpr const auto result{-1}; - CHECK(result == leetcode_724::pivotIndex(input)); -} - -TEST_CASE("test case 3 [test_724]", "[test_724]") { - const vector input{2, 1, -1}; - static constexpr const auto result{0}; - CHECK(result == leetcode_724::pivotIndex(input)); -} - -TEST_CASE("test case 4 [test_724]", "[test_724]") { - const vector input{2, 3, -1, 8, 4}; - static constexpr const auto result{3}; - CHECK(result == leetcode_724::pivotIndex(input)); -} - -TEST_CASE("test case 5 [test_724]", "[test_724]") { - const vector input{1, -1, 4}; - static constexpr const auto result{2}; - CHECK(result == leetcode_724::pivotIndex(input)); -} - -TEST_CASE("test case 6 [test_724]", "[test_724]") { - const vector input{2, 5, 0}; - static constexpr const auto result{-1}; - CHECK(result == leetcode_724::pivotIndex(input)); -} - -TEST_CASE("test case 7 [test_724]", "[test_724]") { - const vector input{1}; - static constexpr const auto result{0}; - CHECK(result == leetcode_724::pivotIndex(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_724_TEST_HPP diff --git a/algorithm/array/leetcode_73.cpp b/algorithm/array/leetcode_73.cpp index 44311f19..48795163 100644 --- a/algorithm/array/leetcode_73.cpp +++ b/algorithm/array/leetcode_73.cpp @@ -1,59 +1,62 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_73_test.hpp" +#include #include +#include namespace leetcode_73 { +using std::vector; using std::unordered_set; -void leetcode_73::setZeroes(vector> &matrix) { - if (matrix.empty() || matrix.front().empty()) { - return; - } - const auto row_size{matrix.size()}, col_size{matrix.front().size()}; - const auto row = [&matrix] { - return std::find(matrix[0].cbegin(), matrix[0].cend(), 0) != matrix[0].cend(); - }(), col = [&matrix, row_size] { - for (size_t i{0}; i < row_size; ++i) { +class Solution { +public: + void setZeroes(vector> &matrix) { + if (matrix.empty() || matrix.front().empty()) { + return; + } + const auto row_size{matrix.size()}, col_size{matrix.front().size()}; + const auto row = [&matrix] { + return std::find(matrix[0].cbegin(), matrix[0].cend(), 0) != matrix[0].cend(); + }(), col = [&matrix, row_size] { + for (size_t i{0}; i < row_size; ++i) { + if (matrix[i][0] == 0) { + return true; + } + } + return false; + }(); + for (size_t i{1}; i < row_size; ++i) { + for (size_t j{1}; j < col_size; ++j) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for (size_t i{1}; i < row_size; ++i) { if (matrix[i][0] == 0) { - return true; + std::fill(matrix[i].begin() + 1, matrix[i].end(), 0); } } - return false; - }(); - for (size_t i{1}; i < row_size; ++i) { for (size_t j{1}; j < col_size; ++j) { - if (matrix[i][j] == 0) { - matrix[i][0] = 0; - matrix[0][j] = 0; + if (matrix[0][j] == 0) { + for (size_t i{1}; i < row_size; ++i) { + matrix[i][j] = 0; + } } } - } - for (size_t i{1}; i < row_size; ++i) { - if (matrix[i][0] == 0) { - std::fill(matrix[i].begin() + 1, matrix[i].end(), 0); + if (row) { + std::fill(matrix[0].begin(), matrix[0].end(), 0); } - } - for (size_t j{1}; j < col_size; ++j) { - if (matrix[0][j] == 0) { - for (size_t i{1}; i < row_size; ++i) { - matrix[i][j] = 0; + if (col) { + for (size_t i{0}; i < row_size; ++i) { + matrix[i][0] = 0; } } } - if (row) { - std::fill(matrix[0].begin(), matrix[0].end(), 0); - } - if (col) { - for (size_t i{0}; i < row_size; ++i) { - matrix[i][0] = 0; - } - } -} +}; } +#endif diff --git a/algorithm/array/leetcode_73_test.hpp b/algorithm/array/leetcode_73_test.cpp similarity index 59% rename from algorithm/array/leetcode_73_test.hpp rename to algorithm/array/leetcode_73_test.cpp index 7fea5a36..0c0205e2 100644 --- a/algorithm/array/leetcode_73_test.hpp +++ b/algorithm/array/leetcode_73_test.cpp @@ -1,34 +1,27 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Plan 数据结构入门 Day5 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_73_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_73_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_73_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_73_TEST_HPP #include #include #include #include +#include "leetcode_73.cpp" namespace leetcode_73 { using std::vector; -struct leetcode_73 { - static void setZeroes(vector> &matrix); - - static vector> getZeroes(const vector> &matrix) { - vector> will_return{matrix}; - setZeroes(will_return); - return will_return; - } -}; +vector> getZeroes(const vector> &matrix) { + vector> will_return{matrix}; + Solution solution; + solution.setZeroes(will_return); + return will_return; +} using Catch::Matchers::Equals; @@ -45,7 +38,7 @@ TEST_CASE("basic test 3 [test_73]") { {0, 0, 0, 0}, {0, 0, 0, 0} }; - CHECK_THAT(result, Equals(leetcode_73::getZeroes(vec1))); + CHECK_THAT(result, Equals(getZeroes(vec1))); } TEST_CASE("basic test [test_73]", "[test_73]") { @@ -59,7 +52,7 @@ TEST_CASE("basic test [test_73]", "[test_73]") { {0, 0, 0}, {1, 0, 1}, }; - CHECK_THAT(result, Equals(leetcode_73::getZeroes(vec1))); + CHECK_THAT(result, Equals(getZeroes(vec1))); } TEST_CASE("basic test 2[test_73]", "[test_73]") { @@ -73,23 +66,23 @@ TEST_CASE("basic test 2[test_73]", "[test_73]") { {0, 1, 4, 0}, {0, 3, 1, 0}, }; - CHECK_THAT(result, Equals(leetcode_73::getZeroes(vec1))); + CHECK_THAT(result, Equals(getZeroes(vec1))); } TEST_CASE("basic test 4[test_73]", "[test_73]") { const vector> vec1{ - {-4, std::numeric_limits::min(), 6, -7, 0}, - {-8, 6, -8, -6, 0}, - {2147483647, 2, -9, -6, -10} + {-4, std::numeric_limits::min(), 6, -7, 0}, + {-8, 6, -8, -6, 0}, + {2147483647, 2, -9, -6, -10} }; const vector> result{ {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {2147483647, 2, -9, -6, 0} }; - CHECK_THAT(result, Equals(leetcode_73::getZeroes(vec1))); + CHECK_THAT(result, Equals(getZeroes(vec1))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_73_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_73_TEST_HPP diff --git a/algorithm/array/leetcode_747.cpp b/algorithm/array/leetcode_747.cpp index 694f9375..367b72e3 100644 --- a/algorithm/array/leetcode_747.cpp +++ b/algorithm/array/leetcode_747.cpp @@ -1,33 +1,39 @@ - // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_747_test.hpp" +#include +#include namespace leetcode_747 { +using std::vector; +#endif -int32_t leetcode_747::dominantIndex(const vector &nums) { - const auto nums_size{nums.size()}; - size_t pos{0}; - int32_t lastMax{-1}, maxV{-1}; - for (size_t i{0}; i < nums_size; ++i) { - if (maxV < nums[i]) { - pos = i; - maxV = nums[i]; +class Solution { +public: + int32_t dominantIndex(std::vector &nums) { + const auto nums_size{nums.size()}; + size_t pos{0}; + int32_t lastMax{-1}, maxV{-1}; + for (size_t i{0}; i < nums_size; ++i) { + if (maxV < nums[i]) { + pos = i; + maxV = nums[i]; + } } - } - for (size_t i{0}; i < nums_size; ++i) { - if (nums[i] != maxV && lastMax < nums[i]) { - lastMax = nums[i]; + for (size_t i{0}; i < nums_size; ++i) { + if (nums[i] != maxV && lastMax < nums[i]) { + lastMax = nums[i]; + } } + if (lastMax * 2 <= maxV) { + return pos; + } + return -1; } - if (lastMax * 2 <= maxV) { - return pos; - } - return -1; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_747_test.cpp b/algorithm/array/leetcode_747_test.cpp new file mode 100644 index 00000000..d6300350 --- /dev/null +++ b/algorithm/array/leetcode_747_test.cpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_747_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_747_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_747.cpp" + +namespace leetcode_747 { +using std::vector; + +TEST_CASE("test case 2 [test_747]", "[test_747]") { + vector input{1, 2, 3, 4}; + static constexpr const auto result{-1}; + Solution solution; + CHECK(result == solution.dominantIndex(input)); +} + +TEST_CASE("test case 1 [test_747]", "[test_747]") { + vector input{3, 6, 1, 0}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.dominantIndex(input)); +} + + +TEST_CASE("test case 3 [test_747]", "[test_747]") { + vector input{1}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.dominantIndex(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_747_TEST_HPP diff --git a/algorithm/array/leetcode_747_test.hpp b/algorithm/array/leetcode_747_test.hpp deleted file mode 100644 index 5ceb3c12..00000000 --- a/algorithm/array/leetcode_747_test.hpp +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_747_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_747_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_747 { -using std::vector; - -struct leetcode_747 { - static int32_t dominantIndex(const vector &nums); -}; - -TEST_CASE("test case 2 [test_747]", "[test_747]") { - const vector input{1, 2, 3, 4}; - static constexpr const auto result{-1}; - CHECK(result == leetcode_747::dominantIndex(input)); -} -TEST_CASE("test case 1 [test_747]", "[test_747]") { - const vector input{3, 6, 1, 0}; - static constexpr const auto result{1}; - CHECK(result == leetcode_747::dominantIndex(input)); -} - - -TEST_CASE("test case 3 [test_747]", "[test_747]") { - const vector input{1}; - static constexpr const auto result{0}; - CHECK(result == leetcode_747::dominantIndex(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_747_TEST_HPP diff --git a/algorithm/array/leetcode_766.cpp b/algorithm/array/leetcode_766.cpp index d864b2b0..6012716d 100644 --- a/algorithm/array/leetcode_766.cpp +++ b/algorithm/array/leetcode_766.cpp @@ -1,52 +1,50 @@ - // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_766_test.hpp" +#include +#include namespace leetcode_766 { +using std::vector; +#endif - -bool leetcode_766::isToeplitzMatrix(const vector> &matrix) { - if (matrix.empty() || matrix.front().empty()) { - return true; - } - const auto m{matrix.size()}, n{matrix.front().size()}; - if (1 == m || 1 == n) { - return true; - } - const auto minV{std::min(m, n)}; - for (size_t i{0}; i < m; ++i) { - auto val{i + 1}; - const auto num{matrix[i][0]}; - for (size_t j = 1; j < std::min(m - i, n); ++j) { - if (num != matrix[val][j]) { - return false; +class Solution { +public: + bool isToeplitzMatrix(vector> &matrix) { + if (matrix.empty() || matrix.front().empty()) { + return true; + } + const auto m{matrix.size()}, n{matrix.front().size()}; + if (1 == m || 1 == n) { + return true; + } + const auto minV{std::min(m, n)}; + for (size_t i{0}; i < m; ++i) { + auto val{i + 1}; + const auto num{matrix[i][0]}; + for (size_t j = 1; j < std::min(m - i, n); ++j) { + if (num != matrix[val][j]) { + return false; + } + val += 1; } - val += 1; } - } -// for (size_t i{1}; i < minV; i++) { -// const auto num = matrix[0][0]; -// if (num != matrix[i][i]) { -// return false; -// } -// } - for (size_t i{1}; i < n; ++i) { - const auto num = matrix[0][i]; - auto val{i + 1}; - for (size_t j{1}; j < std::min(m, n - i); ++j) { - if (num != matrix[j][val]) { - return false; + for (size_t i{1}; i < n; ++i) { + const auto num = matrix[0][i]; + auto val{i + 1}; + for (size_t j{1}; j < std::min(m, n - i); ++j) { + if (num != matrix[j][val]) { + return false; + } + val += 1; } - val += 1; } + return true; } - return true; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_766_test.cpp b/algorithm/array/leetcode_766_test.cpp new file mode 100644 index 00000000..6ad7afc5 --- /dev/null +++ b/algorithm/array/leetcode_766_test.cpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_766_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_766_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_766.cpp" + +namespace leetcode_766 { +using std::vector; + +TEST_CASE("test case 2 [test_766]", "[test_766]") { + vector> input{ + {1, 2, 3, 4}, + {5, 1, 2, 3}, + {9, 5, 1, 2}, + }; + Solution solution; + CHECK(solution.isToeplitzMatrix(input)); +} + +TEST_CASE("test case 1 [test_766]", "[test_766]") { + vector> input{ + {1, 2}, + {2, 2}, + }; + Solution solution; + CHECK_FALSE(solution.isToeplitzMatrix(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_766_TEST_HPP diff --git a/algorithm/array/leetcode_766_test.hpp b/algorithm/array/leetcode_766_test.hpp deleted file mode 100644 index 2d1ba00b..00000000 --- a/algorithm/array/leetcode_766_test.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_766_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_766_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_766 { -using std::vector; - -struct leetcode_766 { - static bool isToeplitzMatrix(const vector> &matrix); -}; - -TEST_CASE("test case 2 [test_766]", "[test_766]") { - const vector> input{ - {1, 2, 3, 4}, - {5, 1, 2, 3}, - {9, 5, 1, 2}, - }; - CHECK(leetcode_766::isToeplitzMatrix(input)); -} - -TEST_CASE("test case 1 [test_766]", "[test_766]") { - const vector> input{ - {1, 2}, - {2, 2}, - }; - CHECK_FALSE(leetcode_766::isToeplitzMatrix(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_766_TEST_HPP diff --git a/algorithm/array/leetcode_7_test.cpp b/algorithm/array/leetcode_7_test.cpp new file mode 100644 index 00000000..8c7d8030 --- /dev/null +++ b/algorithm/array/leetcode_7_test.cpp @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_7_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_7_TEST_HPP + +#include "leetcode_7.cpp" +#include + +namespace leetcode_7 { +using std::vector; + +TEST_CASE("1 [test_7]", "[test_7]") { + auto clas = leetcode_7::Solution(); + CHECK(clas.reverse(123) == 321); + CHECK(clas.reverse2(123) == 321); + CHECK(clas.reverse3(123) == 321); +} + +TEST_CASE("2 [test_7]", "[test_7]") { + auto clas = leetcode_7::Solution(); + CHECK(clas.reverse(-123) == -321); + CHECK(clas.reverse2(-123) == -321); + CHECK(clas.reverse3(-123) == -321); +} + +TEST_CASE("3 [test_7]", "[test_7]") { + auto clas = leetcode_7::Solution(); + CHECK(clas.reverse(120) == 21); + CHECK(clas.reverse2(120) == 21); + CHECK(clas.reverse3(120) == 21); +} + +TEST_CASE("4 [test_7]", "[test_7]") { + auto clas = leetcode_7::Solution(); + CHECK(clas.reverse(0) == 0); + CHECK(clas.reverse2(0) == 0); + CHECK(clas.reverse3(0) == 0); +} + +TEST_CASE("5 [test_7]", "[test_7]") { + auto clas = leetcode_7::Solution(); + CHECK(clas.reverse(-2147483648) == 0); + CHECK(clas.reverse2(-2147483648) == 0); + CHECK(clas.reverse3(-2147483648) == 0); +} + +TEST_CASE("6 [test_7]", "[test_7]") { + auto clas = leetcode_7::Solution(); + CHECK(clas.reverse(1463847412) == 2147483641); + CHECK(clas.reverse2(1463847412) == 2147483641); + CHECK(clas.reverse3(1463847412) == 2147483641); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_7_TEST_HPP diff --git a/algorithm/array/leetcode_7_test.hpp b/algorithm/array/leetcode_7_test.hpp deleted file mode 100644 index 3e8be326..00000000 --- a/algorithm/array/leetcode_7_test.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_7_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_7_TEST_HPP - -#include -#include -#include - -namespace leetcode_7 { - -struct leetcode_7 { - static int32_t reverse(int32_t x); - - static int32_t reverse2(int32_t x); - - static int32_t reverse3(int32_t x); -}; - -TEST_CASE("1 [test_7]", "[test_7]") { - CHECK(leetcode_7::reverse(123) == 321); - CHECK(leetcode_7::reverse2(123) == 321); - CHECK(leetcode_7::reverse3(123) == 321); -} - -TEST_CASE("2 [test_7]", "[test_7]") { - CHECK(leetcode_7::reverse(-123) == -321); - CHECK(leetcode_7::reverse2(-123) == -321); - CHECK(leetcode_7::reverse3(-123) == -321); -} - -TEST_CASE("3 [test_7]", "[test_7]") { - CHECK(leetcode_7::reverse(120) == 21); - CHECK(leetcode_7::reverse2(120) == 21); - CHECK(leetcode_7::reverse3(120) == 21); -} - -TEST_CASE("4 [test_7]", "[test_7]") { - CHECK(leetcode_7::reverse(0) == 0); - CHECK(leetcode_7::reverse2(0) == 0); - CHECK(leetcode_7::reverse3(0) == 0); -} - -TEST_CASE("5 [test_7]", "[test_7]") { - CHECK(leetcode_7::reverse(-2147483648) == 0); - CHECK(leetcode_7::reverse2(-2147483648) == 0); - CHECK(leetcode_7::reverse3(-2147483648) == 0); -} - -TEST_CASE("6 [test_7]", "[test_7]") { - CHECK(leetcode_7::reverse(1463847412) == 2147483641); - CHECK(leetcode_7::reverse2(1463847412) == 2147483641); - CHECK(leetcode_7::reverse3(1463847412) == 2147483641); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_7_TEST_HPP diff --git a/algorithm/array/leetcode_80.cpp b/algorithm/array/leetcode_80.cpp index 7ab096b7..ce3251fb 100644 --- a/algorithm/array/leetcode_80.cpp +++ b/algorithm/array/leetcode_80.cpp @@ -1,47 +1,51 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_80_test.hpp" +#include +#include namespace leetcode_80 { +using std::vector; +#endif - -int32_t leetcode_80::removeDuplicates(vector &nums) { - size_t s{nums.size()}; - if (s <= 2) { - return static_cast(s); - } - int32_t number{nums[0]}; - size_t number_c{1}, insert_count{0}, count{1}; - while (count < s) { - if (number == nums[count]) { - number_c++; - if (number_c == 2) { - while (count < s && number == nums[count]) { - count++; +class Solution { +public: + int32_t removeDuplicates(vector &nums) { + size_t s{nums.size()}; + if (s <= 2) { + return static_cast(s); + } + int32_t number{nums[0]}; + size_t number_c{1}, insert_count{0}, count{1}; + while (count < s) { + if (number == nums[count]) { + number_c++; + if (number_c == 2) { + while (count < s && number == nums[count]) { + count++; + } } + } else { + while (number_c > 0) { + nums[insert_count] = number; + insert_count++; + number_c--; + } + number = nums[count]; + number_c = 1; + count++; } - } else { - while (number_c > 0) { - nums[insert_count] = number; - insert_count++; - number_c--; - } - number = nums[count]; - number_c = 1; - count++; } + while (number_c > 0) { + nums[insert_count] = number; + insert_count++; + number_c--; + } + return static_cast(insert_count); } - while (number_c > 0) { - nums[insert_count] = number; - insert_count++; - number_c--; - } - return static_cast(insert_count); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_804.cpp b/algorithm/array/leetcode_804.cpp index 296f48f5..b3897e0b 100644 --- a/algorithm/array/leetcode_804.cpp +++ b/algorithm/array/leetcode_804.cpp @@ -1,36 +1,45 @@ - // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_804_test.hpp" +#include +#include +#include #include namespace leetcode_804 { +using std::vector; +using std::string; +using std::array; using std::unordered_set; +#endif -int32_t leetcode_804::uniqueMorseRepresentations(const vector &words) { - static constexpr const std::array asks = {".-", "-...", "-.-.", "-..", - ".", "..-.", "--.", "....", - "..", ".---", "-.-", - ".-..", "--", "-.", "---", - ".--.", "--.-", ".-.", "...", - "-", "..-", "...-", ".--", - "-..-", "-.--", "--.."}; - unordered_set uset; - for (const auto &word: words) { - string temp; - temp.reserve(4 * word.size()); - for (const auto wchar: word) { - temp += asks[wchar - 97]; - } - if (uset.count(temp) == 0) { - uset.insert(temp); +class Solution { +public: + int32_t uniqueMorseRepresentations(vector &words) { + static constexpr const array asks = {".-", "-...", "-.-.", "-..", + ".", "..-.", "--.", "....", + "..", ".---", "-.-", + ".-..", "--", "-.", "---", + ".--.", "--.-", ".-.", "...", + "-", "..-", "...-", ".--", + "-..-", "-.--", "--.."}; + unordered_set uset; + for (const auto &word: words) { + string temp; + temp.reserve(4 * word.size()); + for (const auto wchar: word) { + temp += asks[wchar - 97]; + } + if (uset.count(temp) == 0) { + uset.insert(temp); + } } + return uset.size(); } - return uset.size(); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_804_test.cpp b/algorithm/array/leetcode_804_test.cpp new file mode 100644 index 00000000..7da1c140 --- /dev/null +++ b/algorithm/array/leetcode_804_test.cpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_804_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_804_TEST_HPP + +#include +#include "leetcode_804.cpp" + +namespace leetcode_804 { +TEST_CASE("test case 1 [test_804]", "[test_804]") { + static constexpr const std::array inputs{"gin", "zen", "gig", "msg"}; + static constexpr const auto result{2}; + std::vector input_vec{inputs.cbegin(), inputs.cend()}; + Solution solution; + CHECK(result == solution.uniqueMorseRepresentations(input_vec)); +} + +TEST_CASE("test case 2 [test_804]", "[test_804]") { + static constexpr const std::array inputs{"a"}; + static constexpr const auto result{1}; + std::vector input_vec{inputs.cbegin(), inputs.cend()}; + Solution solution; + CHECK(result == solution.uniqueMorseRepresentations(input_vec)); +} +} + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_804_TEST_HPP diff --git a/algorithm/array/leetcode_804_test.hpp b/algorithm/array/leetcode_804_test.hpp deleted file mode 100644 index 7430ba24..00000000 --- a/algorithm/array/leetcode_804_test.hpp +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_804_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_804_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_804 { -using std::vector; -using std::array; - -struct leetcode_804 { - static int32_t uniqueMorseRepresentations(const vector &words); -}; - -TEST_CASE("test case 1 [test_804]", "[test_804]") { - static constexpr const std::array inputs{"gin", "zen", "gig", "msg"}; - static constexpr const auto result{2}; - CHECK(result == leetcode_804::uniqueMorseRepresentations({inputs.cbegin(), inputs.cend()})); -} - -TEST_CASE("test case 2 [test_804]", "[test_804]") { - static constexpr const std::array inputs{"a"}; - static constexpr const auto result{1}; - CHECK(result == leetcode_804::uniqueMorseRepresentations({inputs.cbegin(), inputs.cend()})); - -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_804_TEST_HPP diff --git a/algorithm/array/leetcode_806.cpp b/algorithm/array/leetcode_806.cpp index fa63013f..a601ed85 100644 --- a/algorithm/array/leetcode_806.cpp +++ b/algorithm/array/leetcode_806.cpp @@ -1,27 +1,33 @@ - // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_806_test.hpp" +#include +#include namespace leetcode_806 { +using std::vector; +using std::string; +#endif -vector leetcode_806::numberOfLines(const vector &widths, const string &S) { - const auto number_of_a{97}; - int line{1}, number{0}; - for (const auto ch: S) { - if (number + widths[ch - number_of_a] <= 100) { - number += widths[ch - number_of_a]; - } else { - number = widths[ch - number_of_a]; - line += 1; +class Solution { +public: + vector numberOfLines(const vector &widths, const string &S) { + const auto number_of_a{97}; + int32_t line{1}, number{0}; + for (const auto ch: S) { + if (number + widths[ch - number_of_a] <= 100) { + number += widths[ch - number_of_a]; + } else { + number = widths[ch - number_of_a]; + line += 1; + } } + return {line, number}; } - return {line, number}; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_806_test.cpp b/algorithm/array/leetcode_806_test.cpp new file mode 100644 index 00000000..69b37af7 --- /dev/null +++ b/algorithm/array/leetcode_806_test.cpp @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_806_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_806_TEST_HPP + +#include +#include "leetcode_806.cpp" +#include + +using Catch::Matchers::Equals; + +namespace leetcode_806 { +using std::array; + +TEST_CASE("test case 1 [test_806]", "[test_806]") { + static constexpr const array inputs{10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + 10, 10, 10}; + static constexpr const char *const str{"abcdefghijklmnopqrstuvwxyz"}; + static constexpr const auto begin{3}, end{60}; + Solution solution; + CHECK_THAT( + (std::vector{begin, end}), + Equals(solution.numberOfLines({inputs.begin(), inputs.end()}, str)) + ); +} + +TEST_CASE("test case 2 [test_806]", "[test_806]") { + static constexpr const array inputs{4, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 10, + 10, 10, 10}; + static constexpr const char *const str{"bbbcccdddaaa"}; + static constexpr const auto begin{2}, end{4}; + Solution solution; + CHECK_THAT( + (std::vector{begin, end}), + Equals(solution.numberOfLines({inputs.begin(), inputs.end()}, str)) + ); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_806_TEST_HPP diff --git a/algorithm/array/leetcode_806_test.hpp b/algorithm/array/leetcode_806_test.hpp deleted file mode 100644 index 43307ce9..00000000 --- a/algorithm/array/leetcode_806_test.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_806_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_806_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_806 { -using std::vector; -using std::array; - -struct leetcode_806 { - static vector numberOfLines(const vector &widths, const string &s); -}; -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_806]", "[test_806]") { - static constexpr const std::array inputs{10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, - 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, - 10, 10, 10}; - static constexpr const char *const str{"abcdefghijklmnopqrstuvwxyz"}; - static constexpr const auto begin{3}, end{60}; - CHECK_THAT( - (vector{begin, end}), - Equals(leetcode_806::numberOfLines({inputs.begin(), inputs.end()}, str)) - ); -} - -TEST_CASE("test case 2 [test_806]", "[test_806]") { - static constexpr const std::array inputs{4, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, - 10, 10, 10}; - static constexpr const char *const str{"bbbcccdddaaa"}; - static constexpr const auto begin{2}, end{4}; - CHECK_THAT( - (vector{begin, end}), - Equals(leetcode_806::numberOfLines({inputs.begin(), inputs.end()}, str)) - ); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_806_TEST_HPP diff --git a/algorithm/array/leetcode_807.cpp b/algorithm/array/leetcode_807.cpp index 55f76f36..c3b2d868 100644 --- a/algorithm/array/leetcode_807.cpp +++ b/algorithm/array/leetcode_807.cpp @@ -1,39 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_807_test.hpp" +#include +#include +#include namespace leetcode_807 { -int leetcode_807::maxIncreaseKeepingSkyline(const vector> &grid) { - const auto m = grid.size(); - if (m == 0) { - return 0; - } - vector row{}, line{}; - row.reserve(m); - line.reserve(m); - // ps, in this matrix, .size() == .front().size() - for (size_t i{0}; i < m; ++i) { - int32_t maxrow{-1}, maxline{-1}; - for (size_t j{0}; j < m; ++j) { - maxrow = std::max(maxrow, grid[i][j]); - maxline = std::max(maxline, grid[j][i]); +using std::vector; +#endif + +class Solution { +public: + int32_t maxIncreaseKeepingSkyline(const vector> &grid) { + const auto m = grid.size(); + if (m == 0) { + return 0; } - row.push_back(maxrow); - line.push_back(maxline); - } - int willreturn{0}; - for (size_t i{0}; i < m; ++i) { - for (size_t j{0}; j < m; ++j) { - willreturn += std::min(row[i], line[j]) - grid[i][j]; + vector row{}, line{}; + row.reserve(m); + line.reserve(m); + // ps, in this matrix, .size() == .front().size() + for (size_t i{0}; i < m; ++i) { + int32_t maxrow{-1}, maxline{-1}; + for (size_t j{0}; j < m; ++j) { + maxrow = std::max(maxrow, grid[i][j]); + maxline = std::max(maxline, grid[j][i]); + } + row.push_back(maxrow); + line.push_back(maxline); + } + int32_t willreturn{0}; + for (size_t i{0}; i < m; ++i) { + for (size_t j{0}; j < m; ++j) { + willreturn += std::min(row[i], line[j]) - grid[i][j]; + } } + return willreturn; } - return willreturn; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_807_test.hpp b/algorithm/array/leetcode_807_test.cpp similarity index 52% rename from algorithm/array/leetcode_807_test.hpp rename to algorithm/array/leetcode_807_test.cpp index 3dd756dd..c01e0d24 100644 --- a/algorithm/array/leetcode_807_test.hpp +++ b/algorithm/array/leetcode_807_test.cpp @@ -1,30 +1,22 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_807_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_807_TEST_HPP + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_807_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_807_TEST_HPP #include -#include -#include -#include -#include + + +#include "leetcode_807.cpp" namespace leetcode_807 { using std::vector; using std::array; -struct leetcode_807 { - static int maxIncreaseKeepingSkyline(const vector> &grid); -}; - TEST_CASE("test case 1 {test_807}", "{test_807}") { + Solution solution; const vector> heights{ {3, 0, 8, 4}, {2, 4, 5, 7}, @@ -32,17 +24,18 @@ TEST_CASE("test case 1 {test_807}", "{test_807}") { {0, 3, 1, 0} }; static constexpr const auto result{35}; - CHECK(result == leetcode_807::maxIncreaseKeepingSkyline(heights)); + CHECK(result == solution.maxIncreaseKeepingSkyline(heights)); } TEST_CASE("test case 2 {test_807}", "{test_807}") { + Solution solution; const vector> heights{ {0, 0, 0}, {0, 0, 0}, {0, 0, 0} }; static constexpr const auto result{0}; - CHECK(result == leetcode_807::maxIncreaseKeepingSkyline(heights)); + CHECK(result == solution.maxIncreaseKeepingSkyline(heights)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_807_TEST_HPP +#endif // ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_807_TEST_HPP diff --git a/algorithm/array/leetcode_80_test.hpp b/algorithm/array/leetcode_80_test.cpp similarity index 59% rename from algorithm/array/leetcode_80_test.hpp rename to algorithm/array/leetcode_80_test.cpp index 74ab6cac..f9ad770b 100644 --- a/algorithm/array/leetcode_80_test.hpp +++ b/algorithm/array/leetcode_80_test.cpp @@ -1,34 +1,27 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag 双指针 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_80_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_80_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_80_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_80_TEST_HPP #include #include #include #include +#include "leetcode_80.cpp" namespace leetcode_80 { using std::vector; -struct leetcode_80 { - static int32_t removeDuplicates(vector &nums); -}; - using Catch::Matchers::Equals; TEST_CASE("1 [test_80]", "[test_80]") { vector input{0, 0, 1, 1, 1, 1, 2, 3, 3}; const vector result{0, 0, 1, 1, 2, 3, 3}; - const auto size = leetcode_80::removeDuplicates(input); + Solution solution; + const auto size = solution.removeDuplicates(input); input.resize(size); CHECK_THAT(input, Equals(result)); } @@ -36,9 +29,10 @@ TEST_CASE("1 [test_80]", "[test_80]") { TEST_CASE("2 [test_80]", "[test_80]") { vector input{1, 1, 1, 2, 2, 3}; const vector result{1, 1, 2, 2, 3}; - const auto size = leetcode_80::removeDuplicates(input); + Solution solution; + const auto size = solution.removeDuplicates(input); input.resize(size); CHECK_THAT(input, Equals(result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_80_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_80_TEST_HPP diff --git a/algorithm/array/leetcode_811.cpp b/algorithm/array/leetcode_811.cpp index 5e3c1651..0faf2147 100644 --- a/algorithm/array/leetcode_811.cpp +++ b/algorithm/array/leetcode_811.cpp @@ -1,54 +1,65 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_811_test.hpp" +#include +#include #include +#include +#include namespace leetcode_811 { +using std::vector; +using std::string; using std::unordered_map; +using std::make_pair; +#endif -inline int getNumber(const string &str) { - return (std::stoi(str.substr(0, str.find(' ')))); -} - -vector getDomains(string &str) { - str = (str.substr(str.find(' ') + 1, str.size())); - vector willreturn{str}; - while (count(str.begin(), str.end(), '.') != 0) { - str = str.substr(str.find('.') + 1, str.size()); - willreturn.push_back(str); +class Solution { +private: + inline int32_t getNumber(const string &str) { + return (std::stoi(str.substr(0, str.find(' ')))); } - return willreturn; -} -vector leetcode_811::subdomainVisits(const vector &cpd) { - vector willreturn; - unordered_map umaps; - const auto m = cpd.size(); - if (m == 0) { + vector getDomains(string &str) { + str = (str.substr(str.find(' ') + 1, str.size())); + vector willreturn{str}; + while (count(str.begin(), str.end(), '.') != 0) { + str = str.substr(str.find('.') + 1, str.size()); + willreturn.push_back(str); + } return willreturn; } - for (size_t i{0}; i < m; ++i) { - string element = cpd[i]; - const auto number = getNumber(element); - vector domain = getDomains(element); - const auto n = domain.size(); - for (size_t j{0}; j < n; ++j) { - if (umaps.count(domain[j]) == 0) { - umaps.insert(make_pair(domain[j], number)); - } else { - umaps[domain[j]] += number; + +public: + vector subdomainVisits(const vector &cpd) { + vector willreturn; + unordered_map umaps; + const auto m = cpd.size(); + if (m == 0) { + return willreturn; + } + for (size_t i{0}; i < m; ++i) { + string element = cpd[i]; + const auto number = getNumber(element); + vector domain = getDomains(element); + const auto n = domain.size(); + for (size_t j{0}; j < n; ++j) { + if (umaps.count(domain[j]) == 0) { + umaps.insert(make_pair(domain[j], number)); + } else { + umaps[domain[j]] += number; + } } } + for (auto &umap: umaps) { + willreturn.push_back(std::to_string(umap.second) + " " + umap.first); + } + return willreturn; } - for (auto & umap : umaps) { - willreturn.push_back(std::to_string(umap.second) + " " + umap.first); - } - return willreturn; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_811_test.hpp b/algorithm/array/leetcode_811_test.cpp similarity index 62% rename from algorithm/array/leetcode_811_test.hpp rename to algorithm/array/leetcode_811_test.cpp index 71a4c70f..789522fa 100644 --- a/algorithm/array/leetcode_811_test.hpp +++ b/algorithm/array/leetcode_811_test.cpp @@ -1,41 +1,28 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_811_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_811_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_811_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_811_TEST_HPP #include -#include -#include -#include -#include +#include "leetcode_811.cpp" namespace leetcode_811 { -using std::vector; -using std::array; - -struct leetcode_811 { - static vector subdomainVisits(const vector &cpdomains); -}; - using Catch::Matchers::UnorderedEquals; TEST_CASE("test case 1 [test_811]", "[test_811]") { + Solution solution; static constexpr const std::array inputs{"9001 discuss.leetcode.com"}; static constexpr const std::array results{ "9001 leetcode.com", "9001 discuss.leetcode.com", "9001 com" }; CHECK_THAT((vector{results.cbegin(), results.cend()}), - UnorderedEquals(leetcode_811::subdomainVisits({inputs.cbegin(), inputs.cend()}))); + UnorderedEquals(solution.subdomainVisits({inputs.cbegin(), inputs.cend()}))); } TEST_CASE("test case 2 [test_811]", "[test_811]") { + Solution solution; static constexpr const std::array inputs{"900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "114514 wiki.org"}; static constexpr const std::array results{ @@ -43,7 +30,7 @@ TEST_CASE("test case 2 [test_811]", "[test_811]") { "114514 wiki.org", "114514 org", "1 intel.mail.com", "951 com" }; CHECK_THAT((vector{results.cbegin(), results.cend()}), - UnorderedEquals(leetcode_811::subdomainVisits({inputs.cbegin(), inputs.cend()}))); + UnorderedEquals(solution.subdomainVisits({inputs.cbegin(), inputs.cend()}))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_811_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_811_TEST_HPP diff --git a/algorithm/array/leetcode_830.cpp b/algorithm/array/leetcode_830.cpp index 49889809..82f7b8f4 100644 --- a/algorithm/array/leetcode_830.cpp +++ b/algorithm/array/leetcode_830.cpp @@ -1,34 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_830_test.hpp" +#include +#include +#include namespace leetcode_830 { +using std::vector; +using std::string; +#endif -vector> leetcode_830::largeGroupPositions(const string &S) { - int end{1}, length{1}; - vector> willreturn{}; - const auto s_size{static_cast(S.size())}; - for (int32_t i{1}; i < s_size; ++i) { - end = i; - if (S[i] == S[i - 1]) { - length++; - } else { - if (length >= 3) { - willreturn.push_back({end - length, end - 1}); +class Solution { +public: + vector> largeGroupPositions(const string &S) { + int32_t end{1}, length{1}; + vector> willreturn{}; + const auto s_size{static_cast(S.size())}; + for (int32_t i{1}; i < s_size; ++i) { + end = i; + if (S[i] == S[i - 1]) { + length++; + } else { + if (length >= 3) { + willreturn.push_back({end - length, end - 1}); + } + length = 1; } - length = 1; } + if (length >= 3) { + willreturn.push_back({end - length + 1, end}); + } + return willreturn; } - if (length >= 3) { - willreturn.push_back({end - length + 1, end}); - } - return willreturn; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_830_test.cpp b/algorithm/array/leetcode_830_test.cpp new file mode 100644 index 00000000..9e868e2e --- /dev/null +++ b/algorithm/array/leetcode_830_test.cpp @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_830_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_830_TEST_HPP + +#include +#include +#include +#include "leetcode_830.cpp" + +namespace leetcode_830 { +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_830]", "[test_830]") { + Solution solution; + static constexpr const char *const input{"abbxxxxzzy"}; + const vector> output{{3, 6}}; + CHECK_THAT(output, Equals(solution.largeGroupPositions(input))); +} + +TEST_CASE("test case 2 [test_830]", "[test_830]") { + Solution solution; + static constexpr const char *const input{"abc"}; + const vector> output{}; + CHECK_THAT(output, Equals(solution.largeGroupPositions(input))); +} + +TEST_CASE("test case 3 [test_830]", "[test_830]") { + Solution solution; + static constexpr const char *const input{"abcdddeeeeaabbbcd"}; + const vector> output{{3, 5}, + {6, 9}, + {12, 14}}; + CHECK_THAT(output, Equals(solution.largeGroupPositions(input))); +} + +TEST_CASE("test case 4 [test_830]", "[test_830]") { + Solution solution; + static constexpr const char *const input{"abz"}; + const vector> output{}; + CHECK_THAT(output, Equals(solution.largeGroupPositions(input))); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_830_TEST_HPP diff --git a/algorithm/array/leetcode_830_test.hpp b/algorithm/array/leetcode_830_test.hpp deleted file mode 100644 index 80fb79b4..00000000 --- a/algorithm/array/leetcode_830_test.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_830_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_830_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_830 { -using std::vector; -using std::string; - -struct leetcode_830 { - static vector> largeGroupPositions(const string &s); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_830]", "[test_830]") { - static constexpr const char *const input{"abbxxxxzzy"}; - const vector> output{{3, 6}}; - CHECK_THAT(output, Equals(leetcode_830::largeGroupPositions(input))); -} - -TEST_CASE("test case 2 [test_830]", "[test_830]") { - static constexpr const char *const input{"abc"}; - const vector> output{}; - CHECK_THAT(output, Equals(leetcode_830::largeGroupPositions(input))); -} - -TEST_CASE("test case 3 [test_830]", "[test_830]") { - static constexpr const char *const input{"abcdddeeeeaabbbcd"}; - const vector> output{{3, 5}, {6, 9}, {12, 14}}; - CHECK_THAT(output, Equals(leetcode_830::largeGroupPositions(input))); -} -TEST_CASE("test case 4 [test_830]", "[test_830]") { - static constexpr const char *const input{"abz"}; - const vector> output{}; - CHECK_THAT(output, Equals(leetcode_830::largeGroupPositions(input))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_830_TEST_HPP diff --git a/algorithm/array/leetcode_832.cpp b/algorithm/array/leetcode_832.cpp index 5d874e6f..92b76eff 100644 --- a/algorithm/array/leetcode_832.cpp +++ b/algorithm/array/leetcode_832.cpp @@ -1,38 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_832_test.hpp" +#include +#include namespace leetcode_832 { +using std::vector; +#endif -vector> leetcode_832::flipAndInvertImageConst(const vector> &image) { - const auto m{image.size()}; - if (m == 0) { - return image; - } - const auto n{image.front().size()}; - if (n == 0) { - return image; - } - vector> result(image); - vector traverse(n); - for (size_t i{0}; i < m; ++i) { - for (size_t left{0}, right{n - 1}; left < right && right < n; ++left, --right) { - if (image[i][left] == image[i][right]) { - result[i][left] = !image[i][left]; - result[i][right] = !image[i][right]; - } +class Solution { +public: + vector> flipAndInvertImage(vector> &image) { + const auto m{image.size()}; + if (m == 0) { + return image; } - if (n % 2 == 1) { - result[i][n / 2] = !image[i][n / 2]; + const auto n{image.front().size()}; + if (n == 0) { + return image; } + vector> result(image); + vector traverse(n); + for (size_t i{0}; i < m; ++i) { + for (size_t left{0}, right{n - 1}; left < right && right < n; ++left, --right) { + if (image[i][left] == image[i][right]) { + result[i][left] = !image[i][left]; + result[i][right] = !image[i][right]; + } + } + if (n % 2 == 1) { + result[i][n / 2] = !image[i][n / 2]; + } + } + return result; } - return result; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_832_test.cpp b/algorithm/array/leetcode_832_test.cpp new file mode 100644 index 00000000..fa6492ca --- /dev/null +++ b/algorithm/array/leetcode_832_test.cpp @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_832_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_832_TEST_HPP + +#include +#include "leetcode_832.cpp" +#include + +namespace leetcode_832 { +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_832]", "[test_832]") { + Solution solution; + vector> inputs{{1, 1, 0}, + {1, 0, 1}, + {0, 0, 0}}; + const vector> result{ + {1, 0, 0}, + {0, 1, 0}, + {1, 1, 1}, + }; + CHECK_THAT(result, Equals(solution.flipAndInvertImage(inputs))); +} + +TEST_CASE("test case 2 [test_832]", "[test_832]") { + Solution solution; + vector> inputs{{1, 1, 0, 0}, + {1, 0, 0, 1}, + {0, 1, 1, 1}, + {1, 0, 1, 0} + }; + const vector> result{ + {1, 1, 0, 0}, + {0, 1, 1, 0}, + {0, 0, 0, 1}, + {1, 0, 1, 0} + }; + CHECK_THAT(result, Equals(solution.flipAndInvertImage(inputs))); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_832_TEST_HPP diff --git a/algorithm/array/leetcode_832_test.hpp b/algorithm/array/leetcode_832_test.hpp deleted file mode 100644 index dc9b7445..00000000 --- a/algorithm/array/leetcode_832_test.hpp +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_832_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_832_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_832 { -using std::vector; - -struct leetcode_832 { - static vector> flipAndInvertImageConst(const vector> &image); - -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_832]", "[test_832]") { - const vector> inputs{{1, 1, 0}, - {1, 0, 1}, - {0, 0, 0}}; - const vector> result{ - {1, 0, 0}, - {0, 1, 0}, - {1, 1, 1}, - }; - CHECK_THAT(result, Equals(leetcode_832::flipAndInvertImageConst(inputs))); -} - -TEST_CASE("test case 2 [test_832]", "[test_832]") { - const vector> inputs{{1, 1, 0, 0}, - {1, 0, 0, 1}, - {0, 1, 1, 1}, - {1, 0, 1, 0} - }; - const vector> result{ - {1, 1, 0, 0}, - {0, 1, 1, 0}, - {0, 0, 0, 1}, - {1, 0, 1, 0} - }; - CHECK_THAT(result, Equals(leetcode_832::flipAndInvertImageConst(inputs))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_832_TEST_HPP diff --git a/algorithm/array/leetcode_840.cpp b/algorithm/array/leetcode_840.cpp index 66e523df..eb1663ae 100644 --- a/algorithm/array/leetcode_840.cpp +++ b/algorithm/array/leetcode_840.cpp @@ -1,52 +1,59 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_840_test.hpp" +#include +#include namespace leetcode_840 { +using std::vector; +#endif -bool numMagicSquaresInside_help(const vector> &grid, size_t x, size_t y) { - for (size_t i{0}; i < 3; ++i) { - for (size_t j{0}; j < 3; ++j) { - if (grid[x + i][y + j] > 9 || grid[x + i][y + j] < 1) { - return false; +class Solution { +private: + bool isMagic(const vector> &grid, size_t x, size_t y) { + for (size_t i{0}; i < 3; ++i) { + for (size_t j{0}; j < 3; ++j) { + if (grid[x + i][y + j] > 9 || grid[x + i][y + j] < 1) { + return false; + } } } + return ( + // 中间需要是五 + grid[x + 1][y + 1] == 5 && + grid[x][y] + grid[x + 2][y + 2] == 10 && + grid[x + 1][y] + grid[x + 1][y + 2] == 10 && + grid[x + 2][y] + grid[x][y + 2] == 10 && + grid[x][y] != grid[x + 2][y + 2] && + grid[x + 1][y] != grid[x + 1][y + 2] && + grid[x + 2][y] != grid[x][y + 2] && + grid[x][y] + grid[x][y + 1] + grid[x][y + 2] == 15 && + grid[x][y] + grid[x + 1][y] + grid[x + 2][y] == 15 && + grid[x + 2][y] + grid[x + 2][y + 1] + grid[x + 2][y + 2] == 15 + ); } - return ( - // 中间需要是五 - grid[x + 1][y + 1] == 5 && - grid[x][y] + grid[x + 2][y + 2] == 10 && - grid[x + 1][y] + grid[x + 1][y + 2] == 10 && - grid[x + 2][y] + grid[x][y + 2] == 10 && - grid[x][y] != grid[x + 2][y + 2] && - grid[x + 1][y] != grid[x + 1][y + 2] && - grid[x + 2][y] != grid[x][y + 2] && - grid[x][y] + grid[x][y + 1] + grid[x][y + 2] == 15 && - grid[x][y] + grid[x + 1][y] + grid[x + 2][y] == 15 && - grid[x + 2][y] + grid[x + 2][y + 1] + grid[x + 2][y + 2] == 15 - ); -} -int leetcode_840::numMagicSquaresInside(const vector> &grid) { - const auto m{grid.size()}; - if (m < 3) { - return 0; - } - const auto n{grid.size()}; - if (n < 3) { - return 0; - } - int count = 0; - for (size_t i{0}; i + 3 <= m; ++i) { - for (size_t j{0}; j + 3 <= n; ++j) { - count += numMagicSquaresInside_help(grid, i, j); +public: + int32_t numMagicSquaresInside(const vector> &grid) { + const auto m{grid.size()}; + if (m < 3) { + return 0; + } + const auto n{grid.size()}; + if (n < 3) { + return 0; } + int count = 0; + for (size_t i{0}; i + 3 <= m; ++i) { + for (size_t j{0}; j + 3 <= n; ++j) { + count += isMagic(grid, i, j); + } + } + return count; } - return count; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_840_test.hpp b/algorithm/array/leetcode_840_test.cpp similarity index 55% rename from algorithm/array/leetcode_840_test.hpp rename to algorithm/array/leetcode_840_test.cpp index 3c2f20ac..59090a02 100644 --- a/algorithm/array/leetcode_840_test.hpp +++ b/algorithm/array/leetcode_840_test.cpp @@ -1,46 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_840_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_840_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_840_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_840_TEST_HPP #include -#include -#include +#include "leetcode_840.cpp" #include namespace leetcode_840 { -using std::vector; - -struct leetcode_840 { - static int numMagicSquaresInside(const vector> &grid); -}; - TEST_CASE("test case 1 [test_840]", "[test_840]") { + Solution solution; const vector> inputs{{4, 3, 8, 4}, {9, 5, 1, 9}, {2, 7, 6, 2}}; static constexpr const auto result{1}; - CHECK(result == leetcode_840::numMagicSquaresInside(inputs)); + CHECK(result == solution.numMagicSquaresInside(inputs)); } TEST_CASE("test case 2 [test_840]", "[test_840]") { + Solution solution; const vector> inputs{{8}}; static constexpr const auto result{0}; - CHECK(result == leetcode_840::numMagicSquaresInside(inputs)); + CHECK(result == solution.numMagicSquaresInside(inputs)); } TEST_CASE("test case 3 [test_840]", "[test_840]") { + Solution solution; const vector> inputs{{1, 1, 4}, {5, 1, 4}}; static constexpr const auto result{0}; - CHECK(result == leetcode_840::numMagicSquaresInside(inputs)); + CHECK(result == solution.numMagicSquaresInside(inputs)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_840_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_840_TEST_HPP diff --git a/algorithm/array/leetcode_849.cpp b/algorithm/array/leetcode_849.cpp index 1fc0eaba..b6b09a69 100644 --- a/algorithm/array/leetcode_849.cpp +++ b/algorithm/array/leetcode_849.cpp @@ -1,29 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_849_test.hpp" +#include +#include +#include +#include namespace leetcode_849 { +using std::vector; +#endif -int32_t leetcode_849::numMagicSquaresInside(const vector &seats) { - vector left(seats), right(seats); - const auto size{seats.size()}; - left[0] = (seats[0] == 1) ? 0 : std::numeric_limits::max(); - right[size - 1] = (seats[size - 1] == 1) ? 0 : std::numeric_limits::max(); - for (size_t i{1}; i < size; ++i) { - left[i] = (seats[i] == 1) ? 0 : left[i - 1] + 1; - } - for (size_t i = size; i >= 2; --i) { - right[i - 2] = (seats[i - 2] == 1) ? 0 : right[i - 1] + 1; - } - int will_return{std::numeric_limits::min()}; - for (size_t i{0}; i < size; ++i) { - will_return = std::max(will_return, std::min(left[i], right[i])); +class Solution { +public: + int32_t maxDistToClosest(const vector &seats) { + vector left(seats), right(seats); + const auto size{seats.size()}; + left[0] = (seats[0] == 1) ? 0 : std::numeric_limits::max(); + right[size - 1] = (seats[size - 1] == 1) ? 0 : std::numeric_limits::max(); + for (size_t i{1}; i < size; ++i) { + left[i] = (seats[i] == 1) ? 0 : left[i - 1] + 1; + } + for (size_t i = size; i >= 2; --i) { + right[i - 2] = (seats[i - 2] == 1) ? 0 : right[i - 1] + 1; + } + int will_return{std::numeric_limits::min()}; + for (size_t i{0}; i < size; ++i) { + will_return = std::max(will_return, std::min(left[i], right[i])); + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_849_test.hpp b/algorithm/array/leetcode_849_test.cpp similarity index 51% rename from algorithm/array/leetcode_849_test.hpp rename to algorithm/array/leetcode_849_test.cpp index f51cd68b..dcb33720 100644 --- a/algorithm/array/leetcode_849_test.hpp +++ b/algorithm/array/leetcode_849_test.cpp @@ -1,49 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_849_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_849_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_849_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_849_TEST_HPP #include -#include -#include #include +#include "leetcode_849.cpp" namespace leetcode_849 { -using std::vector; - -struct leetcode_849 { - static int32_t numMagicSquaresInside(const vector &seats); -}; - TEST_CASE("test case 1 [test_849]", "[test_849]") { + Solution solution; const vector inputs{1, 0, 0, 0, 1, 0, 1}; static constexpr const auto result{2}; - CHECK(result == leetcode_849::numMagicSquaresInside(inputs)); + CHECK(result == solution.maxDistToClosest(inputs)); } TEST_CASE("test case 2 [test_849]", "[test_849]") { + Solution solution; const vector inputs{1, 0, 0, 0}; static constexpr const auto result{3}; - CHECK(result == leetcode_849::numMagicSquaresInside(inputs)); + CHECK(result == solution.maxDistToClosest(inputs)); } TEST_CASE("test case 3 [test_849]", "[test_849]") { + Solution solution; const vector inputs{0, 0, 0, 0, 1}; static constexpr const auto result{4}; - CHECK(result == leetcode_849::numMagicSquaresInside(inputs)); + CHECK(result == solution.maxDistToClosest(inputs)); } TEST_CASE("test case 4 [test_849]", "[test_849]") { + Solution solution; const vector inputs{0, 1}; static constexpr const auto result{1}; - CHECK(result == leetcode_849::numMagicSquaresInside(inputs)); + CHECK(result == solution.maxDistToClosest(inputs)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_849_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_849_TEST_HPP diff --git a/algorithm/array/leetcode_852.cpp b/algorithm/array/leetcode_852.cpp index b6239652..9b868e54 100644 --- a/algorithm/array/leetcode_852.cpp +++ b/algorithm/array/leetcode_852.cpp @@ -1,26 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_852_test.hpp" +#include +#include namespace leetcode_852 { +using std::vector; +#endif -int32_t leetcode_852::peakIndexInMountainArray(const vector &A) { - int x1{0}, x4 = static_cast(A.size() - 1); - for (int x2{x1 + (x4 - x1) / 3}, x3{x1 + (x4 - x1) * 2 / 3}; x1 < x4;) { - int temp1 = A[x2], temp2 = A[x3]; - if (temp1 > temp2) { - x4 = x3; - } else { - x1 = x2 + 1; +class Solution { +public: + int32_t peakIndexInMountainArray(const vector &A) { + int x1{0}, x4 = static_cast(A.size() - 1); + for (int x2{x1 + (x4 - x1) / 3}, x3{x1 + (x4 - x1) * 2 / 3}; x1 < x4;) { + int temp1 = A[x2], temp2 = A[x3]; + if (temp1 > temp2) { + x4 = x3; + } else { + x1 = x2 + 1; + } + x2 = x1 + (x4 - x1) / 3; + x3 = x1 + (x4 - x1) * 2 / 3; } - x2 = x1 + (x4 - x1) / 3; - x3 = x1 + (x4 - x1) * 2 / 3; + return x1 - 1; } - return x1 - 1; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_852_test.hpp b/algorithm/array/leetcode_852_test.cpp similarity index 54% rename from algorithm/array/leetcode_852_test.hpp rename to algorithm/array/leetcode_852_test.cpp index 000ebc8a..5ad473d0 100644 --- a/algorithm/array/leetcode_852_test.hpp +++ b/algorithm/array/leetcode_852_test.cpp @@ -1,55 +1,48 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_852_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_852_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_852_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_852_TEST_HPP #include -#include -#include +#include "leetcode_852.cpp" #include namespace leetcode_852 { -using std::vector; - -struct leetcode_852 { - static int32_t peakIndexInMountainArray(const vector &A); -}; - TEST_CASE("test case 1 [test_852]", "[test_852]") { + Solution solution; const vector inputs{0, 1, 0}; static constexpr const auto result{1}; - CHECK(result == leetcode_852::peakIndexInMountainArray(inputs)); + CHECK(result == solution.peakIndexInMountainArray(inputs)); } TEST_CASE("test case 2 [test_852]", "[test_852]") { + Solution solution; const vector inputs{0, 2, 1, 0}; static constexpr const auto result{1}; - CHECK(result == leetcode_852::peakIndexInMountainArray(inputs)); + CHECK(result == solution.peakIndexInMountainArray(inputs)); } TEST_CASE("test case 3 [test_852]", "[test_852]") { + Solution solution; const vector inputs{0, 10, 5, 2}; static constexpr const auto result{1}; - CHECK(result == leetcode_852::peakIndexInMountainArray(inputs)); + CHECK(result == solution.peakIndexInMountainArray(inputs)); } TEST_CASE("test case 4 [test_852]", "[test_852]") { + Solution solution; const vector inputs{3, 4, 5, 1}; static constexpr const auto result{2}; - CHECK(result == leetcode_852::peakIndexInMountainArray(inputs)); + CHECK(result == solution.peakIndexInMountainArray(inputs)); } TEST_CASE("test case 5 [test_852]", "[test_852]") { + Solution solution; const vector inputs{24, 69, 100, 99, 79, 78, 67, 36, 26, 19}; static constexpr const auto result{2}; - CHECK(result == leetcode_852::peakIndexInMountainArray(inputs)); + CHECK(result == solution.peakIndexInMountainArray(inputs)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_852_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_852_TEST_HPP diff --git a/algorithm/array/leetcode_867.cpp b/algorithm/array/leetcode_867.cpp index 2194bb7c..4b6a728a 100644 --- a/algorithm/array/leetcode_867.cpp +++ b/algorithm/array/leetcode_867.cpp @@ -1,25 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_867_test.hpp" +#include +#include namespace leetcode_867 { -vector > leetcode_867::transpose(const vector > &A) { - const auto m{A.size()}; - if (m == 0) { - return {}; - } - const auto n{A[0].size()}; - vector > will_return(n, vector(m)); - for (size_t i{0}; i < n; ++i) { - for (size_t j{0}; j < m; ++j) { - will_return[i][j] = A[j][i]; +using std::vector; +#endif + +class Solution { +public: + vector> transpose(const vector> &A) { + const auto m{A.size()}; + if (m == 0) { + return {}; } + const auto n{A[0].size()}; + vector> will_return(n, vector(m)); + for (size_t i{0}; i < n; ++i) { + for (size_t j{0}; j < m; ++j) { + will_return[i][j] = A[j][i]; + } + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_867_test.hpp b/algorithm/array/leetcode_867_test.cpp similarity index 61% rename from algorithm/array/leetcode_867_test.hpp rename to algorithm/array/leetcode_867_test.cpp index c23fe410..cb60af41 100644 --- a/algorithm/array/leetcode_867_test.hpp +++ b/algorithm/array/leetcode_867_test.cpp @@ -1,46 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP #include -#include -#include #include +#include "leetcode_867.cpp" namespace leetcode_867 { -using std::vector; - -struct leetcode_867 { - static vector> transpose(const vector> &A); -}; using Catch::Matchers::Equals; TEST_CASE("test case 1 {test_867}", "{test_867}") { + Solution solution; const vector> inputs{{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}}; const vector> result{{{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}}; - CHECK_THAT(result, Equals(leetcode_867::transpose(inputs))); + CHECK_THAT(result, Equals(solution.transpose(inputs))); } TEST_CASE("test case 2 {test_867}", "{test_867}") { + Solution solution; const vector> inputs{{1, 2, 3}, {4, 5, 6}}; const vector> result{{1, 4}, {2, 5}, {3, 6}}; - CHECK_THAT(result, Equals(leetcode_867::transpose(inputs))); + CHECK_THAT(result, Equals(solution.transpose(inputs))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP diff --git a/algorithm/array/leetcode_868.cpp b/algorithm/array/leetcode_868.cpp index 57f9ca8d..f4a61314 100644 --- a/algorithm/array/leetcode_868.cpp +++ b/algorithm/array/leetcode_868.cpp @@ -1,34 +1,40 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_868_test.hpp" +#include +#include +#include namespace leetcode_868 { +using std::vector; +#endif -int32_t leetcode_868::binaryGap(int32_t N) { - vector ones; - ones.reserve(32); - while (N > 0) { - ones.push_back(N % 2); - N /= 2; - } - vector pos; - const auto ones_size{ones.size()}; - for (size_t i{0}; i < ones_size; ++i) { - if (1 == ones[i]) { - pos.push_back(i); +class Solution { +public: + int32_t binaryGap(int32_t N) { + vector ones; + ones.reserve(32); + while (N > 0) { + ones.push_back(N % 2); + N /= 2; } + vector pos; + const auto ones_size{ones.size()}; + for (size_t i{0}; i < ones_size; ++i) { + if (1 == ones[i]) { + pos.push_back(i); + } + } + const auto pos_size{pos.size()}; + size_t diff{0}; + for (size_t i{0}; i < pos_size - 1; i++) { + diff = std::max(diff, pos[i + 1] - pos[i]); + } + return static_cast(diff); } - const auto pos_size{pos.size()}; - size_t diff{0}; - for (size_t i{0}; i < pos_size - 1; i++) { - diff = std::max(diff, pos[i + 1] - pos[i]); - } - return static_cast(diff); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_868_test.hpp b/algorithm/array/leetcode_868_test.cpp similarity index 53% rename from algorithm/array/leetcode_868_test.hpp rename to algorithm/array/leetcode_868_test.cpp index f1c25b4d..9b67a3e7 100644 --- a/algorithm/array/leetcode_868_test.hpp +++ b/algorithm/array/leetcode_868_test.cpp @@ -1,45 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_868_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_868_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_868_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_868_TEST_HPP #include -#include -#include -#include +#include "leetcode_868.cpp" namespace leetcode_868 { -using std::vector; -struct leetcode_868 { - static int32_t binaryGap(int32_t N); -}; TEST_CASE("test case 1 {test_868}", "{test_868}") { + Solution solution; static constexpr const auto input{22}; static constexpr const auto result{2}; - CHECK(result == leetcode_868::binaryGap(input)); + CHECK(result == solution.binaryGap(input)); } + TEST_CASE("test case 2 {test_868}", "{test_868}") { + Solution solution; static constexpr const auto input{5}; static constexpr const auto result{2}; - CHECK(result == leetcode_868::binaryGap(input)); + CHECK(result == solution.binaryGap(input)); } + TEST_CASE("test case 3 {test_868}", "{test_868}") { + Solution solution; static constexpr const auto input{6}; static constexpr const auto result{1}; - CHECK(result == leetcode_868::binaryGap(input)); + CHECK(result == solution.binaryGap(input)); } + TEST_CASE("test case 4 {test_868}", "{test_868}") { + Solution solution; static constexpr const auto input{8}; static constexpr const auto result{0}; - CHECK(result == leetcode_868::binaryGap(input)); + CHECK(result == solution.binaryGap(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_868_TEST_HPP + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_868_TEST_HPP diff --git a/algorithm/array/leetcode_88.cpp b/algorithm/array/leetcode_88.cpp index 8513f089..9a75f1ef 100644 --- a/algorithm/array/leetcode_88.cpp +++ b/algorithm/array/leetcode_88.cpp @@ -1,26 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_88_test.hpp" +#include namespace leetcode_88 { -void leetcode_88::merge(vector &nums1, int32_t m, const vector &nums2, int32_t n) { - for (int32_t begin_x{m - 1}, begin_y{n - 1}, count{m + n - 1}; count >= 0; count--) { - if (begin_x < 0) { - // repeat with meaning - nums1[count] = nums2[begin_y]; - begin_y--; - } else if (begin_y < 0 || nums1[begin_x] > nums2[begin_y]) { - nums1[count] = nums1[begin_x]; - begin_x--; - } else { - nums1[count] = nums2[begin_y]; - begin_y--; +using std::vector; +#endif + +class Solution { +public: + void merge(vector &nums1, int32_t m, const vector &nums2, int32_t n) { + for (int32_t begin_x{m - 1}, begin_y{n - 1}, count{m + n - 1}; count >= 0; count--) { + if (begin_x < 0) { + // repeat with meaning + nums1[count] = nums2[begin_y]; + begin_y--; + } else if (begin_y < 0 || nums1[begin_x] > nums2[begin_y]) { + nums1[count] = nums1[begin_x]; + begin_x--; + } else { + nums1[count] = nums2[begin_y]; + begin_y--; + } } } +}; + +#ifdef ALGORITHM_TEST_MACRO } -} +#endif diff --git a/algorithm/array/leetcode_88_test.hpp b/algorithm/array/leetcode_88_test.cpp similarity index 67% rename from algorithm/array/leetcode_88_test.hpp rename to algorithm/array/leetcode_88_test.cpp index b4ee1d78..aebfdfd3 100644 --- a/algorithm/array/leetcode_88_test.hpp +++ b/algorithm/array/leetcode_88_test.cpp @@ -1,32 +1,22 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag 双指针 //@Plan 数据结构入门 Day2 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_88_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_88_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_88_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_88_TEST_HPP #include -#include -#include #include +#include "leetcode_88.cpp" namespace leetcode_88 { -using std::vector; - -struct leetcode_88 { - static void merge(vector &nums1, int32_t m, const vector &nums2, int32_t n); -}; using Catch::Matchers::Equals; TEST_CASE("cases [test_88]", "[test_88]") { + Solution solution; vector vec1{}; vector vec2{}; vector result{}; @@ -51,9 +41,9 @@ TEST_CASE("cases [test_88]", "[test_88]") { vec1 = {1}; result = {1}; } - leetcode_88::merge(vec1, vec1.size() - vec2.size(), vec2, vec2.size()); + solution.merge(vec1, vec1.size() - vec2.size(), vec2, vec2.size()); CHECK_THAT(vec1, Equals(result)); } } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_88_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_88_TEST_HPP diff --git a/algorithm/array/leetcode_896.cpp b/algorithm/array/leetcode_896.cpp index 1f9bf8ee..05c9d4cd 100644 --- a/algorithm/array/leetcode_896.cpp +++ b/algorithm/array/leetcode_896.cpp @@ -1,38 +1,45 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_896_test.hpp" +#include +#include +#include +#include namespace leetcode_896 { +using std::vector; +#endif -bool leetcode_896::isMonotonic(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size == 0 || nums_size == 1) { - return true; - } - static constexpr const auto compare = [](const auto x, const auto y) -> int32_t { - if (x > y) { - return 1; - } else if (x < y) { - return -1; +class Solution { +public: + bool isMonotonic(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size == 0 || nums_size == 1) { + return true; } - return 0; - }; - int counts{0}; - int maxv{std::numeric_limits::min()}, minv{std::numeric_limits::max()}; - for (size_t i{1}; i < nums_size; ++i) { - counts = compare(nums[i], nums[i - 1]); - maxv = std::max(maxv, counts); - minv = std::min(minv, counts); - if (maxv == 1 && minv == -1) { - return false; + static constexpr const auto compare = [](const auto x, const auto y) -> int32_t { + if (x > y) { + return 1; + } else if (x < y) { + return -1; + } + return 0; + }; + int counts{0}; + int maxv{std::numeric_limits::min()}, minv{std::numeric_limits::max()}; + for (size_t i{1}; i < nums_size; ++i) { + counts = compare(nums[i], nums[i - 1]); + maxv = std::max(maxv, counts); + minv = std::min(minv, counts); + if (maxv == 1 && minv == -1) { + return false; + } } + return true; } - return true; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_896_test.hpp b/algorithm/array/leetcode_896_test.cpp similarity index 51% rename from algorithm/array/leetcode_896_test.hpp rename to algorithm/array/leetcode_896_test.cpp index fe06f2fa..f5bb45ce 100644 --- a/algorithm/array/leetcode_896_test.hpp +++ b/algorithm/array/leetcode_896_test.cpp @@ -1,50 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_896_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_896_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_896_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_896_TEST_HPP #include -#include -#include +#include "leetcode_896.cpp" #include namespace leetcode_896 { -using std::vector; - -struct leetcode_896 { - static bool isMonotonic(const vector &nums); -}; - TEST_CASE("test case 1 {test_896}", "{test_896}") { + Solution solution; const vector input{1, 1, 4, 5, 1, 4}; - CHECK_FALSE(leetcode_896::isMonotonic(input)); + CHECK_FALSE(solution.isMonotonic(input)); } TEST_CASE("test case 2 {test_896}", "{test_896}") { + Solution solution; const vector input{1, 9, 1, 9, 8, 1, 0}; - CHECK_FALSE(leetcode_896::isMonotonic(input)); + CHECK_FALSE(solution.isMonotonic(input)); } TEST_CASE("test case 3 {test_896}", "{test_896}") { + Solution solution; const vector input{1, 2, 3, 4, 5, 6}; - CHECK(leetcode_896::isMonotonic(input)); + CHECK(solution.isMonotonic(input)); } TEST_CASE("test case 4 {test_896}", "{test_896}") { + Solution solution; const vector input{1, 1, 2, 3, 4, 5, 5}; - CHECK(leetcode_896::isMonotonic(input)); + CHECK(solution.isMonotonic(input)); } TEST_CASE("test case 5 {test_896}", "{test_896}") { + Solution solution; const vector input{1, 3, 2}; - CHECK_FALSE(leetcode_896::isMonotonic(input)); + CHECK_FALSE(solution.isMonotonic(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_896_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_896_TEST_HPP diff --git a/algorithm/array/leetcode_905.cpp b/algorithm/array/leetcode_905.cpp index e2d5e2fd..cb45bcb2 100644 --- a/algorithm/array/leetcode_905.cpp +++ b/algorithm/array/leetcode_905.cpp @@ -1,19 +1,25 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_905_test.hpp" +#include namespace leetcode_905 { -vector leetcode_905::sortArrayByParity(vector &nums) { - const auto nums_size{nums.size()}; - for (size_t begin{0}, end{nums_size - 1}; begin < end; std::swap(nums[begin], nums[end])) { - for (; ((nums[begin] & 1) == 0) && (begin < end); ++begin) {} - for (; ((nums[end] & 1) == 1) && (begin < end); --end) {} +using std::vector; +#endif + +class Solution { +public: + vector sortArrayByParity(vector &nums) { + const auto nums_size{nums.size()}; + for (size_t begin{0}, end{nums_size - 1}; begin < end; std::swap(nums[begin], nums[end])) { + for (; ((nums[begin] & 1) == 0) && (begin < end); ++begin) {} + for (; ((nums[end] & 1) == 1) && (begin < end); --end) {} + } + return nums; } - return nums; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_905_test.cpp b/algorithm/array/leetcode_905_test.cpp new file mode 100644 index 00000000..1172cae7 --- /dev/null +++ b/algorithm/array/leetcode_905_test.cpp @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 双指针 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_905_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_905_TEST_HPP + +#include +#include "leetcode_905.cpp" +#include + +using Catch::Matchers::Equals; +namespace leetcode_905 { +TEST_CASE("test case 1 {test_905}", "{test_905}") { + Solution solution; + vector input{3, 1, 2, 4}; + const vector result{4, 2, 1, 3}; + CHECK_THAT(result, Equals(solution.sortArrayByParity(input))); +} + +TEST_CASE("test case 2 {test_905}", "{test_905}") { + Solution solution; + vector input{0}; + const vector result{0}; + CHECK_THAT(result, Equals(solution.sortArrayByParity(input))); +} +} + +#endif // ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_905_TEST_HPP diff --git a/algorithm/array/leetcode_905_test.hpp b/algorithm/array/leetcode_905_test.hpp deleted file mode 100644 index fa2bfe63..00000000 --- a/algorithm/array/leetcode_905_test.hpp +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 双指针 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_905_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_905_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_905 { -using std::vector; - -struct leetcode_905 { -private: - static vector sortArrayByParity(vector &nums); - -public: - static vector sortArrayByParity2(const vector &nums) { - vector will_return{nums}; - sortArrayByParity(will_return); - return will_return; - } -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 {test_905}", "{test_905}") { - const vector input{3, 1, 2, 4}; - const vector result{4, 2, 1, 3}; - CHECK_THAT(result, Equals(leetcode_905::sortArrayByParity2(input))); -} - -TEST_CASE("test case 2 {test_905}", "{test_905}") { - const vector input{0}; - const vector result{0}; - CHECK_THAT(result, Equals(leetcode_905::sortArrayByParity2(input))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_905_TEST_HPP diff --git a/algorithm/array/leetcode_908.cpp b/algorithm/array/leetcode_908.cpp index 028fd651..f0521ec4 100644 --- a/algorithm/array/leetcode_908.cpp +++ b/algorithm/array/leetcode_908.cpp @@ -1,21 +1,26 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_908_test.hpp" +#include +#include namespace leetcode_908 { +using std::vector; +#endif -int32_t leetcode_908::smallestRangeI(const vector &nums, int32_t k) { - int min{0x3f3f3f3f}, max{0}; - for (const auto num: nums) { - min = std::min(min, num); - max = std::max(max, num); +class Solution { +public: + int32_t smallestRangeI(const vector &nums, int32_t k) { + int min{0x3f3f3f3f}, max{0}; + for (const auto num: nums) { + min = std::min(min, num); + max = std::max(max, num); + } + return (max - min >= 2 * k ? max - min - 2 * k : 0); } - return (max - min >= 2 * k ? max - min - 2 * k : 0); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_908_test.hpp b/algorithm/array/leetcode_908_test.cpp similarity index 56% rename from algorithm/array/leetcode_908_test.hpp rename to algorithm/array/leetcode_908_test.cpp index 942000ed..c52d5737 100644 --- a/algorithm/array/leetcode_908_test.hpp +++ b/algorithm/array/leetcode_908_test.cpp @@ -1,53 +1,48 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_908_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_908_TEST_HPP + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP #include -#include -#include +#include "leetcode_908.cpp" #include namespace leetcode_908 { -using std::vector; - -struct leetcode_908 { - static int32_t smallestRangeI(const vector &nums, int32_t k); -}; TEST_CASE("test case 1 {test_908}", "{test_908}") { + Solution solution; const vector input{1}; static constexpr const auto k{0}; static constexpr const auto result{0}; - CHECK(result == leetcode_908::smallestRangeI(input, k)); + CHECK(result == solution.smallestRangeI(input, k)); } TEST_CASE("test case 2 {test_908}", "{test_908}") { + Solution solution; const vector input{0, 10}; static constexpr const auto k{2}; static constexpr const auto result{6}; - CHECK(result == leetcode_908::smallestRangeI(input, k)); + CHECK(result == solution.smallestRangeI(input, k)); } TEST_CASE("test case 3 {test_908}", "{test_908}") { + Solution solution; const vector input{1, 3, 6}; static constexpr const auto k{3}; static constexpr const auto result{0}; - CHECK(result == leetcode_908::smallestRangeI(input, k)); + CHECK(result == solution.smallestRangeI(input, k)); } TEST_CASE("test case 4 {test_908}", "{test_908}") { + Solution solution; const vector input{2, 7, 2}; static constexpr const auto k{1}; static constexpr const auto result{3}; - CHECK(result == leetcode_908::smallestRangeI(input, k)); + CHECK(result == solution.smallestRangeI(input, k)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_908_TEST_HPP + +#endif // ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_908_TEST_HPP diff --git a/algorithm/array/leetcode_922.cpp b/algorithm/array/leetcode_922.cpp index 1fec13c9..8be8df37 100644 --- a/algorithm/array/leetcode_922.cpp +++ b/algorithm/array/leetcode_922.cpp @@ -1,27 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_922_test.hpp" +#include +#include +#include namespace leetcode_922 { +using std::vector; +#endif - -vector leetcode_922::sortArrayByParityII(const vector &nums) { - vector will_return{nums}; - const auto nums_size{will_return.size()}; - size_t sing{0}; - int64_t doub{static_cast(nums_size) - 1}; - for (; sing < nums_size && will_return[sing] % 2 == 0; sing += 2) {} - for (; doub > 0 && will_return[doub] % 2 == 1; doub -= 2) {} - while (sing < nums_size && doub > 0) { - std::swap(will_return[sing], will_return[doub]); +class Solution { +public: + vector sortArrayByParityII(vector &nums) { + vector will_return{nums}; + const auto nums_size{will_return.size()}; + size_t sing{0}; + int64_t doub{static_cast(nums_size) - 1}; for (; sing < nums_size && will_return[sing] % 2 == 0; sing += 2) {} for (; doub > 0 && will_return[doub] % 2 == 1; doub -= 2) {} + while (sing < nums_size && doub > 0) { + std::swap(will_return[sing], will_return[doub]); + for (; sing < nums_size && will_return[sing] % 2 == 0; sing += 2) {} + for (; doub > 0 && will_return[doub] % 2 == 1; doub -= 2) {} + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_922_test.cpp b/algorithm/array/leetcode_922_test.cpp new file mode 100644 index 00000000..dd9660b5 --- /dev/null +++ b/algorithm/array/leetcode_922_test.cpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP + +#include +#include "leetcode_922.cpp" +#include + +namespace leetcode_922 { + +void judgement(const vector &nums) { + const auto nums_size{nums.size()}; + CHECK(nums_size % 2 == 0); + for (size_t i{0}; i < nums_size; ++i) { + CHECK(static_cast(nums[i] % 2) == static_cast( i % 2)); + } +} + +TEST_CASE("test case 1 {test_922}", "{test_922}") { + Solution solution; + vector input{4, 2, 5, 7}; + judgement(solution.sortArrayByParityII(input)); +} + +TEST_CASE("test case 2 {test_922}", "{test_922}") { + Solution solution; + vector input{1, 1, 4, 5, 4, 4}; + judgement(solution.sortArrayByParityII(input)); +} + +TEST_CASE("test case 3 {test_922}", "{test_922}") { + Solution solution; + vector input{1, 9, 2, 9, 8, 1, 0, 0}; + judgement(solution.sortArrayByParityII(input)); +} + +TEST_CASE("test case 4 {test_922}", "{test_922}") { + Solution solution; + vector input{8, 5, 2, 7}; + judgement(solution.sortArrayByParityII(input)); +} +} +#endif // ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_922_TEST_HPP diff --git a/algorithm/array/leetcode_922_test.hpp b/algorithm/array/leetcode_922_test.hpp deleted file mode 100644 index 9e286e84..00000000 --- a/algorithm/array/leetcode_922_test.hpp +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_922_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_922_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_922 { -using std::vector; - -struct leetcode_922 { - static vector sortArrayByParityII(const vector &nums); -}; - - -void judgement(const vector &nums) { - const auto nums_size{nums.size()}; - CHECK(nums_size % 2 == 0); - for (size_t i{0}; i < nums_size; ++i) { - CHECK(static_cast(nums[i] % 2) == static_cast( i % 2)); - } -} - -TEST_CASE("test case 1 {test_922}", "{test_922}") { - const vector input{4, 2, 5, 7}; - judgement(leetcode_922::sortArrayByParityII(input)); -} - -TEST_CASE("test case 2 {test_922}", "{test_922}") { - const vector input{1, 1, 4, 5, 4, 4}; - judgement(leetcode_922::sortArrayByParityII(input)); -} - -TEST_CASE("test case 3 {test_922}", "{test_922}") { - const vector input{1, 9, 2, 9, 8, 1, 0, 0}; - judgement(leetcode_922::sortArrayByParityII(input)); -} - -TEST_CASE("test case 4 {test_922}", "{test_922}") { - const vector input{8, 5, 2, 7}; - judgement(leetcode_922::sortArrayByParityII(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_922_TEST_HPP diff --git a/algorithm/array/leetcode_941.cpp b/algorithm/array/leetcode_941.cpp index a0055bc1..e8e87acb 100644 --- a/algorithm/array/leetcode_941.cpp +++ b/algorithm/array/leetcode_941.cpp @@ -1,31 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_941_test.hpp" +#include +#include namespace leetcode_941 { +using std::vector; +#endif -bool leetcode_941::validMountainArray(const vector &arr) { - const auto arr_size{arr.size()}; - if (arr_size < 3) { - return false; - } else if (arr_size == 3) { - return arr[0] < arr[1] && arr[1] > arr[2]; - } - size_t count{0}; - for (size_t i{1}; i + 1 < arr_size; ++i) { - if (arr[i - 1] == arr[i] || arr[i] == arr[i + 1]) { +class Solution { +public: + bool validMountainArray(const vector &arr) { + const auto arr_size{arr.size()}; + if (arr_size < 3) { return false; + } else if (arr_size == 3) { + return arr[0] < arr[1] && arr[1] > arr[2]; } - count += (arr[i - 1] < arr[i]) == (arr[i] < arr[i + 1]); - } - if (count + 3 == arr_size) { - return true; + size_t count{0}; + for (size_t i{1}; i + 1 < arr_size; ++i) { + if (arr[i - 1] == arr[i] || arr[i] == arr[i + 1]) { + return false; + } + count += (arr[i - 1] < arr[i]) == (arr[i] < arr[i + 1]); + } + if (count + 3 == arr_size) { + return true; + } + return false; } - return false; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_941_test.cpp b/algorithm/array/leetcode_941_test.cpp new file mode 100644 index 00000000..dc37d157 --- /dev/null +++ b/algorithm/array/leetcode_941_test.cpp @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP + +#include +#include "leetcode_941.cpp" +#include + +namespace leetcode_941 { +TEST_CASE("test case 1 {test_941}", "{test_941}") { + Solution solution; + const vector input{4, 5, 10, 7}; + CHECK(solution.validMountainArray(input)); +} + +TEST_CASE("test case 2 {test_941}", "{test_941}") { + Solution solution; + const vector input{0, 3, 2, 1}; + CHECK(solution.validMountainArray(input)); +} + +TEST_CASE("test case 3 {test_941}", "{test_941}") { + Solution solution; + const vector input{114, 514, 191}; + CHECK(solution.validMountainArray(input)); +} + +TEST_CASE("test case 4 {test_941}", "{test_941}") { + Solution solution; + const vector input{1, 8, 0}; + CHECK(solution.validMountainArray(input)); +} + +TEST_CASE("test case 5 {test_941}", "{test_941}") { + Solution solution; + const vector input{9, 1, 9}; + CHECK_FALSE(solution.validMountainArray(input)); +} +} + +#endif // ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_941_TEST_HPP diff --git a/algorithm/array/leetcode_941_test.hpp b/algorithm/array/leetcode_941_test.hpp deleted file mode 100644 index d1a2601e..00000000 --- a/algorithm/array/leetcode_941_test.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_941_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_941_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_941 { -using std::vector; - -struct leetcode_941 { - static bool validMountainArray(const vector &arr); -}; - - -TEST_CASE("test case 1 {test_941}", "{test_941}") { - const vector input{4, 5, 10, 7}; - CHECK(leetcode_941::validMountainArray(input)); -} - -TEST_CASE("test case 2 {test_941}", "{test_941}") { - const vector input{0, 3, 2, 1}; - CHECK(leetcode_941::validMountainArray(input)); -} - -TEST_CASE("test case 3 {test_941}", "{test_941}") { - const vector input{114, 514, 191}; - CHECK(leetcode_941::validMountainArray(input)); -} - -TEST_CASE("test case 4 {test_941}", "{test_941}") { - const vector input{1, 8, 0}; - CHECK(leetcode_941::validMountainArray(input)); -} - -TEST_CASE("test case 5 {test_941}", "{test_941}") { - const vector input{9, 1, 9}; - CHECK_FALSE(leetcode_941::validMountainArray(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_941_TEST_HPP diff --git a/algorithm/array/leetcode_942.cpp b/algorithm/array/leetcode_942.cpp index 104b8d83..21378339 100644 --- a/algorithm/array/leetcode_942.cpp +++ b/algorithm/array/leetcode_942.cpp @@ -1,29 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_942_test.hpp" +#include +#include namespace leetcode_942 { +using std::vector; +using std::string; +#endif -vector leetcode_942::diStringMatch(const string &str) { - const auto str_size{str.size()}; - int32_t min{0}, max{static_cast(str_size)}; - vector willreturn(max + 1); - for (size_t i{0}; i < str_size; i++) { - if (str[i] == 'I') { - willreturn[i] = min; - min++; - } else { - willreturn[i] = max; - max--; +class Solution { +public: + vector diStringMatch(const string &str) { + const auto str_size{str.size()}; + int32_t min{0}, max{static_cast(str_size)}; + vector willreturn(max + 1); + for (size_t i{0}; i < str_size; i++) { + if (str[i] == 'I') { + willreturn[i] = min; + min++; + } else { + willreturn[i] = max; + max--; + } } + willreturn.back() = min; + return willreturn; } - willreturn.back() = min; - return willreturn; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_942_test.hpp b/algorithm/array/leetcode_942_test.cpp similarity index 60% rename from algorithm/array/leetcode_942_test.hpp rename to algorithm/array/leetcode_942_test.cpp index e12bc85e..6c62aef9 100644 --- a/algorithm/array/leetcode_942_test.hpp +++ b/algorithm/array/leetcode_942_test.cpp @@ -1,29 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_942_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_942_TEST_HPP + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_867_TEST_HPP #include -#include -#include +#include "leetcode_942.cpp" #include #include namespace leetcode_942 { -using std::vector; -using std::string; - -struct leetcode_942 { - static vector diStringMatch(const string &str); -}; - static void check(const string &str, const vector &vec) { const auto str_size{str.size()}, vec_size{vec.size()}; CHECK(str_size + 1 == vec_size); @@ -38,18 +26,21 @@ static void check(const string &str, const vector &vec) { } TEST_CASE("test case 1 {test_942}", "{test_942}") { + Solution solution; static constexpr const char *const str{"IDID"}; - check(str, leetcode_942::diStringMatch(str)); + check(str, solution.diStringMatch(str)); } TEST_CASE("test case 2 {test_942}", "{test_942}") { + Solution solution; static constexpr const char *const str{"III"}; - check(str, leetcode_942::diStringMatch(str)); + check(str, solution.diStringMatch(str)); } TEST_CASE("test case 3 {test_942}", "{test_942}") { + Solution solution; static constexpr const char *const str{"DDI"}; - check(str, leetcode_942::diStringMatch(str)); + check(str, solution.diStringMatch(str)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_942_TEST_HPP +#endif // ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_942_TEST_HPP diff --git a/algorithm/array/leetcode_944.cpp b/algorithm/array/leetcode_944.cpp index 2fc2bb12..a904866e 100644 --- a/algorithm/array/leetcode_944.cpp +++ b/algorithm/array/leetcode_944.cpp @@ -1,25 +1,31 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_944_test.hpp" +#include +#include namespace leetcode_944 { +using std::vector; +using std::string; +#endif -int leetcode_944::minDeletionSize(const vector &strs) { - int count{0}; - const auto lines{strs.size()}; - const auto str_size{strs[0].size()}; - for (size_t i{0},notdeletex{true}; i < str_size; ++i,notdeletex = true) { - for (size_t j{1}; j < lines; ++j) { - notdeletex = notdeletex & (strs[j][i] >= strs[j - 1][i]); +class Solution { +public: + int32_t minDeletionSize(const vector &strs) { + int count{0}; + const auto lines{strs.size()}; + const auto str_size{strs[0].size()}; + for (size_t i{0}, notdeletex{true}; i < str_size; ++i, notdeletex = true) { + for (size_t j{1}; j < lines; ++j) { + notdeletex = notdeletex & (strs[j][i] >= strs[j - 1][i]); + } + count += !notdeletex; } - count += !notdeletex; + return count; } - return count; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_944_test.hpp b/algorithm/array/leetcode_944_test.cpp similarity index 53% rename from algorithm/array/leetcode_944_test.hpp rename to algorithm/array/leetcode_944_test.cpp index eab98208..034a8978 100644 --- a/algorithm/array/leetcode_944_test.hpp +++ b/algorithm/array/leetcode_944_test.cpp @@ -1,50 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_944_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_944_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_944_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_944_TEST_HPP #include -#include -#include #include #include +#include +#include "leetcode_944.cpp" namespace leetcode_944 { -using std::vector; -using std::string; - -struct leetcode_944 { - static int minDeletionSize(const vector &A); -}; - TEST_CASE("test case 1 {test_944}", "{test_944}") { + Solution solution; static constexpr const std::array input{ "abc", "bce", "cae" }; static constexpr const auto result{1}; - CHECK(result == leetcode_944::minDeletionSize({input.begin(), input.end()})); + CHECK(result == solution.minDeletionSize({input.begin(), input.end()})); } TEST_CASE("test case 2 {test_944}", "{test_944}") { + Solution solution; static constexpr const std::array input{ "a", "b" }; static constexpr const auto result{0}; - CHECK(result == leetcode_944::minDeletionSize({input.begin(), input.end()})); + CHECK(result == solution.minDeletionSize({input.begin(), input.end()})); } + TEST_CASE("test case 3 {test_944}", "{test_944}") { + Solution solution; static constexpr const std::array input{ "zyx", "wvu", "tsr" }; static constexpr const auto result{3}; - CHECK(result == leetcode_944::minDeletionSize({input.begin(), input.end()})); + CHECK(result == solution.minDeletionSize({input.begin(), input.end()})); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_944_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_944_TEST_HPP diff --git a/algorithm/array/leetcode_977.cpp b/algorithm/array/leetcode_977.cpp index 705d89e5..80d3d819 100644 --- a/algorithm/array/leetcode_977.cpp +++ b/algorithm/array/leetcode_977.cpp @@ -1,36 +1,40 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_977_test.hpp" +#include +#include namespace leetcode_977 { +using std::vector; +#endif -// best O(n) -vector leetcode_977::sortedSquares(const vector &nums) { - const auto nums_size{nums.size()}; - static constexpr const auto cmp = [](int32_t x, int32_t y) { - return x * x <= y * y; - }; - vector will_return{}; - const size_t posi = std::min_element(nums.cbegin(), nums.cend(), cmp) - nums.cbegin(); - size_t left{posi + 1}, right{posi + 1}; - while (0 < left && right < nums_size) { - const auto cmpValue = cmp(nums[left - 1], nums[right]); - if (cmpValue) { - will_return.push_back(nums[left - 1] * nums[left - 1]); - --left; - } else { - will_return.push_back(nums[right] * nums[right]); - ++right; +class Solution { +public: + vector sortedSquares(const vector &nums) { + const auto nums_size{nums.size()}; + static constexpr const auto cmp = [](int32_t x, int32_t y) { + return x * x <= y * y; + }; + vector will_return{}; + const size_t posi = std::min_element(nums.cbegin(), nums.cend(), cmp) - nums.cbegin(); + size_t left{posi + 1}, right{posi + 1}; + while (0 < left && right < nums_size) { + const auto cmpValue = cmp(nums[left - 1], nums[right]); + if (cmpValue) { + will_return.push_back(nums[left - 1] * nums[left - 1]); + --left; + } else { + will_return.push_back(nums[right] * nums[right]); + ++right; + } } + for (; 0 < left; --left) { will_return.push_back(nums[left - 1] * nums[left - 1]); } + for (; right < nums_size; ++right) { will_return.push_back(nums[right] * nums[right]); } + return will_return; } - for (; 0 < left; --left) { will_return.push_back(nums[left - 1] * nums[left - 1]); } - for (; right < nums_size; ++right) { will_return.push_back(nums[right] * nums[right]); } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_977_test.cpp b/algorithm/array/leetcode_977_test.cpp new file mode 100644 index 00000000..b38cbfd1 --- /dev/null +++ b/algorithm/array/leetcode_977_test.cpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_977_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_977_TEST_HPP + +#include +#include "leetcode_977.cpp" +#include + +namespace leetcode_977 { +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 {test_977}", "{test_977}") { + Solution solution; + const vector input{-4, -1, 0, 3, 10}; + const vector result{0, 1, 9, 16, 100}; + CHECK_THAT(result, Equals(solution.sortedSquares(input))); +} + +TEST_CASE("test case 2 {test_977}", "{test_977}") { + Solution solution; + const vector input{-7, -3, 2, 3, 11}; + const vector result{4, 9, 9, 49, 121}; + CHECK_THAT(result, Equals(solution.sortedSquares(input))); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_977_TEST_HPP diff --git a/algorithm/array/leetcode_977_test.hpp b/algorithm/array/leetcode_977_test.hpp deleted file mode 100644 index 36790310..00000000 --- a/algorithm/array/leetcode_977_test.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_977_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_977_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_977 { -using std::vector; - -struct leetcode_977 { - static vector sortedSquares(const vector &nums); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 {test_977}", "{test_977}") { - const vector input{-4, -1, 0, 3, 10}; - const vector result{0, 1, 9, 16, 100}; - CHECK_THAT(result, Equals(leetcode_977::sortedSquares(input))); -} - -TEST_CASE("test case 2 {test_977}", "{test_977}") { - const vector input{-7, -3, 2, 3, 11}; - const vector result{4, 9,9, 49, 121}; - CHECK_THAT(result, Equals(leetcode_977::sortedSquares(input))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_977_TEST_HPP diff --git a/algorithm/array/leetcode_985.cpp b/algorithm/array/leetcode_985.cpp index 23c8481e..039d5a08 100644 --- a/algorithm/array/leetcode_985.cpp +++ b/algorithm/array/leetcode_985.cpp @@ -1,40 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_985_test.hpp" +#include +#include +#include namespace leetcode_985 { +using std::vector; +#endif -vector leetcode_985::sumEvenAfterQueries(const vector &nums, const vector> &queries) { - vector willreturn; - vector mut_nums{nums}; - willreturn.reserve(queries.size()); - int32_t sums{0}; - for (const auto num: mut_nums) { - sums += ((num % 2 == 0) ? num : 0); - } - for (const auto &query: queries) { - //for (int32_t i{0}; i < queries.size(); i++) { - const auto val{query[0]}; - const auto index{query[1]}; - const auto lastIdx{mut_nums[index]}; - if (lastIdx % 2 == 0) { - if (val % 2 == 0) { - sums += val; - } else { - sums -= lastIdx; +class Solution { +public: + vector sumEvenAfterQueries(vector &nums, const vector> &queries) { + vector willreturn; + vector mut_nums{nums}; + willreturn.reserve(queries.size()); + int32_t sums{0}; + for (const auto num: mut_nums) { + sums += ((num % 2 == 0) ? num : 0); + } + for (const auto &query: queries) { + //for (int32_t i{0}; i < queries.size(); i++) { + const auto val{query[0]}; + const auto index{query[1]}; + const auto lastIdx{mut_nums[index]}; + if (lastIdx % 2 == 0) { + if (val % 2 == 0) { + sums += val; + } else { + sums -= lastIdx; + } + } else if (val % 2 != 0) { + sums += (lastIdx + val); } - } else if (val % 2 != 0) { - sums += (lastIdx + val); + mut_nums[index] += val; + willreturn.push_back(sums); } - mut_nums[index] += val; - willreturn.push_back(sums); + return willreturn; } - return willreturn; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_985_test.cpp b/algorithm/array/leetcode_985_test.cpp new file mode 100644 index 00000000..4f3e1df3 --- /dev/null +++ b/algorithm/array/leetcode_985_test.cpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_985_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_985_TEST_HPP + +#include +#include +#include "leetcode_985.cpp" + +namespace leetcode_985 { +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 {test_985}", "{test_985}") { + Solution solution; + vector input{1, 2, 3, 4}; + const vector> queries{ + {1, 0}, + {-3, 1}, + {-4, 0}, + {2, 3}, + }; + const vector result{8, 6, 2, 4}; + CHECK_THAT(result, Equals(solution.sumEvenAfterQueries(input, queries))); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_985_TEST_HPP diff --git a/algorithm/array/leetcode_985_test.hpp b/algorithm/array/leetcode_985_test.hpp deleted file mode 100644 index 1a68aa2e..00000000 --- a/algorithm/array/leetcode_985_test.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_985_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_985_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_985 { -using std::vector; - -struct leetcode_985 { - static vector sumEvenAfterQueries(const vector &nums, const vector> &queries); -}; - - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 {test_985}", "{test_985}") { - const vector input{1, 2, 3, 4}; - const vector> queries{ - {1, 0}, - {-3, 1}, - {-4, 0}, - {2, 3}, - }; - const vector result{8, 6, 2, 4}; - CHECK_THAT(result, Equals(leetcode_985::sumEvenAfterQueries(input, queries))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_985_TEST_HPP diff --git a/algorithm/array/leetcode_986.cpp b/algorithm/array/leetcode_986.cpp index 114d2e7e..0092c8b7 100644 --- a/algorithm/array/leetcode_986.cpp +++ b/algorithm/array/leetcode_986.cpp @@ -1,35 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_986_test.hpp" +#include +#include namespace leetcode_986 { +using std::vector; +#endif -vector> leetcode_986::intervalIntersection(const vector> &fst, const vector> &snd) { - vector> will_return; - const auto fst_size{fst.size()}, snd_size{snd.size()}; - const auto judgement = [&fst, &snd](size_t pre, size_t post) -> vector { - const auto &fst_element{fst[pre]}, &snd_element{snd[post]}; - return {std::max(fst_element[0], snd_element[0]), - std::min(fst_element[1], snd_element[1])}; - }; - for (size_t x{0}, y{0}, judge{0}; x < fst_size && y < snd_size;) { - if (fst[x][1] < snd[y][0]) { - ++x; - } else if (fst[x][0] > snd[y][1]) { - ++y; - } else { - const vector temp = judgement(x, y); - will_return.emplace_back(temp); - judge = ((temp[1] >= fst[x][1]) == 1 ? 1 : 0); - x += judge; - y += (1 - judge); +class Solution { +public: + vector> + intervalIntersection(const vector> &fst, const vector> &snd) { + vector> will_return; + const auto fst_size{fst.size()}, snd_size{snd.size()}; + const auto judgement = [&fst, &snd](size_t pre, size_t post) -> vector { + const auto &fst_element{fst[pre]}, &snd_element{snd[post]}; + return {std::max(fst_element[0], snd_element[0]), + std::min(fst_element[1], snd_element[1])}; + }; + for (size_t x{0}, y{0}, judge{0}; x < fst_size && y < snd_size;) { + if (fst[x][1] < snd[y][0]) { + ++x; + } else if (fst[x][0] > snd[y][1]) { + ++y; + } else { + const vector temp = judgement(x, y); + will_return.emplace_back(temp); + judge = ((temp[1] >= fst[x][1]) == 1 ? 1 : 0); + x += judge; + y += (1 - judge); + } } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_986_test.hpp b/algorithm/array/leetcode_986_test.cpp similarity index 67% rename from algorithm/array/leetcode_986_test.hpp rename to algorithm/array/leetcode_986_test.cpp index fb5334c5..35e1509a 100644 --- a/algorithm/array/leetcode_986_test.hpp +++ b/algorithm/array/leetcode_986_test.cpp @@ -1,31 +1,19 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 双指针 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_986_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_986_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_986_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_986_TEST_HPP #include -#include -#include +#include "leetcode_986.cpp" #include namespace leetcode_986 { -using std::vector; - -struct leetcode_986 { - static vector> intervalIntersection(const vector> &fst, const vector> &snd); -}; - - using Catch::Matchers::Equals; TEST_CASE("test case 1 {test_986}", "{test_986}") { + Solution solution; const vector> fst{{0, 2}, {5, 10}, {13, 23}, @@ -40,18 +28,19 @@ TEST_CASE("test case 1 {test_986}", "{test_986}") { {15, 23}, {24, 24}, {25, 25}}; - CHECK_THAT(result, Equals(leetcode_986::intervalIntersection(fst, snd))); + CHECK_THAT(result, Equals(solution.intervalIntersection(fst, snd))); } TEST_CASE("test case 3 {test_986}", "{test_986}") { + Solution solution; const vector> fst{{17, 20}}; const vector> snd{{2, 3}, {6, 8}, {12, 14}, {19, 20}}; const vector> result{{19, 20}}; - CHECK_THAT(result, Equals(leetcode_986::intervalIntersection(fst, snd))); + CHECK_THAT(result, Equals(solution.intervalIntersection(fst, snd))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_986_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_986_TEST_HPP diff --git a/algorithm/array/leetcode_989.cpp b/algorithm/array/leetcode_989.cpp index d657ce01..933ced16 100644 --- a/algorithm/array/leetcode_989.cpp +++ b/algorithm/array/leetcode_989.cpp @@ -1,31 +1,38 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_989_test.hpp" +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_989 { +using std::vector; +#endif -vector leetcode_989::addToArrayForm(const vector &num, int32_t k) { - vector will_return{num}; - const auto num_size{num.size()}; - int32_t last{0}; - for (size_t i{will_return.size()}; i >= 1; --i) { - last += k % 10; - k = k / 10; - will_return[i-1] += last; - last = (will_return[i - 1] >= 10); - will_return[i-1] = will_return[i-1] % 10; - } - while (k > 0 || last > 0) { - last += k % 10; - k /= 10; - will_return.emplace(will_return.begin(), last % 10); - last = last / 10; +class Solution { +public: + std::vector addToArrayForm(std::vector &num, int32_t k) { + vector will_return{num}; + const auto num_size{num.size()}; + int32_t last{0}; + for (size_t i{will_return.size()}; i >= 1; --i) { + last += k % 10; + k = k / 10; + will_return[i - 1] += last; + last = (will_return[i - 1] >= 10); + will_return[i - 1] = will_return[i - 1] % 10; + } + while (k > 0 || last > 0) { + last += k % 10; + k /= 10; + will_return.emplace(will_return.begin(), last % 10); + last = last / 10; + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_989_test.cpp b/algorithm/array/leetcode_989_test.cpp new file mode 100644 index 00000000..1c3116ef --- /dev/null +++ b/algorithm/array/leetcode_989_test.cpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 双指针 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_989_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_989_TEST_HPP + +#include "leetcode_989.cpp" +#include + +namespace leetcode_989 { +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 {test_989}", "{test_989}") { + auto sol = Solution(); + std::vector fst{1, 3, 2, 1}; + static constexpr const auto k{34}; + std::vector result{1, 3, 5, 5}; + CHECK_THAT(result, Equals(sol.addToArrayForm(fst, k))); +} + +TEST_CASE("test case 2 {test_989}", "{test_989}") { + auto sol = Solution(); + std::vector fst{2, 7, 4}; + static constexpr const auto k{181}; + std::vector result{4, 5, 5}; + CHECK_THAT(result, Equals(sol.addToArrayForm(fst, k))); +} + +TEST_CASE("test case 3 {test_989}", "{test_989}") { + auto sol = Solution(); + std::vector fst{2, 1, 5}; + static constexpr const auto k{806}; + std::vector result{1, 0, 2, 1}; + CHECK_THAT(result, Equals(sol.addToArrayForm(fst, k))); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_989_TEST_HPP diff --git a/algorithm/array/leetcode_989_test.hpp b/algorithm/array/leetcode_989_test.hpp deleted file mode 100644 index 73a798e0..00000000 --- a/algorithm/array/leetcode_989_test.hpp +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 双指针 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_989_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_989_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_989 { -using std::vector; - -struct leetcode_989 { - static vector addToArrayForm(const vector &num, int32_t k); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 {test_989}", "{test_989}") { - const vector fst{1, 3, 2, 1}; - static constexpr const auto k{34}; - const vector result{1, 3, 5, 5}; - CHECK_THAT(result, Equals(leetcode_989::addToArrayForm(fst, k))); -} - -TEST_CASE("test case 2 {test_989}", "{test_989}") { - const vector fst{2, 7, 4}; - static constexpr const auto k{181}; - const vector result{4, 5, 5}; - CHECK_THAT(result, Equals(leetcode_989::addToArrayForm(fst, k))); -} - -TEST_CASE("test case 3 {test_989}", "{test_989}") { - const vector fst{2, 1, 5}; - static constexpr const auto k{806}; - const vector result{1, 0, 2, 1}; - CHECK_THAT(result, Equals(leetcode_989::addToArrayForm(fst, k))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_989_TEST_HPP diff --git a/algorithm/array/leetcode_999.cpp b/algorithm/array/leetcode_999.cpp index 32f0ba9b..0c07bcee 100644 --- a/algorithm/array/leetcode_999.cpp +++ b/algorithm/array/leetcode_999.cpp @@ -1,99 +1,107 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ +#include #include -#include "leetcode_999_test.hpp" +#include +#include +#include namespace leetcode_999 { +using std::array; +using std::vector; + +#endif static constexpr const size_t board_size{8}; -int32_t leetcode_999::numRookCaptures(const vector> &board) { - size_t x{0}, y{0}; - for (size_t i{0}; i < board_size; ++i) { - for (size_t j{0}; j < board_size; ++j) { - if (board[i][j] == 'R') { - x = i; - y = j; +class Solution { +public: + int32_t numRookCaptures(vector> &board) { + size_t x{0}, y{0}; + for (size_t i{0}; i < board_size; ++i) { + for (size_t j{0}; j < board_size; ++j) { + if (board[i][j] == 'R') { + x = i; + y = j; + } } } - } - std::array judge{false, false, false, false}; - for (size_t i{x + 1}; i < board_size; ++i) { - //cout << board[i][y] << endl; - switch (board[i][y]) { - case 'B': { - i = board_size; - break; - } - case '.': { - break; - } - case 'p': { - i = board_size; - judge[0] = true; - break; + std::array judge{false, false, false, false}; + for (size_t i{x + 1}; i < board_size; ++i) { + // cout << board[i][y] << endl; + switch (board[i][y]) { + case 'B': { + i = board_size; + break; + } + case '.': { + break; + } + case 'p': { + i = board_size; + judge[0] = true; + break; + } } - } - } - for (size_t i{x}; i >= 1; --i) { - //cout << board[i][y] << endl; - switch (board[i - 1][y]) { - case 'B': { - i = 1; - break; - } + for (size_t i{x}; i >= 1; --i) { + // cout << board[i][y] << endl; + switch (board[i - 1][y]) { + case 'B': { + i = 1; + break; + } - case '.': { - break; - } + case '.': { + break; + } - case 'p': { - judge[1] = true; - i = 1; - break; + case 'p': { + judge[1] = true; + i = 1; + break; + } } } - } - for (size_t i{y}; i >= 1; --i) { - switch (board[x][i - 1]) { - case 'B': { - i = 1; - break; - } - case '.': { - break; - } - case 'p': { - judge[2] = true; - i = 1; - break; + for (size_t i{y}; i >= 1; --i) { + switch (board[x][i - 1]) { + case 'B': { + i = 1; + break; + } + case '.': { + break; + } + case 'p': { + judge[2] = true; + i = 1; + break; + } } } - } - for (size_t i{y + 1}; i < board_size; i++) { - switch (board[x][i]) { - case 'B': { - i = board_size; - break; + for (size_t i{y + 1}; i < board_size; i++) { + switch (board[x][i]) { + case 'B': { + i = board_size; + break; + } + case '.': { + break; + } + case 'p': { + judge[3] = true; + i = board_size; + break; + } } - case '.': { - break; - } - case 'p': { - judge[3] = true; - i = board_size; - break; - } - } + return std::accumulate(judge.cbegin(), judge.cend(), 0); } - return std::accumulate(judge.cbegin(), judge.cend(), 0); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_999_test.cpp b/algorithm/array/leetcode_999_test.cpp new file mode 100644 index 00000000..3bf210a4 --- /dev/null +++ b/algorithm/array/leetcode_999_test.cpp @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 双指针 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_999_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_999_TEST_HPP + +#include +#include "leetcode_999.cpp" + +namespace leetcode_999 { + +TEST_CASE("test case 1 {test_999}", "{test_999}") { + auto sol = Solution(); + std::vector> board{{'.', '.', '.', '.', '.', '.', '.', '.'}, + {'.', '.', '.', 'p', '.', '.', '.', '.'}, + {'.', '.', '.', 'R', '.', '.', '.', 'p'}, + {'.', '.', '.', '.', '.', '.', '.', '.'}, + {'.', '.', '.', '.', '.', '.', '.', '.'}, + {'.', '.', '.', 'p', '.', '.', '.', '.'}, + {'.', '.', '.', '.', '.', '.', '.', '.'}, + {'.', '.', '.', '.', '.', '.', '.', '.'}}; + static constexpr const auto result{3}; + CHECK(result == sol.numRookCaptures(board)); +} + +TEST_CASE("test case 2 {test_999}", "{test_999}") { + auto sol = Solution(); + std::vector> board{{'.', '.', '.', '.', '.', '.', '.', '.'}, + {'.', 'p', 'p', 'p', 'p', 'p', '.', '.'}, + {'.', 'p', 'p', 'B', 'p', 'p', '.', '.'}, + {'.', 'p', 'B', 'R', 'B', 'p', '.', '.'}, + {'.', 'p', 'p', 'B', 'p', 'p', '.', '.'}, + {'.', 'p', 'p', 'p', 'p', 'p', '.', '.'}, + {'.', '.', '.', '.', '.', '.', '.', '.'}, + {'.', '.', '.', '.', '.', '.', '.', '.'}}; + static constexpr const auto result{0}; + CHECK(result == sol.numRookCaptures(board)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_999_TEST_HPP diff --git a/algorithm/array/leetcode_999_test.hpp b/algorithm/array/leetcode_999_test.hpp deleted file mode 100644 index 9a07f63d..00000000 --- a/algorithm/array/leetcode_999_test.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 双指针 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_999_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_999_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_999 { -using std::vector; - -struct leetcode_999 { - static int32_t numRookCaptures(const vector> &board); -}; - - -TEST_CASE("test case 1 {test_999}", "{test_999}") { - const vector> board{{'.', '.', '.', '.', '.', '.', '.', '.'}, - {'.', '.', '.', 'p', '.', '.', '.', '.'}, - {'.', '.', '.', 'R', '.', '.', '.', 'p'}, - {'.', '.', '.', '.', '.', '.', '.', '.'}, - {'.', '.', '.', '.', '.', '.', '.', '.'}, - {'.', '.', '.', 'p', '.', '.', '.', '.'}, - {'.', '.', '.', '.', '.', '.', '.', '.'}, - {'.', '.', '.', '.', '.', '.', '.', '.'}}; - static constexpr const auto result{3}; - CHECK(result == leetcode_999::numRookCaptures(board)); -} - -TEST_CASE("test case 2 {test_999}", "{test_999}") { - const vector> board{{'.', '.', '.', '.', '.', '.', '.', '.'}, - {'.', 'p', 'p', 'p', 'p', 'p', '.', '.'}, - {'.', 'p', 'p', 'B', 'p', 'p', '.', '.'}, - {'.', 'p', 'B', 'R', 'B', 'p', '.', '.'}, - {'.', 'p', 'p', 'B', 'p', 'p', '.', '.'}, - {'.', 'p', 'p', 'p', 'p', 'p', '.', '.'}, - {'.', '.', '.', '.', '.', '.', '.', '.'}, - {'.', '.', '.', '.', '.', '.', '.', '.'}}; - static constexpr const auto result{0}; - CHECK(result == leetcode_999::numRookCaptures(board)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_999_TEST_HPP diff --git a/algorithm/array/leetcode_golden_0812.cpp b/algorithm/array/leetcode_golden_0812.cpp new file mode 100644 index 00000000..924bd1af --- /dev/null +++ b/algorithm/array/leetcode_golden_0812.cpp @@ -0,0 +1,134 @@ + +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO + +#include +#include +#include +#include +#include +#include +#include + +using std::vector; +using std::string; +using std::unordered_map; + +namespace leetcode_golden_0812 { +#endif + +class Solution { +private: + bool check(const vector> &nums, int32_t i, int32_t j) { + const auto length = static_cast(nums.size()); + for (int32_t x{0}; x < length; x++) { + if (x != j && nums[i][x] == 1) { + return false; + } + if (x != i && nums[x][j] == 1) { + return false; + } + } + for (int32_t x{i + 1}, y{j + 1}; x < length && y < length; x++, y++) { + if (nums[x][y] == 1) { + return false; + } + } + for (int32_t x{i - 1}, y{j - 1}; x >= 0 && y >= 0; x--, y--) { + if (nums[x][y] == 1) { + return false; + } + } + for (int32_t x{i - 1}, y{j + 1}; x >= 0 && y < length; x--, y++) { + if (nums[x][y] == 1) { + return false; + } + } + for (int32_t x{i + 1}, y{j - 1}; x < length && y >= 0; x++, y--) { + if (nums[x][y] == 1) { + return false; + } + } + return true; + } + + void store(const vector> &nums, vector> &insert) { + const auto length = nums.size(); + insert.emplace_back(); + for (size_t i{0}; i < length; i++) { + string line(length, '.'); + for (size_t j{0}; j < length; j++) { + if (nums[i][j] == 1) { + line[j] = 'Q'; + } + } + insert.back().push_back(line); + } + } + +public: + vector> solveNQueen(int32_t n) { + if (n == 1) { + return {{"Q"}}; + } else if (n < 4) { + return {}; + } + assert(n > 3); + // 感觉这里的思路应该用递归比较好, 对于每一个n, 我们假设n-1已经解决了, 对于每一种情况来说,有左上 左下 右上 右下四个拓展情况, 每种拓展情况有2n-1个类型, + // 通过(n-1)^2的时间复杂度visit获取其 + // 但是八皇后问题不能这样递推, 因为不是所有n皇后问题都能够简化出一个n-1皇后的区域, 倒不如说能规约出来的才比较少见. + // 使用回溯的方式来计算, + vector> will_return{}; + vector> visit(n, vector(n, 0)); + int32_t i{0}, j{0}; + int32_t count{0}; + std::stack sta{}; + // 需要返回的数组只不过是一个{(x1,y1),(x2,y2)....}的映射, 所以不需要存储那个, 只需要存每个皇后的坐标即可, 也方便之后进行去重. + while (i < n && j < n) { + if (visit[i][j] == 0) { + visit[i][j] = 1; + } // this can be a queen. + // then should filter all the other positions, line, row and diagonal. + // 或者是不存储只是尝试? + // 对(i,j)尝试放一个, 接下来对(i+1,0 to n-1)进行挨个尝试, 每个判定一次, 如果都不行, 则回退i并j+1. + // 大概n^3 + if (check(visit, i, j)) { + if (i + 1 < n) { + i++; + sta.push(j); + j = 0; + continue; + } else { + store(visit, will_return); + // should get the last i + } + } + visit[i][j] = 0; + if (j + 1 < n) { + j++; + } else if (j + 1 == n) { + i--; + j = sta.top(); + sta.pop(); + if (i == 0 && j + 1 >= n) { + break; + } + while (j + 1 == n) { + visit[i][j] = 0; + i--; + j = sta.top(); + sta.pop(); + } + visit[i][j] = 0; + j += 1; + } + + } + return will_return; + } +}; + +#ifdef ALGORITHM_TEST_MACRO +} +#endif diff --git a/algorithm/array/leetcode_golden_0812_test.cpp b/algorithm/array/leetcode_golden_0812_test.cpp new file mode 100644 index 00000000..4e788b7c --- /dev/null +++ b/algorithm/array/leetcode_golden_0812_test.cpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_golden_0812_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_golden_0812_TEST_HPP + +#include +#include "leetcode_golden_0812.cpp" + +namespace leetcode_golden_0812 { +using Catch::Matchers::UnorderedEquals; + +TEST_CASE("test case 1 [test_golden_0812]", "[test_golden_0812]") { + auto sol = Solution(); + constexpr const int32_t input{1}; + const std::vector> result{{"Q"}}; + CHECK_THAT(result, UnorderedEquals(sol.solveNQueen(input))); +} + +TEST_CASE("test case 2 3 [test_golden_0812]", "[test_golden_0812]") { + auto sol = Solution(); + CHECK_THAT(std::vector>{}, UnorderedEquals(sol.solveNQueen(2))); + CHECK_THAT(std::vector>{}, UnorderedEquals(sol.solveNQueen(3))); +} + +TEST_CASE("test case 5 [test_golden_0812]", "[test_golden_0812]") { + auto sol = Solution(); + CHECK_THAT((std::vector>{{ + ".Q..", + "...Q", + "Q...", + "..Q.", + + }, + { + "..Q.", + "Q...", + "...Q", + ".Q..", + + }}), + UnorderedEquals(sol.solveNQueen(4))); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_golden_0812_TEST_HPP diff --git a/algorithm/array/leetcode_so_03.cpp b/algorithm/array/leetcode_so_03.cpp index aa10e51e..c0cd5f74 100644 --- a/algorithm/array/leetcode_so_03.cpp +++ b/algorithm/array/leetcode_so_03.cpp @@ -1,50 +1,58 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_so_03_test.hpp" #include +#include +#include +#include +#include -namespace leetcode_so_03 { +using std::vector; using std::unordered_map; -int32_t leetcode_so_03::findRepeatNumber(const vector &nums_) { - vector nums{nums_}; - std::sort(nums.begin(), nums.end()); - for (size_t i{0}, size{nums.size()}; i + 1 < size; ++i) { - if (nums[i] == nums[i + 1]) { - return nums[i]; +namespace leetcode_so_03 { +#endif + +class Solution { +public: + int32_t findRepeatNumber(const vector &nums_) { + vector nums{nums_}; + std::sort(nums.begin(), nums.end()); + for (size_t i{0}, size{nums.size()}; i + 1 < size; ++i) { + if (nums[i] == nums[i + 1]) { + return nums[i]; + } } + return 0; } - return 0; -} -int32_t leetcode_so_03::findRepeatNumber2(const vector &nums) { - unordered_map umap; - for (size_t i{0}, size{nums.size()}; i < size; ++i) { - ++umap[nums[i]]; - if (umap[nums[i]] == 2) { - return nums[i]; + int32_t findRepeatNumber2(const vector &nums) { + unordered_map umap; + for (size_t i{0}, size{nums.size()}; i < size; ++i) { + ++umap[nums[i]]; + if (umap[nums[i]] == 2) { + return nums[i]; + } } + return -1; } - return -1; -} -int32_t leetcode_so_03::findRepeatNumber3(const vector &nums_) { - vector nums{nums_}; - for (size_t i{0}, size{nums.size()}; i < size; ++i) { - const auto num = [](const auto i) { - return i >= 0 ? i : -i - 1; - }(nums[i]); - if (nums[num] < 0) { - return num; + int32_t findRepeatNumber3(const vector &nums_) { + vector nums{nums_}; + for (size_t i{0}, size{nums.size()}; i < size; ++i) { + const auto num = [](const auto i) { + return i >= 0 ? i : -i - 1; + }(nums[i]); + if (nums[num] < 0) { + return num; + } + nums[num] = -nums[num] - 1; } - nums[num] = -nums[num] - 1; + return -1; } - return -1; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_so_03_test.cpp b/algorithm/array/leetcode_so_03_test.cpp new file mode 100644 index 00000000..c97c0cda --- /dev/null +++ b/algorithm/array/leetcode_so_03_test.cpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 暴力解法 +//@Plan 剑指OfferII-I Day04 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_03_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_03_TEST_HPP + +#include "leetcode_so_03.cpp" +#include + +namespace leetcode_so_03 { + +TEST_CASE("test case 1 [test_so_03]", "[test_so_03]") { + auto sol = Solution(); + std::vector input{1, 2, 2, 3, 1}; + std::vector input2{1, 2, 2, 3, 1}; + std::vector input3{1, 2, 2, 3, 1}; + static constexpr const auto resultOne{1}, resultTwo{2}; + CHECK(resultOne == sol.findRepeatNumber(input)); + CHECK(resultTwo == sol.findRepeatNumber2(input2)); + CHECK(resultTwo == sol.findRepeatNumber3(input3)); +} + +TEST_CASE("test case 2 [test_so_03]", "[test_so_03]") { + auto sol = Solution(); + std::vector input{2, 3, 1, 0, 2, 5, 3}; + std::vector input2{2, 3, 1, 0, 2, 5, 3}; + std::vector input3{2, 3, 1, 0, 2, 5, 3}; + static constexpr const auto resultOne{2}; + CHECK(resultOne == sol.findRepeatNumber(input)); + CHECK(resultOne == sol.findRepeatNumber2(input2)); + CHECK(resultOne == sol.findRepeatNumber3(input3)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_03_TEST_HPP diff --git a/algorithm/array/leetcode_so_03_test.hpp b/algorithm/array/leetcode_so_03_test.hpp deleted file mode 100644 index dba9b28d..00000000 --- a/algorithm/array/leetcode_so_03_test.hpp +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 暴力解法 -//@Plan 剑指OfferII-I Day04 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_03_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_03_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_so_03 { -using std::vector; - -struct leetcode_so_03 { - static int32_t findRepeatNumber(const vector &nums); - - static int32_t findRepeatNumber2(const vector &nums); - - static int32_t findRepeatNumber3(const vector &nums); -}; - -TEST_CASE("test case 1 [test_so_03]", "[test_so_03]") { - const vector input{1, 2, 2, 3, 1}; - static constexpr const auto resultOne{1}, resultTwo{2}; - CHECK(resultOne == leetcode_so_03::findRepeatNumber(input)); - CHECK(resultTwo == leetcode_so_03::findRepeatNumber2(input)); - CHECK(resultTwo == leetcode_so_03::findRepeatNumber3(input)); -} - -TEST_CASE("test case 2 [test_so_03]", "[test_so_03]") { - const vector input{2, 3, 1, 0, 2, 5, 3}; - static constexpr const auto resultOne{2} - //, resultTwo{3} - ; - CHECK(resultOne == leetcode_so_03::findRepeatNumber(input)); - CHECK(resultOne == leetcode_so_03::findRepeatNumber2(input)); - CHECK(resultOne == leetcode_so_03::findRepeatNumber3(input)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_03_TEST_HPP diff --git a/algorithm/array/leetcode_so_21.cpp b/algorithm/array/leetcode_so_21.cpp index 16000c5e..18594eaf 100644 --- a/algorithm/array/leetcode_so_21.cpp +++ b/algorithm/array/leetcode_so_21.cpp @@ -1,28 +1,40 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds +#include +#include +#include -*/ -#include "leetcode_so_21_test.hpp" +using std::vector; namespace leetcode_so_21 { +#endif -vector leetcode_so_21::exchange(const vector &nums_const) { - if (nums_const.empty()) { - return {}; +class Solution { +public: + vector exchange(const vector &nums_const) { + if (nums_const.empty()) { + return {}; + } + vector nums{nums_const}; + static constexpr const auto judge = [](const auto num) -> bool { return num % 2 == 0; }; + // 实际上完全可以是左边模三余1,右边余0,2 + const auto nums_size{nums.size()}; + for (size_t left{0}, right{nums_size - 1}; left < right;) { + for (; left < right && !judge(nums[left]); ++left) { + } + for (; left < right && judge(nums[right]); --right) { + } + if (left >= right) { + return nums; + } + std::swap(nums[left], nums[right]); + } + return nums; } - vector nums{nums_const}; - static constexpr const auto judge = [](const auto num) -> bool { return num % 2 == 0; }; - // 实际上完全可以是左边模三余1,右边余0,2 - const auto nums_size{nums.size()}; - for (size_t left{0}, right{nums_size - 1}; left < right;) { - for (; left < right && !judge(nums[left]); ++left) {} - for (; left < right && judge(nums[right]); --right) {} - if (left >= right) { return nums; } - std::swap(nums[left], nums[right]); - } - return nums; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/array/leetcode_so_21_test.cpp b/algorithm/array/leetcode_so_21_test.cpp new file mode 100644 index 00000000..9ae00f7f --- /dev/null +++ b/algorithm/array/leetcode_so_21_test.cpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag 双指针 +//@Plan 剑指OfferII-I Day13 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_21_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_21_TEST_HPP + +#include "leetcode_so_21.cpp" +#include + +namespace leetcode_so_21 { +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_so_21]", "[test_so_21]") { + auto sol = Solution(); + std::vector input{1, 2, 3, 4}; + const std::vector output{1, 3, 2, 4}; + CHECK_THAT(output, Equals(sol.exchange(input))); +} + +TEST_CASE("test case 2 [test_so_21]", "[test_so_21]") { + auto sol = Solution(); + std::vector input{1, 3, 5}; + const std::vector output{1, 3, 5}; + CHECK_THAT(output, Equals(sol.exchange(input))); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_21_TEST_HPP diff --git a/algorithm/array/leetcode_so_21_test.hpp b/algorithm/array/leetcode_so_21_test.hpp deleted file mode 100644 index 849af02d..00000000 --- a/algorithm/array/leetcode_so_21_test.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Tag 双指针 -//@Plan 剑指OfferII-I Day13 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_21_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_21_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_so_21 { -using std::vector; - -struct leetcode_so_21 { - static vector exchange(const vector &nums); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_so_21]", "[test_so_21]") { - const vector input{1, 2, 3, 4}; - const vector output{1, 3, 2, 4}; - CHECK_THAT(output, Equals(leetcode_so_21::exchange(input))); -} - -TEST_CASE("test case 2 [test_so_21]", "[test_so_21]") { - const vector input{1, 3, 5}; - const vector output{1, 3, 5}; - CHECK_THAT(output, Equals(leetcode_so_21::exchange(input))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_21_TEST_HPP diff --git a/algorithm/array/leetcode_so_45.cpp b/algorithm/array/leetcode_so_45.cpp index 5ee72eef..57d9fba4 100644 --- a/algorithm/array/leetcode_so_45.cpp +++ b/algorithm/array/leetcode_so_45.cpp @@ -1,42 +1,53 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_so_45_test.hpp" +#include +#include +#include +#include +#include namespace leetcode_so_45 { +using std::array; +using std::vector; +using std::string; +#endif -string leetcode_so_45::minNumber(const vector &numsImmutable) { - auto nums{numsImmutable}; - const auto comp = [](auto nums1, auto nums2) { - const auto tovec = [](auto nums_fst, auto nums_snd) { - vector vec{}; - if (nums_fst == 0) { vec.push_back(0); } - for (; nums_fst != 0; nums_fst /= 10) { vec.push_back(nums_fst % 10); } - if (nums_snd == 0) { vec.push_back(0); } - for (; nums_snd != 0; nums_snd /= 10) { vec.push_back(nums_snd % 10); } - return vector{vec.crbegin(), vec.crend()}; - // TODO,此处可优化 - }; - const vector fst = tovec(nums1, nums2), snd = tovec(nums2, nums1); - const auto length = fst.size(); - for (size_t i{0}; i < length; ++i) { - if (fst[i] > snd[i]) { - return true; - } else if (fst[i] < snd[i]) { - return false; +class Solution { +public: + string minNumber(const vector &numsImmutable) { + auto nums{numsImmutable}; + const auto comp = [](auto nums1, auto nums2) { + const auto tovec = [](auto nums_fst, auto nums_snd) { + vector vec{}; + if (nums_fst == 0) { vec.push_back(0); } + for (; nums_fst != 0; nums_fst /= 10) { vec.push_back(nums_fst % 10); } + if (nums_snd == 0) { vec.push_back(0); } + for (; nums_snd != 0; nums_snd /= 10) { vec.push_back(nums_snd % 10); } + return vector{vec.crbegin(), vec.crend()}; + // TODO,此处可优化 + }; + const vector fst = tovec(nums1, nums2), snd = tovec(nums2, nums1); + const auto length = fst.size(); + for (size_t i{0}; i < length; ++i) { + if (fst[i] > snd[i]) { + return true; + } else if (fst[i] < snd[i]) { + return false; + } } + return false; + }; + std::sort(nums.begin(), nums.end(), comp); + string will_return{}; + for (const auto num: nums) { + will_return += std::to_string(num); } - return false; - }; - std::sort(nums.begin(), nums.end(), comp); - string will_return{}; - for (const auto num: nums) { - will_return += std::to_string(num); + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/array/leetcode_so_45_test.cpp b/algorithm/array/leetcode_so_45_test.cpp new file mode 100644 index 00000000..b8455428 --- /dev/null +++ b/algorithm/array/leetcode_so_45_test.cpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Description 自定义比较函数 +//@Plan 剑指OfferII-I Day16 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_45_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_45_TEST_HPP + +#include "leetcode_so_45.cpp" +#include + +namespace leetcode_so_45 { +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_so_45]", "[test_so_45]") { + auto sol = Solution(); + std::vector input{10, 2}; + static constexpr const char *const output{"102"}; + CHECK_THAT(output, Equals(sol.minNumber(input))); +} + +TEST_CASE("test case 2 [test_so_45]", "[test_so_45]") { + auto sol = Solution(); + std::vector input{3, 30, 34, 5, 9}; + static constexpr const char *const output{"3033459"}; + CHECK_THAT(output, Equals(sol.minNumber(input))); +} + +TEST_CASE("test case 3 [test_so_45]", "[test_so_45]") { + auto sol = Solution(); + std::vector input{12, 121}; + static constexpr const char *const output{"12112"}; + CHECK_THAT(output, Equals(sol.minNumber(input))); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_45_TEST_HPP diff --git a/algorithm/array/leetcode_so_45_test.hpp b/algorithm/array/leetcode_so_45_test.hpp deleted file mode 100644 index df2805ba..00000000 --- a/algorithm/array/leetcode_so_45_test.hpp +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag array -//@Tag 数组 -//@Description 自定义比较函数 -//@Plan 剑指OfferII-I Day16 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_45_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_45_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_so_45 { -using std::vector; -using std::string; - -struct leetcode_so_45 { - static string minNumber(const vector &nums); -}; -using Catch::Matchers::Equals; -TEST_CASE("test case 1 [test_so_45]", "[test_so_45]") { - const vector input{10, 2}; - static constexpr const char *const output{"102"}; - CHECK_THAT(output,Equals(leetcode_so_45::minNumber(input))); -} - -TEST_CASE("test case 2 [test_so_45]", "[test_so_45]") { - const vector input{3, 30, 34, 5, 9}; - static constexpr const char *const output{"3033459"}; - CHECK_THAT(output,Equals(leetcode_so_45::minNumber(input))); -} - -TEST_CASE("test case 3 [test_so_45]", "[test_so_45]") { - const vector input{12, 121}; - static constexpr const char *const output{"12112"}; - CHECK_THAT(output,Equals(leetcode_so_45::minNumber(input))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_45_TEST_HPP diff --git a/algorithm/array/leetcode_so_61.cpp b/algorithm/array/leetcode_so_61.cpp index dfbabe74..2214e89d 100644 --- a/algorithm/array/leetcode_so_61.cpp +++ b/algorithm/array/leetcode_so_61.cpp @@ -1,40 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_so_61_test.hpp" #include +#include +#include namespace leetcode_so_61 { using std::array; +using std::vector; +#endif -bool leetcode_so_61::isStraight(const vector &nums) { - if (nums.size() != 5) { - return false; - } - std::array umap{0};// 0 to 13 - int32_t maxV{-1}, minV{114514}, zeros{0}; - for (const auto num: nums) { - if (num == 0) { - ++zeros; - } else { - if (umap[num] == 0) { - umap[num] = 1; +class Solution { +public: + bool isStraight(const vector &nums) { + if (nums.size() != 5) { + return false; + } + std::array umap{0};// 0 to 13 + int32_t maxV{-1}, minV{114514}, zeros{0}; + for (const auto num: nums) { + if (num == 0) { + ++zeros; } else { - return false; + if (umap[num] == 0) { + umap[num] = 1; + } else { + return false; + } + maxV = std::max(maxV, num); + minV = std::min(minV, num); } - maxV = std::max(maxV, num); - minV = std::min(minV, num); } + const auto maxDiff{maxV - minV}; + if (maxDiff > 4 || maxDiff + zeros < 4) { + return false; + } + return true; } - const auto maxDiff{maxV - minV}; - if (maxDiff > 4 || maxDiff + zeros < 4) { - return false; - } - return true; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/array/leetcode_so_61_test.hpp b/algorithm/array/leetcode_so_61_test.cpp similarity index 50% rename from algorithm/array/leetcode_so_61_test.hpp rename to algorithm/array/leetcode_so_61_test.cpp index a27620a2..ddce1893 100644 --- a/algorithm/array/leetcode_so_61_test.hpp +++ b/algorithm/array/leetcode_so_61_test.cpp @@ -1,51 +1,45 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 //@Plan 剑指OfferII-I Day16 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_61_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_61_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_61_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_61_TEST_HPP +#include "leetcode_so_61.cpp" #include -#include -#include -#include namespace leetcode_so_61 { -using std::vector; - -struct leetcode_so_61 { - static bool isStraight(const vector &nums); -}; TEST_CASE("test case 1 [test_so_61]", "[test_so_61]") { + auto sol = Solution(); const vector input{10, 2}; - CHECK_FALSE(leetcode_so_61::isStraight(input)); + CHECK_FALSE(sol.isStraight(input)); } TEST_CASE("test case 2 [test_so_61]", "[test_so_61]") { + auto sol = Solution(); const vector input{1, 2, 3, 4, 5}; - CHECK(leetcode_so_61::isStraight(input)); + CHECK(sol.isStraight(input)); } TEST_CASE("test case 3 [test_so_61]", "[test_so_61]") { + auto sol = Solution(); const vector input{12, 13, 7, 10, 8}; - CHECK_FALSE(leetcode_so_61::isStraight(input)); + CHECK_FALSE(sol.isStraight(input)); } TEST_CASE("test case 4 [test_so_61]", "[test_so_61]") { + auto sol = Solution(); const vector input{0, 0, 1, 2, 5}; - CHECK(leetcode_so_61::isStraight(input)); + CHECK(sol.isStraight(input)); } TEST_CASE("test case 5 [test_so_61]", "[test_so_61]") { + auto sol = Solution(); const vector input{0, 0, 2, 2, 5}; - CHECK_FALSE(leetcode_so_61::isStraight(input)); + CHECK_FALSE(sol.isStraight(input)); } + } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_61_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_SO_61_TEST_HPP diff --git a/algorithm/associative_container/CMakeLists.txt b/algorithm/associative_container/CMakeLists.txt index 4fd7ba5c..42a54888 100644 --- a/algorithm/associative_container/CMakeLists.txt +++ b/algorithm/associative_container/CMakeLists.txt @@ -17,10 +17,10 @@ set(dependencies ${dependencies} ${leetcode_order}) unset(leetcode_order) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE CS203_DSAA_TEST_MACRO) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) endforeach () unset(dependencies) diff --git a/algorithm/associative_container/leetcode_1002.cpp b/algorithm/associative_container/leetcode_1002.cpp index f4fe12a2..dbac5a94 100644 --- a/algorithm/associative_container/leetcode_1002.cpp +++ b/algorithm/associative_container/leetcode_1002.cpp @@ -1,35 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1002_test.hpp" +#include +#include +#include +#include +#include +#include namespace leetcode_1002 { -static constexpr const size_t chars{26}; +using std::array; +using std::string; +using std::vector; +#endif -vector leetcode_1002::commonChars(const vector &words) { - std::array arr{0}; - std::fill(arr.begin(), arr.end(), 100); - for (const auto &word: words) { - std::array nums{0}; - for (const auto &ch: word) { - ++nums[ch - 'a']; - } - for (size_t i{0}; i < chars; ++i) { - arr[i] = std::min(nums[i], arr[i]); +class Solution { +public: + vector commonChars(const vector &words) { + static constexpr const size_t chars{26}; + array arr{0}; + std::fill(arr.begin(), arr.end(), 100); + for (const auto &word: words) { + array nums{0}; + for (const auto &ch: word) { + ++nums[ch - 'a']; + } + for (size_t i{0}; i < chars; ++i) { + arr[i] = std::min(nums[i], arr[i]); + } } - } - vector will_return{}; - for (char i{'a'}; i <= 'z'; ++i) { - const auto ch = arr[i - 'a']; - for (size_t j{1}; j <= ch; j++) { - will_return.push_back(std::string{i}); + vector will_return{}; + for (char i{'a'}; i <= 'z'; ++i) { + const auto ch = arr[i - 'a']; + for (size_t j{1}; j <= ch; j++) { + will_return.push_back(string{i}); + } } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_1002_test.hpp b/algorithm/associative_container/leetcode_1002_test.cpp similarity index 61% rename from algorithm/associative_container/leetcode_1002_test.hpp rename to algorithm/associative_container/leetcode_1002_test.cpp index 064ba0aa..8d728949 100644 --- a/algorithm/associative_container/leetcode_1002_test.hpp +++ b/algorithm/associative_container/leetcode_1002_test.cpp @@ -1,30 +1,14 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag associative_container //@Tag xor -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1002_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1002_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1002_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1002_TEST_HPP +#include "leetcode_1002.cpp" #include -#include -#include -#include -#include -#include namespace leetcode_1002 { -using std::array; -using std::string; -using std::vector; - -struct leetcode_1002 { - static vector commonChars(const vector &words); -}; using Catch::Matchers::Equals; @@ -35,8 +19,9 @@ TEST_CASE("test case 1 {test_1002}", "{test_1002}") { static constexpr const std::array result{ "e", "l", "l" }; + Solution solution; CHECK_THAT((vector{result.cbegin(), result.cend()}), - Equals(leetcode_1002::commonChars({arr.cbegin(), arr.cend()})) + Equals(solution.commonChars({arr.cbegin(), arr.cend()})) ); } @@ -48,8 +33,9 @@ TEST_CASE("test case 2 {test_1002}", "{test_1002}") { static constexpr const std::array result{ "c", "o" }; + Solution solution; CHECK_THAT((vector{result.cbegin(), result.cend()}), - Equals(leetcode_1002::commonChars({arr.cbegin(), arr.cend()})) + Equals(solution.commonChars({arr.cbegin(), arr.cend()})) ); } @@ -59,10 +45,11 @@ TEST_CASE("test case 3 {test_1002}", "{test_1002}") { "acabcddd", "bcbdbcbd", "baddbadb", "cbdddcac", "aacbcccd", "ccccddda", "cababaab", "addcaccd" }; static constexpr const std::array result{}; + Solution solution; CHECK_THAT((vector{result.cbegin(), result.cend()}), - Equals(leetcode_1002::commonChars({arr.cbegin(), arr.cend()})) + Equals(solution.commonChars({arr.cbegin(), arr.cend()})) ); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1002_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1002_TEST_HPP diff --git a/algorithm/associative_container/leetcode_1078.cpp b/algorithm/associative_container/leetcode_1078.cpp index 0075e64a..2ba9e66c 100644 --- a/algorithm/associative_container/leetcode_1078.cpp +++ b/algorithm/associative_container/leetcode_1078.cpp @@ -1,39 +1,48 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1078_test.hpp" +#include +#include +#include +#include +#include namespace leetcode_1078 { +using std::vector; +using std::string; +#endif -vector leetcode_1078::findOcurrences(const string &text, const string &first, const string &second) { - vector vecs; - vector words{}, results{}; - const auto fstHash = std::hash()(first); - const auto sndHash = std::hash()(second); - string texts_{text}; - texts_.push_back(' '); - const string &texts{texts_}; - for (size_t i{0}, length{1}; i < texts.size();) { - if (texts[i + length] == ' ') { - const auto substr{texts.substr(i, length)}; - vecs.push_back(std::hash()(substr)); - words.push_back(substr); - i += length + 1; - length = 1; - } else { - length += 1; +class Solution { +public: + vector findOcurrences(const string &text, const string &first, const string &second) { + vector vecs; + vector words{}, results{}; + const auto fstHash = std::hash()(first); + const auto sndHash = std::hash()(second); + string texts_{text}; + texts_.push_back(' '); + const string &texts{texts_}; + for (size_t i{0}, length{1}; i < texts.size();) { + if (texts[i + length] == ' ') { + const auto substr{texts.substr(i, length)}; + vecs.push_back(std::hash()(substr)); + words.push_back(substr); + i += length + 1; + length = 1; + } else { + length += 1; + } } - } - for (size_t i{1}; i + 1 < vecs.size(); ++i) { - if (vecs[i - 1] == fstHash && vecs[i] == sndHash) { - results.push_back(words[i + 1]); + for (size_t i{1}; i + 1 < vecs.size(); ++i) { + if (vecs[i - 1] == fstHash && vecs[i] == sndHash) { + results.push_back(words[i + 1]); + } } + return results; } - return results; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_1078_test.cpp b/algorithm/associative_container/leetcode_1078_test.cpp new file mode 100644 index 00000000..a2f7cd18 --- /dev/null +++ b/algorithm/associative_container/leetcode_1078_test.cpp @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag associative_container + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1078_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1078_TEST_HPP + +#include "leetcode_1078.cpp" +#include + +namespace leetcode_1078 { + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 {test_1078}", "{test_1078}") { + static constexpr const char *const text{"how are you indian mi fans do you like mi four i"}; + static constexpr const char *const fst{"mi"}; + static constexpr const char *const snd{"fans"}; + const vector result{"do"}; + Solution solution; + CHECK_THAT(result, Equals(solution.findOcurrences(text, fst, snd))); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1078_TEST_HPP diff --git a/algorithm/associative_container/leetcode_1078_test.hpp b/algorithm/associative_container/leetcode_1078_test.hpp deleted file mode 100644 index f76e5f90..00000000 --- a/algorithm/associative_container/leetcode_1078_test.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag associative_container - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1078_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1078_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_1078 { -using std::vector; - -struct leetcode_1078 { - static vector findOcurrences(const string &text, const string &first, const string &second); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 {test_1078}", "{test_1078}") { - static constexpr const char *const text{"how are you indian mi fans do you like mi four i"}; - static constexpr const char *const fst{"mi"}; - static constexpr const char *const snd{"fans"}; - const vector result{"do"}; - CHECK_THAT(result, Equals(leetcode_1078::findOcurrences(text, fst, snd))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1078_TEST_HPP diff --git a/algorithm/associative_container/leetcode_1122.cpp b/algorithm/associative_container/leetcode_1122.cpp index 1be0ef70..8c5e32fc 100644 --- a/algorithm/associative_container/leetcode_1122.cpp +++ b/algorithm/associative_container/leetcode_1122.cpp @@ -1,29 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1122_test.hpp" +#include +#include +#include #include +#include namespace leetcode_1122 { using std::array; +using std::vector; +#endif -vector leetcode_1122::relativeSortArray(const vector &arr1, const vector &arr2) { - std::array umap{0}; - const auto arr2_size = static_cast(arr2.size()); - for (int32_t i{0}; i < arr2_size; ++i) { - umap[arr2[i]] = i + 1; +class Solution { +public: + vector relativeSortArray(const vector &arr1, const vector &arr2) { + std::array umap{0}; + const auto arr2_size = static_cast(arr2.size()); + for (int32_t i{0}; i < arr2_size; ++i) { + umap[arr2[i]] = i + 1; + } + vector arr{arr1}; + std::sort(arr.begin(), arr.end(), [&umap](const auto x, const auto y) -> bool { + const auto num_x = (umap[x] == 0) ? x + 2000 : umap[x]; + const auto num_y = (umap[y] == 0) ? y + 2000 : umap[y]; + return num_x < num_y; + }); + return arr; } - vector arr{arr1}; - std::sort(arr.begin(), arr.end(), [&umap](const auto x, const auto y) -> bool { - const auto num_x = (umap[x] == 0) ? x + 2000 : umap[x]; - const auto num_y = (umap[y] == 0) ? y + 2000 : umap[y]; - return num_x < num_y; - }); - return arr; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_1122_test.cpp b/algorithm/associative_container/leetcode_1122_test.cpp new file mode 100644 index 00000000..07a865ce --- /dev/null +++ b/algorithm/associative_container/leetcode_1122_test.cpp @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag associative_container + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1122_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1122_TEST_HPP + +#include "leetcode_1122.cpp" +#include + +namespace leetcode_1122 { + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 {test_1122}", "{test_1122}") { + const vector arr1{2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19}; + const vector arr2{2, 1, 4, 3, 9, 6}; + const vector result{2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19}; + Solution solution; + CHECK_THAT(result, Equals(solution.relativeSortArray(arr1, arr2))); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1122_TEST_HPP diff --git a/algorithm/associative_container/leetcode_1122_test.hpp b/algorithm/associative_container/leetcode_1122_test.hpp deleted file mode 100644 index ad4dcd20..00000000 --- a/algorithm/associative_container/leetcode_1122_test.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag associative_container - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1122_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1122_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_1122 { -using std::vector; - -struct leetcode_1122 { - static vector relativeSortArray(const vector &arr1, const vector &arr2); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 {test_1122}", "{test_1122}") { - const vector arr1{2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19}; - const vector arr2{2, 1, 4, 3, 9, 6}; - const vector result{2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19}; - CHECK_THAT(result, Equals(leetcode_1122::relativeSortArray(arr1, arr2))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1122_TEST_HPP diff --git a/algorithm/associative_container/leetcode_1128.cpp b/algorithm/associative_container/leetcode_1128.cpp index a79c32f4..bd606508 100644 --- a/algorithm/associative_container/leetcode_1128.cpp +++ b/algorithm/associative_container/leetcode_1128.cpp @@ -1,34 +1,40 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1128_test.hpp" +#include +#include +#include #include namespace leetcode_1128 { using std::array; +using std::vector; +#endif -int32_t leetcode_1128::numEquivDominoPairs(const vector> &dominoes) { - std::array, 10> arr{}; - for (const auto &domino: dominoes) { - const auto fst{domino[0]}, snd{domino[1]}; - if (fst > snd) { - arr[fst][snd] += 1; - } else { - arr[snd][fst] += 1; +class Solution { +public: + int numEquivDominoPairs(const vector> &dominoes) { + std::array, 10> arr{}; + for (const auto &domino: dominoes) { + const auto fst{domino[0]}, snd{domino[1]}; + if (fst > snd) { + arr[fst][snd] += 1; + } else { + arr[snd][fst] += 1; + } } - } - int32_t will_return{0}; - for (size_t i{0}; i < 10; ++i) { - for (size_t j{0}; j < i; ++j) { - const auto num{arr[i][j]}; - will_return += (num > 1 ? (num - 1) * num / 2 : 0); + int32_t will_return{0}; + for (size_t i{0}; i < 10; ++i) { + for (size_t j{0}; j < i; ++j) { + const auto num{arr[i][j]}; + will_return += (num > 1 ? (num - 1) * num / 2 : 0); + } } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_1128_test.cpp b/algorithm/associative_container/leetcode_1128_test.cpp new file mode 100644 index 00000000..8ce7bfce --- /dev/null +++ b/algorithm/associative_container/leetcode_1128_test.cpp @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag associative_container + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1128_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1128_TEST_HPP + +#include "leetcode_1128.cpp" +#include + +namespace leetcode_1128 { + +TEST_CASE("test case 1 {test_1128}", "{test_1128}") { + const vector> input{{1, 2}, + {2, 1}, + {3, 4}, + {5, 6}}; + Solution solution; + CHECK(1 == solution.numEquivDominoPairs(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1128_TEST_HPP diff --git a/algorithm/associative_container/leetcode_1128_test.hpp b/algorithm/associative_container/leetcode_1128_test.hpp deleted file mode 100644 index d1aecc7b..00000000 --- a/algorithm/associative_container/leetcode_1128_test.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag associative_container - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1128_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1128_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_1128 { -using std::vector; - -struct leetcode_1128 { - static int32_t numEquivDominoPairs(const vector> &dominoes); -}; - -TEST_CASE("test case 1 {test_1128}", "{test_1128}") { - const vector> input{{1, 2}, - {2, 1}, - {3, 4}, - {5, 6}}; - CHECK(1 == leetcode_1128::numEquivDominoPairs(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1128_TEST_HPP diff --git a/algorithm/associative_container/leetcode_1160.cpp b/algorithm/associative_container/leetcode_1160.cpp index 7f83d8c5..f78e0765 100644 --- a/algorithm/associative_container/leetcode_1160.cpp +++ b/algorithm/associative_container/leetcode_1160.cpp @@ -1,34 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1160_test.hpp" +#include +#include +#include +#include +#include #include namespace leetcode_1160 { using std::array; +using std::vector; +using std::string; +#endif -int32_t leetcode_1160::countCharacters(const vector &words, std::string_view chars) { - array sizes{0}; - for (const auto ch: chars) { - sizes[ch - 'a'] += 1; - } - int32_t will_return{0}; - for (const auto &word: words) { - array useable{sizes}; - will_return += word.size(); - for (const auto wor: word) { - if (useable[wor - 'a'] == 0) { - will_return -= word.size(); - break; +class Solution { +public: + int32_t countCharacters(const vector &words, std::string_view chars) { + array sizes{0}; + for (const auto ch: chars) { + sizes[ch - 'a'] += 1; + } + int32_t will_return{0}; + for (const auto &word: words) { + array useable{sizes}; + will_return += word.size(); + for (const auto wor: word) { + if (useable[wor - 'a'] == 0) { + will_return -= word.size(); + break; + } + useable[wor - 'a'] -= 1; } - useable[wor - 'a'] -= 1; } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_1160_test.cpp b/algorithm/associative_container/leetcode_1160_test.cpp new file mode 100644 index 00000000..277810e9 --- /dev/null +++ b/algorithm/associative_container/leetcode_1160_test.cpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag associative_container + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1160_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1160_TEST_HPP + +#include "leetcode_1160.cpp" +#include + +namespace leetcode_1160 { + +TEST_CASE("test case 1 {test_1160}", "{test_1160}") { + const vector input{"aaa", "bbb", "ccc"}; + const string chars{"aabbbcccc"}; + Solution solution; + CHECK(6 == solution.countCharacters(input, chars)); +} + +TEST_CASE("test case 2 {test_1160}", "{test_1160}") { + const vector input{"cat", "bt", "hat", "tree"}; + const string chars{"atach"}; + Solution solution; + CHECK(6 == solution.countCharacters(input, chars)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1160_TEST_HPP diff --git a/algorithm/associative_container/leetcode_1160_test.hpp b/algorithm/associative_container/leetcode_1160_test.hpp deleted file mode 100644 index f7223a63..00000000 --- a/algorithm/associative_container/leetcode_1160_test.hpp +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag associative_container - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1160_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1160_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_1160 { -using std::vector; -using std::string; -using std::string_view; - -struct leetcode_1160 { - static int32_t countCharacters(const vector &words, string_view chars); -}; - -TEST_CASE("test case 1 {test_1160}", "{test_1160}") { - const vector input{"aaa", "bbb", "ccc"}; - const string chars{"aabbbcccc"}; - CHECK(6 == leetcode_1160::countCharacters(input, chars)); -} - -TEST_CASE("test case 2 {test_1160}", "{test_1160}") { - const vector input{"cat", "bt", "hat", "tree"}; - const string chars{"atach"}; - CHECK(6 == leetcode_1160::countCharacters(input, chars)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1160_TEST_HPP diff --git a/algorithm/associative_container/leetcode_1409.cpp b/algorithm/associative_container/leetcode_1409.cpp index 9fd7b0f0..f88cda4b 100644 --- a/algorithm/associative_container/leetcode_1409.cpp +++ b/algorithm/associative_container/leetcode_1409.cpp @@ -1,38 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1409_test.hpp" +#include +#include +#include #include - +#include namespace leetcode_1409 { using std::unordered_map; - -vector leetcode_1409::processQueries(const vector &queries, int32_t m) { - vector will_return; - if (queries.empty()) { - return will_return; - } - unordered_map num_pos; - for (int32_t i{0}; i < m; ++i) { - num_pos[i + 1] = i; - } - for (const auto &i: queries) { - int32_t pos = num_pos[i]; - will_return.push_back(pos); - for (auto &j: num_pos) { - if (j.second < pos) { - j.second++; - } - } - num_pos[i] = 0; - } - return will_return; -} +using std::vector; +#endif class bit final { private: @@ -47,35 +26,66 @@ class bit final { explicit bit(const int32_t size) : vec(size + 1, 0), max_size(size) {} void update(const int32_t location, const int32_t num) { - assert(location >= 1); // 入参并不从零开始, - for (int32_t pos{location}; pos <= max_size; pos += lowbit(pos)) { vec[pos] += num; } + assert(location >= 1); // 入参并不从零开始, + for (int32_t pos{location}; pos <= max_size; pos += lowbit(pos)) { + vec[pos] += num; + } } int32_t query(const int32_t location) const { int32_t ans{0}; - for (int32_t pos{location}; pos > 0; pos -= lowbit(pos)) { ans += vec[pos]; } + for (int32_t pos{location}; pos > 0; pos -= lowbit(pos)) { + ans += vec[pos]; + } return ans; } }; -vector leetcode_1409::processQueries2(const vector &queries, int32_t m) { - const int32_t query_nums = queries.size(); - bit tree(m + query_nums); - vector pos(m + 1); - for (int i{1}; i <= m; ++i) { - pos[i] = query_nums + i; - tree.update(query_nums + i, 1); +class Solution { +public: + vector processQueries(const vector &queries, int32_t m) { + vector will_return; + if (queries.empty()) { + return will_return; + } + unordered_map num_pos; + for (int32_t i{0}; i < m; ++i) { + num_pos[i + 1] = i; + } + for (const auto &i: queries) { + int32_t pos = num_pos[i]; + will_return.push_back(pos); + for (auto &j: num_pos) { + if (j.second < pos) { + j.second++; + } + } + num_pos[i] = 0; + } + return will_return; } - vector ans; - for (int i{0}; i < query_nums; ++i) { - const auto query{queries[i]}; - const auto loca = pos[query]; - tree.update(loca, -1); - ans.push_back(tree.query(loca)); - pos[query] = query_nums - i; - tree.update(pos[query], 1); + + vector processQueries2(const vector &queries, int32_t m) { + const int32_t query_nums = queries.size(); + bit tree(m + query_nums); + vector pos(m + 1); + for (int i{1}; i <= m; ++i) { + pos[i] = query_nums + i; + tree.update(query_nums + i, 1); + } + vector ans; + for (int i{0}; i < query_nums; ++i) { + const auto query{queries[i]}; + const auto loca = pos[query]; + tree.update(loca, -1); + ans.push_back(tree.query(loca)); + pos[query] = query_nums - i; + tree.update(pos[query], 1); + } + return ans; } - return ans; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_1409_test.cpp b/algorithm/associative_container/leetcode_1409_test.cpp new file mode 100644 index 00000000..64e3be05 --- /dev/null +++ b/algorithm/associative_container/leetcode_1409_test.cpp @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag associative_container + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1409_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1409_TEST_HPP + +#include "leetcode_1409.cpp" +#include + +namespace leetcode_1409 { + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 {test_1409}", "{test_1409}") { + const vector input{3, 1, 2, 1}; + static constexpr const auto m{5}; + const vector result{2, 1, 2, 1}; + Solution solution; + CHECK_THAT(result, Equals(solution.processQueries(input, m))); + CHECK_THAT(result, Equals(solution.processQueries2(input, m))); +} + +TEST_CASE("test case 2 {test_1409}", "{test_1409}") { + const vector input{4, 1, 2, 2}; + static constexpr const auto m{4}; + const vector result{3, 1, 2, 0}; + Solution solution; + CHECK_THAT(result, Equals(solution.processQueries(input, m))); + CHECK_THAT(result, Equals(solution.processQueries2(input, m))); +} + +TEST_CASE("test case 3 {test_1409}", "{test_1409}") { + const vector input{7, 5, 5, 8, 3}; + static constexpr const auto m{8}; + const vector result{6, 5, 0, 7, 5}; + Solution solution; + CHECK_THAT(result, Equals(solution.processQueries(input, m))); + CHECK_THAT(result, Equals(solution.processQueries2(input, m))); +} + +TEST_CASE("test case 4 {test_1409}", "{test_1409}") { + const vector input{8, 7, 4, 2, 8, 1, 7, 7}; + static constexpr const auto m{8}; + const vector result{7, 7, 5, 4, 3, 4, 4, 0}; + Solution solution; + CHECK_THAT(result, Equals(solution.processQueries(input, m))); + CHECK_THAT(result, Equals(solution.processQueries2(input, m))); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1409_TEST_HPP diff --git a/algorithm/associative_container/leetcode_1409_test.hpp b/algorithm/associative_container/leetcode_1409_test.hpp deleted file mode 100644 index 4ce2d570..00000000 --- a/algorithm/associative_container/leetcode_1409_test.hpp +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag associative_container - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1409_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1409_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_1409 { -using std::vector; - -struct leetcode_1409 { - static vector processQueries(const vector &queries, int32_t m); - - static vector processQueries2(const vector &queries, int32_t m); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 {test_1409}", "{test_1409}") { - const vector input{3, 1, 2, 1}; - static constexpr const auto m{5}; - const vector result{2, 1, 2, 1}; - CHECK_THAT(result, Equals(leetcode_1409::processQueries(input, m))); - CHECK_THAT(result, Equals(leetcode_1409::processQueries2(input, m))); -} - -TEST_CASE("test case 2 {test_1409}", "{test_1409}") { - const vector input{4, 1, 2, 2}; - static constexpr const auto m{4}; - const vector result{3, 1, 2, 0}; - CHECK_THAT(result, Equals(leetcode_1409::processQueries(input, m))); - CHECK_THAT(result, Equals(leetcode_1409::processQueries2(input, m))); -} - -TEST_CASE("test case 3 {test_1409}", "{test_1409}") { - const vector input{7, 5, 5, 8, 3}; - static constexpr const auto m{8}; - const vector result{6, 5, 0, 7, 5}; - CHECK_THAT(result, Equals(leetcode_1409::processQueries(input, m))); - CHECK_THAT(result, Equals(leetcode_1409::processQueries2(input, m))); -} - -TEST_CASE("test case 4 {test_1409}", "{test_1409}") { - const vector input{8, 7, 4, 2, 8, 1, 7, 7}; - static constexpr const auto m{8}; - const vector result{7, 7, 5, 4, 3, 4, 4, 0}; - CHECK_THAT(result, Equals(leetcode_1409::processQueries(input, m))); - CHECK_THAT(result, Equals(leetcode_1409::processQueries2(input, m))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_1409_TEST_HPP diff --git a/algorithm/associative_container/leetcode_888.cpp b/algorithm/associative_container/leetcode_888.cpp index 93f943ee..e2c73c9a 100644 --- a/algorithm/associative_container/leetcode_888.cpp +++ b/algorithm/associative_container/leetcode_888.cpp @@ -1,33 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_888_test.hpp" +#include +#include +#include +#include #include #include namespace leetcode_888 { using std::unordered_set; using std::accumulate; +using std::vector; +#endif -vector leetcode_888::fairCandySwap(const vector &alice, const vector &tifa) { - const int sum1 = accumulate(alice.begin(), alice.end(), 0); - const int sum2 = accumulate(tifa.begin(), tifa.end(), 0); - assert((sum1 - sum2) % 2 != 1); - const int diff = (sum1 - sum2) / 2; - unordered_set s2; - for (const auto i: tifa) { - s2.insert(i); - } - const auto aliceSize{alice.size()}; - for (size_t i{0}; i < aliceSize; ++i) { - if (s2.count(alice[i] - diff) == 1) { - return {alice[i], alice[i] - diff}; +class Solution { +public: + vector fairCandySwap(const vector &alice, const vector &tifa) { + const int sum1 = accumulate(alice.begin(), alice.end(), 0); + const int sum2 = accumulate(tifa.begin(), tifa.end(), 0); + assert((sum1 - sum2) % 2 != 1); + const int diff = (sum1 - sum2) / 2; + unordered_set s2; + for (const auto i: tifa) { + s2.insert(i); + } + const auto aliceSize{alice.size()}; + for (size_t i{0}; i < aliceSize; ++i) { + if (s2.count(alice[i] - diff) == 1) { + return {alice[i], alice[i] - diff}; + } } + return {}; } - return {}; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_888_test.hpp b/algorithm/associative_container/leetcode_888_test.cpp similarity index 52% rename from algorithm/associative_container/leetcode_888_test.hpp rename to algorithm/associative_container/leetcode_888_test.cpp index 05996fc8..99aad846 100644 --- a/algorithm/associative_container/leetcode_888_test.hpp +++ b/algorithm/associative_container/leetcode_888_test.cpp @@ -1,26 +1,14 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag associative_container //@Tag hashset -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_888_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_888_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_888_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_888_TEST_HPP +#include "leetcode_888.cpp" #include -#include -#include -#include namespace leetcode_888 { -using std::vector; - -struct leetcode_888 { - static vector fairCandySwap(const vector &aliceSizes, const vector &bobSizes); -}; using Catch::Matchers::Equals; @@ -28,28 +16,32 @@ TEST_CASE("test case 1 {test_888}", "{test_888}") { const vector alice{1, 1}; const vector tifa{2, 2}; const vector cloud{1, 2}; - CHECK_THAT(cloud, Equals(leetcode_888::fairCandySwap(alice, tifa))); + Solution solution; + CHECK_THAT(cloud, Equals(solution.fairCandySwap(alice, tifa))); } TEST_CASE("test case 2 {test_888}", "{test_888}") { const vector alice{1, 1}; const vector tifa{2, 3}; const vector cloud{1, 2}; - CHECK_THAT(cloud, Equals(leetcode_888::fairCandySwap(alice, tifa))); + Solution solution; + CHECK_THAT(cloud, Equals(solution.fairCandySwap(alice, tifa))); } TEST_CASE("test case 3 {test_888}", "{test_888}") { const vector alice{2}; const vector tifa{1, 3}; const vector cloud{2, 3}; - CHECK_THAT(cloud, Equals(leetcode_888::fairCandySwap(alice, tifa))); + Solution solution; + CHECK_THAT(cloud, Equals(solution.fairCandySwap(alice, tifa))); } TEST_CASE("test case 4 {test_888}", "{test_888}") { const vector alice{1, 2, 5}; const vector tifa{2, 4}; const vector cloud{5, 4}; - CHECK_THAT(cloud, Equals(leetcode_888::fairCandySwap(alice, tifa))); + Solution solution; + CHECK_THAT(cloud, Equals(solution.fairCandySwap(alice, tifa))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_888_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_888_TEST_HPP diff --git a/algorithm/associative_container/leetcode_890.cpp b/algorithm/associative_container/leetcode_890.cpp index 5d5df382..65aa30cb 100644 --- a/algorithm/associative_container/leetcode_890.cpp +++ b/algorithm/associative_container/leetcode_890.cpp @@ -1,58 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_890_test.hpp" -#include -#include +#include +#include +#include +#include +#include +#include namespace leetcode_890 { -using std::unordered_set; -using std::accumulate; - -bool match(const string &word, const string &pattern) { - const auto word_size{word.size()}; - if (word_size != pattern.size()) { - return false; - } - std::array charCount{0}; - for (const auto ch: pattern) { - charCount[ch - 'a']++; - } - std::array mapToPattern{0}, patternToMap{0}; - - for (size_t i{0}; i < word_size; ++i) { - const auto ch_order = word[i] - 'a'; - const auto pattern_order = pattern[i] - 'a'; - if (mapToPattern[ch_order] == 0 && patternToMap[pattern_order] == 0) { - mapToPattern[ch_order] = pattern_order + 1; - patternToMap[pattern_order] = ch_order + 1; - } - if (mapToPattern[ch_order] == 0) { - return false; - } - charCount[mapToPattern[ch_order] - 1] -= 1; - } - return std::all_of(charCount.cbegin(), charCount.cend(), [](const auto x) { return x == 0; }); -} - +using std::string; +using std::vector; +#endif -vector leetcode_890::findAndReplacePattern(const vector &words, const string &pattern) { - vector will_return{}; - std::array charCount{0}; - for (const auto ch: pattern) { - charCount[ch - 'a']++; - } - const auto pattern_size{pattern.size()}; - const auto match = [charCount, pattern_size](const string &word, const string &pattern) { +class Solution { +public: + bool match(const string &word, const string &pattern) { const auto word_size{word.size()}; - if (word_size != pattern_size) { + if (word_size != pattern.size()) { return false; } - std::array charCountT{charCount}, mapToPattern{0}, patternToMap{0}; + std::array charCount{0}; + for (const auto ch: pattern) { + charCount[ch - 'a']++; + } + std::array mapToPattern{0}, patternToMap{0}; + for (size_t i{0}; i < word_size; ++i) { const auto ch_order = word[i] - 'a'; const auto pattern_order = pattern[i] - 'a'; @@ -63,15 +37,47 @@ vector leetcode_890::findAndReplacePattern(const vector &words, if (mapToPattern[ch_order] == 0) { return false; } - charCountT[mapToPattern[ch_order] - 1] -= 1; + charCount[mapToPattern[ch_order] - 1] -= 1; } - return std::all_of(charCountT.cbegin(), charCountT.cend(), [](const auto x) { return x == 0; }); - }; - for (const auto &word: words) { - if (match(word, pattern)) { - will_return.push_back(word); + return std::all_of(charCount.cbegin(), charCount.cend(), [](const auto x) { return x == 0; }); + } + + vector findAndReplacePattern(const vector &words, const string &pattern) { + vector will_return{}; + std::array charCount{0}; + for (const auto ch: pattern) { + charCount[ch - 'a']++; } + const auto pattern_size{pattern.size()}; + const auto match = [charCount, pattern_size](const string &word, const string &pattern) { + const auto word_size{word.size()}; + if (word_size != pattern_size) { + return false; + } + std::array charCountT{charCount}, mapToPattern{0}, patternToMap{0}; + for (size_t i{0}; i < word_size; ++i) { + const auto ch_order = word[i] - 'a'; + const auto pattern_order = pattern[i] - 'a'; + if (mapToPattern[ch_order] == 0 && patternToMap[pattern_order] == 0) { + mapToPattern[ch_order] = pattern_order + 1; + patternToMap[pattern_order] = ch_order + 1; + } + if (mapToPattern[ch_order] == 0) { + return false; + } + charCountT[mapToPattern[ch_order] - 1] -= 1; + } + return std::all_of(charCountT.cbegin(), charCountT.cend(), [](const auto x) { return x == 0; }); + }; + for (const auto &word: words) { + if (match(word, pattern)) { + will_return.push_back(word); + } + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_890_test.cpp b/algorithm/associative_container/leetcode_890_test.cpp new file mode 100644 index 00000000..e593c76c --- /dev/null +++ b/algorithm/associative_container/leetcode_890_test.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag associative_container +//@Tag array as hashmap +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_890_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_890_TEST_HPP + +#include "leetcode_890.cpp" +#include + +namespace leetcode_890 { + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 {test_890}", "{test_890}") { + static constexpr const std::array input{"abc", "deq", "mee", "aqq", "dkd", "ccc"}; + static constexpr const char *const pattern{"abb"}; + static constexpr const std::array result{"mee", "aqq"}; + Solution solution; + CHECK_THAT( + (vector{result.cbegin(), result.cend()}), + Equals(solution.findAndReplacePattern({input.cbegin(), input.cend()}, pattern)) + ); + +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_890_TEST_HPP diff --git a/algorithm/associative_container/leetcode_890_test.hpp b/algorithm/associative_container/leetcode_890_test.hpp deleted file mode 100644 index 63903132..00000000 --- a/algorithm/associative_container/leetcode_890_test.hpp +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag associative_container -//@Tag array as hashmap -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_890_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_890_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_890 { -using std::vector; - -struct leetcode_890 { - static vector findAndReplacePattern(const vector &words, const string &pattern); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 {test_890}", "{test_890}") { - static constexpr const std::array input{"abc", "deq", "mee", "aqq", "dkd", "ccc"}; - static constexpr const char *const pattern{"abb"}; - static constexpr const std::array result{"mee", "aqq"}; - CHECK_THAT( - (vector{result.cbegin(), result.cend()}), - Equals(leetcode_890::findAndReplacePattern({input.cbegin(), input.cend()}, pattern)) - ); - -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_890_TEST_HPP diff --git a/algorithm/associative_container/leetcode_893.cpp b/algorithm/associative_container/leetcode_893.cpp index 8fc9589a..76ed64ef 100644 --- a/algorithm/associative_container/leetcode_893.cpp +++ b/algorithm/associative_container/leetcode_893.cpp @@ -1,43 +1,53 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_893_test.hpp" +#include +#include +#include +#include #include #include +#include namespace leetcode_893 { using std::array; using std::unordered_set; +using std::vector; +using std::string; +#endif + +class Solution { +public: + int numSpecialEquivGroups(const vector &words) { + struct hasher { + size_t operator()(const std::array &p) const { + size_t i{0}; + for (auto t: p) { + i = 31 * i + std::hash()(t); + } + return i; + } + }; -struct hasher { - size_t operator()(const std::array &p) const { - size_t i{0}; - for (auto t: p) { - i = 31 * i + std::hash()(t); + const auto words_size{words.size()}; + if (words_size == 0) { + return 0; } - return i; + unordered_set, hasher> will_return{}; + const auto word_size{words.front().size()}; + for (size_t i{0}; i < words_size; ++i) { + array charElement{0}; + const auto &word = words[i]; + for (size_t j{0}; j < word_size; ++j) { + charElement[((j % 2) ? 0 : 26) + word[j] - 'a']++; + } + will_return.insert(charElement); + } + return static_cast(will_return.size()); } }; -int32_t leetcode_893::numSpecialEquivGroups(const vector &words) { - const auto words_size{words.size()}; - if (words_size == 0) { - return 0; - } - unordered_set, hasher> will_return{}; - const auto word_size{words.front().size()}; - for (size_t i{0}; i < words_size; ++i) { - array charElement{0}; - const auto &word = words[i]; - for (size_t j{0}; j < word_size; ++j) { - charElement[((j % 2) ? 0 : 26) + word[j] - 'a']++; - } - will_return.insert(charElement); - } - return static_cast(will_return.size()); -} +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_893_test.hpp b/algorithm/associative_container/leetcode_893_test.cpp similarity index 52% rename from algorithm/associative_container/leetcode_893_test.hpp rename to algorithm/associative_container/leetcode_893_test.cpp index 85394a52..073b7279 100644 --- a/algorithm/associative_container/leetcode_893_test.hpp +++ b/algorithm/associative_container/leetcode_893_test.cpp @@ -1,46 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag associative_container //@Tag arrays as hashmap //@Tag 自定义hash函数 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_893_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_893_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_893_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_893_TEST_HPP +#include "leetcode_893.cpp" #include -#include -#include -#include -#include namespace leetcode_893 { -using std::vector; - -struct leetcode_893 { - static int32_t numSpecialEquivGroups(const vector &words); -}; TEST_CASE("test case 1 {test_893}", "{test_893}") { static constexpr const std::array input{"abc", "deq", "mee", "aqq", "dkd", "ccc"}; static constexpr const auto result{6}; - CHECK(result == leetcode_893::numSpecialEquivGroups({input.cbegin(), input.cend()})); + Solution solution; + CHECK(result == solution.numSpecialEquivGroups({input.cbegin(), input.cend()})); } TEST_CASE("test case 2 {test_893}", "{test_893}") { static constexpr const std::array input{"abcd", "cdab", "cbad", "xyzz", "zzxy", "zzyx"}; static constexpr const auto result{3}; - CHECK(result == leetcode_893::numSpecialEquivGroups({input.cbegin(), input.cend()})); + Solution solution; + CHECK(result == solution.numSpecialEquivGroups({input.cbegin(), input.cend()})); } TEST_CASE("test case 3 {test_893}", "{test_893}") { static constexpr const std::array input{"abc", "acb", "bac", "bca", "cab", "cba"}; static constexpr const auto result{3}; - CHECK(result == leetcode_893::numSpecialEquivGroups({input.cbegin(), input.cend()})); + Solution solution; + CHECK(result == solution.numSpecialEquivGroups({input.cbegin(), input.cend()})); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_893_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_893_TEST_HPP diff --git a/algorithm/associative_container/leetcode_914.cpp b/algorithm/associative_container/leetcode_914.cpp index 5d976d9f..1e58bada 100644 --- a/algorithm/associative_container/leetcode_914.cpp +++ b/algorithm/associative_container/leetcode_914.cpp @@ -1,45 +1,53 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_914_test.hpp" +#include +#include +#include #include #include #include +#include namespace leetcode_914 { using std::array; using std::unordered_map; using std::unordered_set; +using std::vector; +#endif -void getPrime(int32_t value, unordered_map &uset) { - for (int32_t begin{2}; begin <= value; ++begin) { - if (value % begin == 0) { - ++uset[begin]; +class Solution { +private: + void getPrime(int32_t value, unordered_map &uset) { + for (int32_t begin{2}; begin <= value; ++begin) { + if (value % begin == 0) { + ++uset[begin]; + } } } -} -bool leetcode_914::hasGroupsSizeX(const vector &deck) { - if (deck.size() < 2) { - return false; - } - int maxv{0}; - unordered_map umap; - for (const auto i: deck) { - umap[i]++; - maxv = std::max(umap[i], maxv); - } - unordered_map umap2; - for (const auto [key, value]: umap) { - getPrime(value, umap2); +public: + bool hasGroupsSizeX(const vector &deck) { + if (deck.size() < 2) { + return false; + } + int maxv{0}; + unordered_map umap; + for (const auto i: deck) { + umap[i]++; + maxv = std::max(umap[i], maxv); + } + unordered_map umap2; + for (const auto [key, value]: umap) { + getPrime(value, umap2); + } + return std::any_of(umap2.cbegin(), umap2.cend(), [&umap](std::pair pai) { + return pai.second == umap.size(); + }); } - return std::any_of(umap2.cbegin(), umap2.cend(), [&umap](std::pair pai) { - return pai.second == umap.size(); - }); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_914_test.cpp b/algorithm/associative_container/leetcode_914_test.cpp new file mode 100644 index 00000000..4c1915ec --- /dev/null +++ b/algorithm/associative_container/leetcode_914_test.cpp @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag associative_container +//@Tag arrays as hashmap +//@Tag 自定义hash函数 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_914_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_914_TEST_HPP + +#include "leetcode_914.cpp" +#include + +namespace leetcode_914 { + +TEST_CASE("test case 1 {test_914}", "{test_914}") { + const vector input{1, 2, 3, 4, 4, 3, 2, 1}; + Solution solution; + CHECK(solution.hasGroupsSizeX(input)); +} + +TEST_CASE("test case 2 {test_914}", "{test_914}") { + const vector input{1, 1, 4, 5, 1, 4, 1, 9, 1, 9, 8, 1, 0}; + Solution solution; + CHECK_FALSE(solution.hasGroupsSizeX(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_914_TEST_HPP diff --git a/algorithm/associative_container/leetcode_914_test.hpp b/algorithm/associative_container/leetcode_914_test.hpp deleted file mode 100644 index 2787e4ad..00000000 --- a/algorithm/associative_container/leetcode_914_test.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag associative_container -//@Tag arrays as hashmap -//@Tag 自定义hash函数 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_914_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_914_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_914 { -using std::vector; - -struct leetcode_914 { - static bool hasGroupsSizeX(const vector &deck); -}; - - -TEST_CASE("test case 1 {test_914}", "{test_914}") { - const vector input{1, 2, 3, 4, 4, 3, 2, 1}; - CHECK(leetcode_914::hasGroupsSizeX(input)); -} - -TEST_CASE("test case 2 {test_914}", "{test_914}") { - const vector input{1, 1, 4, 5, 1, 4, 1, 9, 1, 9, 8, 1, 0}; - CHECK_FALSE(leetcode_914::hasGroupsSizeX(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_914_TEST_HPP diff --git a/algorithm/associative_container/leetcode_929.cpp b/algorithm/associative_container/leetcode_929.cpp index a4a7683b..98ca4103 100644 --- a/algorithm/associative_container/leetcode_929.cpp +++ b/algorithm/associative_container/leetcode_929.cpp @@ -1,50 +1,59 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_929_test.hpp" +#include +#include +#include +#include #include namespace leetcode_929 { using std::unordered_set; +using std::vector; +using std::string; +#endif -string transfer(const string &str) { - string re{}; - const auto str_size{str.size()}; - re.resize(str_size); - for (size_t i{0}, count{0}; i < str_size; ++i) { - switch (str[i]) { - case '.': { - continue; - } - case '+': { - for (; i < str_size && str[i] != '@'; ++i) {} - --i; - break; - } - case '@': { - for (; i < str_size; ++i, ++count) { re[count] = str[i]; } - re.resize(count); - return re; - } - default: { - re[count] = str[i]; - ++count; +class Solution { +private: + string transfer(const string &str) { + string re{}; + const auto str_size{str.size()}; + re.resize(str_size); + for (size_t i{0}, count{0}; i < str_size; ++i) { + switch (str[i]) { + case '.': { + continue; + } + case '+': { + for (; i < str_size && str[i] != '@'; ++i) {} + --i; + break; + } + case '@': { + for (; i < str_size; ++i, ++count) { re[count] = str[i]; } + re.resize(count); + return re; + } + default: { + re[count] = str[i]; + ++count; + } } } + return ""; } - return ""; -} -int32_t leetcode_929::numUniqueEmails(const vector &emails) { - unordered_set uset; - for (const auto &email: emails) { - uset.insert(transfer(email)); +public: + int32_t numUniqueEmails(const vector &emails) { + unordered_set uset; + for (const auto &email: emails) { + uset.insert(transfer(email)); + } + return uset.size(); } - return uset.size(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_929_test.hpp b/algorithm/associative_container/leetcode_929_test.cpp similarity index 51% rename from algorithm/associative_container/leetcode_929_test.hpp rename to algorithm/associative_container/leetcode_929_test.cpp index 42a1b10c..ba26f438 100644 --- a/algorithm/associative_container/leetcode_929_test.hpp +++ b/algorithm/associative_container/leetcode_929_test.cpp @@ -1,38 +1,23 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag associative_container //@Tag arrays as hashmap //@Tag 自定义hash函数 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_929_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_929_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_929_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_929_TEST_HPP +#include "leetcode_929.cpp" #include -#include -#include -#include -#include namespace leetcode_929 { -using std::array; -using std::vector; - -struct leetcode_929 { - static int32_t numUniqueEmails(const vector &emails); -}; - - TEST_CASE("test case 1 {test_929}", "{test_929}") { static constexpr const std::array arr{ "114.51419+1981@0893.996", "114.5.1419+251.666@0893.996", "11451419+8888@08.93.996" }; static constexpr const auto result{2}; - CHECK(result == leetcode_929::numUniqueEmails({arr.begin(), arr.end()})); + Solution solution; + CHECK(result == solution.numUniqueEmails({arr.begin(), arr.end()})); } TEST_CASE("test case 2 {test_929}", "{test_929}") { @@ -40,7 +25,8 @@ TEST_CASE("test case 2 {test_929}", "{test_929}") { "9@0hello.world", "5@hello.world", "4@hello.world" }; static constexpr const auto result{3}; - CHECK(result == leetcode_929::numUniqueEmails({arr.begin(), arr.end()})); + Solution solution; + CHECK(result == solution.numUniqueEmails({arr.begin(), arr.end()})); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_929_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_929_TEST_HPP diff --git a/algorithm/associative_container/leetcode_961.cpp b/algorithm/associative_container/leetcode_961.cpp index 3e61d10e..f13a5708 100644 --- a/algorithm/associative_container/leetcode_961.cpp +++ b/algorithm/associative_container/leetcode_961.cpp @@ -1,26 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_961_test.hpp" +#include +#include +#include #include namespace leetcode_961 { using std::unordered_set; +using std::vector; +#endif -int32_t leetcode_961::repeatedNTimes(const vector &nums) { - unordered_set uset{}; - for (const auto num: nums) { - if (uset.count(num) != 0) { - return num; - } else { - uset.insert(num); +class Solution { +public: + int repeatedNTimes(const vector &nums) { + unordered_set uset{}; + for (const auto num: nums) { + if (uset.count(num) != 0) { + return num; + } else { + uset.insert(num); + } } + return -1; } - return -1; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/associative_container/leetcode_961_test.cpp b/algorithm/associative_container/leetcode_961_test.cpp new file mode 100644 index 00000000..2e2b9bed --- /dev/null +++ b/algorithm/associative_container/leetcode_961_test.cpp @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag associative_container +//@Tag xor +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_961_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_961_TEST_HPP + +#include "leetcode_961.cpp" +#include + +namespace leetcode_961 { + +TEST_CASE("test case 1 {test_961}", "{test_961}") { + static constexpr const std::array arr{ + 1, 2, 3, 3 + }; + static constexpr const auto result{3}; + Solution solution; + CHECK(result == solution.repeatedNTimes({arr.cbegin(), arr.cend()})); +} + +TEST_CASE("test case 2 {test_961}", "{test_961}") { + static constexpr const std::array arr{ + 1, 0, 4, 4, 4, 4, 4, 5, 1, 4 + }; + static constexpr const auto result{4}; + Solution solution; + CHECK(result == solution.repeatedNTimes({arr.cbegin(), arr.cend()})); +} + +TEST_CASE("test case 3 {test_961}", "{test_961}") { + static constexpr const std::array arr{ + 1, 9, 2, 9, 8, 9, 3, 9, 0, 9 + }; + static constexpr const auto result{9}; + Solution solution; + CHECK(result == solution.repeatedNTimes({arr.cbegin(), arr.cend()})); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_961_TEST_HPP diff --git a/algorithm/associative_container/leetcode_961_test.hpp b/algorithm/associative_container/leetcode_961_test.hpp deleted file mode 100644 index 966b8c93..00000000 --- a/algorithm/associative_container/leetcode_961_test.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag associative_container -//@Tag xor -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_961_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_961_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_961 { -using std::array; -using std::vector; - -struct leetcode_961 { - static int32_t repeatedNTimes(const vector &nums); -}; - -TEST_CASE("test case 1 {test_961}", "{test_961}") { - static constexpr const std::array arr{ - 1, 2, 3, 3 - }; - static constexpr const auto result{3}; - CHECK(result == leetcode_961::repeatedNTimes({arr.cbegin(), arr.cend()})); -} - -TEST_CASE("test case 2 {test_961}", "{test_961}") { - static constexpr const std::array arr{ - 1, 0, 4, 4, 4, 4, 4, 5, 1, 4 - }; - static constexpr const auto result{4}; - CHECK(result == leetcode_961::repeatedNTimes({arr.cbegin(), arr.cend()})); -} - -TEST_CASE("test case 3 {test_961}", "{test_961}") { - static constexpr const std::array arr{ - 1, 9, 2, 9, 8, 9, 3, 9, 0, 9 - }; - static constexpr const auto result{9}; - CHECK(result == leetcode_961::repeatedNTimes({arr.cbegin(), arr.cend()})); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ASSOCIATIVE_CONTAINER_LEETCODE_961_TEST_HPP diff --git a/algorithm/binary_search/CMakeLists.txt b/algorithm/binary_search/CMakeLists.txt index a9f7bbb8..14ae4c93 100644 --- a/algorithm/binary_search/CMakeLists.txt +++ b/algorithm/binary_search/CMakeLists.txt @@ -4,12 +4,12 @@ project(${PROJECT_NAME}_binary_search LANGUAGES CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") -add_library(${PROJECT_NAME}_basic ${LIB_WAY} ${CMAKE_CURRENT_SOURCE_DIR}/basic.cpp +add_library(${PROJECT_NAME}_basic_src ${LIB_WAY} ${CMAKE_CURRENT_SOURCE_DIR}/basic.cpp ${CMAKE_CURRENT_SOURCE_DIR}/include/basic.hpp) -target_include_directories(${PROJECT_NAME}_basic PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) +target_include_directories(${PROJECT_NAME}_basic_src PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) enable_testing() -set(dependencies basic_test triple_search rotate_array) +set(dependencies basic triple_search rotate_array) set(leetcode_order 35 4 33 162 34) LIST(APPEND leetcode_order 69 81 153_154 so_53ii) @@ -22,12 +22,12 @@ unset(leetcode_order) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE CS203_DSAA_TEST_MACRO) + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) target_link_libraries(${PROJECT_NAME}_${elementName} PRIVATE - CS203_DSAA_template_INCLUDE - ${PROJECT_NAME}_basic) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + algorithm_template_INCLUDE + ${PROJECT_NAME}_basic_src) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) endforeach () unset(dependencies) diff --git a/algorithm/binary_search/basic.cpp b/algorithm/binary_search/basic.cpp index c7fea847..cf048fe6 100644 --- a/algorithm/binary_search/basic.cpp +++ b/algorithm/binary_search/basic.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include "basic.hpp" diff --git a/algorithm/binary_search/basic_test.cpp b/algorithm/binary_search/basic_test.cpp index b9f2c714..06098467 100644 --- a/algorithm/binary_search/basic_test.cpp +++ b/algorithm/binary_search/basic_test.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include "basic.cpp" diff --git a/algorithm/binary_search/include/basic.hpp b/algorithm/binary_search/include/basic.hpp index fd23a35c..0637a3a1 100644 --- a/algorithm/binary_search/include/basic.hpp +++ b/algorithm/binary_search/include/basic.hpp @@ -1,13 +1,8 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_BASIC_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_BASIC_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_BASIC_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_BASIC_HPP #include #include @@ -40,4 +35,4 @@ num_t upper_bound_warpper(cVecRef nums, num_t first, num_t last, num_t value); num_t binary_search_pos(cVecRef vec, int32_t target, int32_t begin, int32_t end); } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_BASIC_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_BASIC_HPP diff --git a/algorithm/binary_search/leetcode_1237.cpp b/algorithm/binary_search/leetcode_1237.cpp index de56ef98..1c1faeac 100644 --- a/algorithm/binary_search/leetcode_1237.cpp +++ b/algorithm/binary_search/leetcode_1237.cpp @@ -1,90 +1,100 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanos - -*/ -#include "leetcode_1237_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include "basic.hpp" #include +#include +#include namespace leetcode_1237 { -int32_t getXMin(const CustomFunction &customfunction, int32_t z) { - // fst step, find the minimum x - // 如果f(1,1)就已经大于z了,就不需要进行了,直接退出 - // 如果(50,1000)等于z, 说明(49,1000)小于z, 需要从50开始 - // 如果(50,1000)大于z, 说明(49,1000)小于z, 需要从50开始 - // 如果(50,1000)大于z, 说明(49,1000)等于z, 需要从49开始 - const auto y{1000}; - for (int32_t x_left{1}, x_right{1000}; x_left < x_right;) { - const auto mid = (x_right - x_left) / 2 + x_left; - const auto value{customfunction(mid, y)}; - if (value == z) { - return mid; - } else if (value > z) { - const auto midM1{mid - 1}; - const auto valueM1{customfunction(midM1, y)}; - if (valueM1 < z) { +using CustomFunction = std::function; +using std::vector; +#endif + + +class Solution { +private: + int32_t getXMin(const CustomFunction &customfunction, int32_t z) { + // fst step, find the minimum x + // 如果f(1,1)就已经大于z了,就不需要进行了,直接退出 + // 如果(50,1000)等于z, 说明(49,1000)小于z, 需要从50开始 + // 如果(50,1000)大于z, 说明(49,1000)小于z, 需要从50开始 + // 如果(50,1000)大于z, 说明(49,1000)等于z, 需要从49开始 + const auto y{1000}; + for (int32_t x_left{1}, x_right{1000}; x_left < x_right;) { + const auto mid = (x_right - x_left) / 2 + x_left; + const auto value{customfunction(mid, y)}; + if (value == z) { return mid; + } else if (value > z) { + const auto midM1{mid - 1}; + const auto valueM1{customfunction(midM1, y)}; + if (valueM1 < z) { + return mid; + } + x_right = mid; + } else { + x_left = mid + 1; } - x_right = mid; - } else { - x_left = mid + 1; } + return 1; } - return 1; -} -int32_t getXMax(const CustomFunction &customfunction, int32_t z) { - // fst step, find the minimum x - // 如果f(1,1)就已经大于z了,就不需要进行了,直接退出 - // 如果(50,1)等于z, 说明(51,1)大于z, 截止到50 - // 如果(50,1)小于z, 说明(51,1)大于z, 截止到50 - const auto y{1}; - for (int32_t x_left{1}, x_right{1000}; x_left < x_right;) { - const auto mid = (x_right - x_left) / 2 + x_left; - const auto value{customfunction(mid, y)}; - if (value == z) { - return mid; - } else if (value < z) { - const auto midP1 = mid + 1; - const auto valueP1{customfunction(midP1, y)}; - if (valueP1 > z) { + int32_t getXMax(const CustomFunction &customfunction, int32_t z) { + // fst step, find the minimum x + // 如果f(1,1)就已经大于z了,就不需要进行了,直接退出 + // 如果(50,1)等于z, 说明(51,1)大于z, 截止到50 + // 如果(50,1)小于z, 说明(51,1)大于z, 截止到50 + const auto y{1}; + for (int32_t x_left{1}, x_right{1000}; x_left < x_right;) { + const auto mid = (x_right - x_left) / 2 + x_left; + const auto value{customfunction(mid, y)}; + if (value == z) { return mid; + } else if (value < z) { + const auto midP1 = mid + 1; + const auto valueP1{customfunction(midP1, y)}; + if (valueP1 > z) { + return mid; + } + x_left = mid + 1; + } else { + x_right = mid; } - x_left = mid + 1; - } else { - x_right = mid; } + return 1000; } - return 1000; -} -vector> leetcode_1237::findSolution(const CustomFunction &customfunction, int32_t z) { - vector> will_return{}; - if (customfunction(1, 1) > z) { - return will_return; - } // O(1)守门 - const auto xmin{getXMin(customfunction, z)}; // log(n) - const auto xmax{getXMax(customfunction, z)}; // log(n) - for (int32_t i{xmin}, y_righest{1000}; i <= xmax; ++i) { // log(n) for each step - // f(x1,y1) == z - // then, for f(x1+1,y2) == z, y2 z) { - y_right = mid; - } else if (value == z) { - will_return.emplace_back(vector{i, mid}); - y_righest = y_right; - break; - } else { - y_left = mid + 1; +public: + vector> findSolution(const CustomFunction &customfunction, int32_t z) { + vector> will_return{}; + if (customfunction(1, 1) > z) { + return will_return; + } // O(1)守门 + const auto xmin{getXMin(customfunction, z)}; // log(n) + const auto xmax{getXMax(customfunction, z)}; // log(n) + for (int32_t i{xmin}, y_righest{1000}; i <= xmax; ++i) { // log(n) for each step + // f(x1,y1) == z + // then, for f(x1+1,y2) == z, y2 z) { + y_right = mid; + } else if (value == z) { + will_return.emplace_back(vector{i, mid}); + y_righest = y_right; + break; + } else { + y_left = mid + 1; + } } } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_1237_test.hpp b/algorithm/binary_search/leetcode_1237_test.cpp similarity index 65% rename from algorithm/binary_search/leetcode_1237_test.hpp rename to algorithm/binary_search/leetcode_1237_test.cpp index 26814fe5..cdd7d3f7 100644 --- a/algorithm/binary_search/leetcode_1237_test.hpp +++ b/algorithm/binary_search/leetcode_1237_test.cpp @@ -1,34 +1,20 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanos - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag binary search //@Tag 二分 //@Tag 多重二分 //@Level Mid -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1237_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1237_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1237_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1237_TEST_HPP +#include "leetcode_1237.cpp" #include -#include -#include -#include namespace leetcode_1237 { using std::vector; - - using CustomFunction = std::function; - -namespace leetcode_1237 { -vector> findSolution(const CustomFunction &customfunction, int32_t z); -} - using Catch::Matchers::Equals; TEST_CASE("1 [test_1237]", "[test_1237]") { @@ -36,7 +22,8 @@ TEST_CASE("1 [test_1237]", "[test_1237]") { return x + y; }; static constexpr const auto z{5}; - const auto result = leetcode_1237::findSolution(func, z); + Solution solution; + const auto result = solution.findSolution(func, z); const vector> output{{1, 4}, {2, 3}, {3, 2}, @@ -49,7 +36,8 @@ TEST_CASE("2 [test_1237]", "[test_1237]") { return x * y; }; static constexpr const auto z{5}; - const auto result = leetcode_1237::findSolution(func, z); + Solution solution; + const auto result = solution.findSolution(func, z); const vector> output{{1, 5}, // it's not the age of traditional addition {5, 1}}; CHECK_THAT(output, Equals(result)); @@ -57,4 +45,4 @@ TEST_CASE("2 [test_1237]", "[test_1237]") { } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1237_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1237_TEST_HPP diff --git a/algorithm/binary_search/leetcode_153_154.cpp b/algorithm/binary_search/leetcode_153_154.cpp index a9287624..2ed03fe6 100644 --- a/algorithm/binary_search/leetcode_153_154.cpp +++ b/algorithm/binary_search/leetcode_153_154.cpp @@ -1,36 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +namespace leetcode_154 { +using std::vector; -*/ -#include "leetcode_153_154_test.hpp" +#endif -namespace leetcode_154 { -int32_t leetcode_154::findMin(const vector &nums) { - size_t begin{0}, middle{0}; - size_t end{nums.size() - 1}; - while (begin < end) { - middle = (end - begin) / 2 + begin; - if (nums[middle] > nums[end]) { - begin = middle + 1; - } else if (nums[middle] < nums[end]) { - end = middle; - } else { - end--; +class Solution { +public: + int32_t findMin(const vector &nums) { + size_t begin{0}, middle{0}; + size_t end{nums.size() - 1}; + while (begin < end) { + middle = (end - begin) / 2 + begin; + if (nums[middle] > nums[end]) { + begin = middle + 1; + } else if (nums[middle] < nums[end]) { + end = middle; + } else { + end--; + } } + return nums[begin]; } - return nums[begin]; -} -} - -namespace leetcode_153 { -using leetcode_154::leetcode_154; +}; -int32_t leetcode_153::findMin(const vector &nums) { - return leetcode_154::findMin(nums); -} +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_153_154_test.cpp b/algorithm/binary_search/leetcode_153_154_test.cpp new file mode 100644 index 00000000..ca327cdb --- /dev/null +++ b/algorithm/binary_search/leetcode_153_154_test.cpp @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag binary search +//@Tag 二分 +//@Level Mid +//@Sword-Offer 11 +//@Plan 剑指OfferII-I Day05 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_153_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_153_TEST_HPP + +#include "leetcode_153_154.cpp" +#include + +namespace leetcode_153 { +using std::vector; +using leetcode_154::Solution; + +TEST_CASE("1 [test_153]", "[test_153]") { + const vector input{3, 4, 5, 1, 2}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.findMin(input)); +} + +TEST_CASE("2 [test_153]", "[test_153]") { + const vector input{4, 5, 6, 7, 0, 1, 2}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.findMin(input)); +} + +TEST_CASE("3 [test_153]", "[test_153]") { + const vector input{11, 13, 15, 17}; + static constexpr const auto result{11}; + Solution solution; + CHECK(result == solution.findMin(input)); +} + +TEST_CASE("test case 4 [test_153]", "[test_153]") { + const vector input{1, 2, 5}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.findMin(input)); +} + +TEST_CASE("test case 5 [test_153]", "[test_153]") { + const vector input{2, 114, 514, 0, 1}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.findMin(input)); +} +} + +namespace leetcode_154 { +using std::vector; + +TEST_CASE("test case 2 [test_154]", "[test_154]") { + const vector input{2, 2, 2, 0, 1}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.findMin(input)); +} +} + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_153_TEST_HPP diff --git a/algorithm/binary_search/leetcode_153_154_test.hpp b/algorithm/binary_search/leetcode_153_154_test.hpp deleted file mode 100644 index efbebaaf..00000000 --- a/algorithm/binary_search/leetcode_153_154_test.hpp +++ /dev/null @@ -1,84 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag array -//@Tag 数组 -//@Tag binary search -//@Tag 二分 -//@Level Mid -//@Sword-Offer 11 -//@Plan 剑指OfferII-I Day05 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_153_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_153_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_153 { -using std::vector; - -struct leetcode_153 final { - static int32_t findMin(const vector &nums); -}; -} -namespace leetcode_154 { -using std::vector; - -struct leetcode_154 final { - static int32_t findMin(const vector &nums); -}; - -TEST_CASE("test case 2 [test_154]", "[test_154]") { - const vector input{2, 2, 2, 0, 1}; - static constexpr const auto result{0}; - CHECK(result == leetcode_154::findMin(input)); -} -} -namespace leetcode_153_154 { -using std::vector; -using leetcode_153::leetcode_153; -using leetcode_154::leetcode_154; - -TEST_CASE("1 [test_153]", "[test_153]") { - const vector input{3, 4, 5, 1, 2}; - static constexpr const auto result{1}; - CHECK(result == leetcode_153::findMin(input)); - CHECK(result == leetcode_154::findMin(input)); -} - -TEST_CASE("2 [test_153]", "[test_153]") { - const vector input{4, 5, 6, 7, 0, 1, 2}; - static constexpr const auto result{0}; - CHECK(result == leetcode_153::findMin(input)); - CHECK(result == leetcode_154::findMin(input)); -} - -TEST_CASE("3 [test_153]", "[test_153]") { - const vector input{11, 13, 15, 17}; - static constexpr const auto result{11}; - CHECK(result == leetcode_153::findMin(input)); - CHECK(result == leetcode_154::findMin(input)); -} - - -TEST_CASE("test case 4 [test_153]", "[test_153]") { - const vector input{1, 2, 5}; - static constexpr const auto result{1}; - CHECK(result == leetcode_153::findMin(input)); - CHECK(result == leetcode_154::findMin(input)); -} - -TEST_CASE("test case 5 [test_153]", "[test_153]") { - const vector input{2, 114, 514, 0, 1}; - static constexpr const auto result{0}; - CHECK(result == leetcode_153::findMin(input)); - CHECK(result == leetcode_154::findMin(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_153_TEST_HPP diff --git a/algorithm/binary_search/leetcode_1608.cpp b/algorithm/binary_search/leetcode_1608.cpp index 51223be5..bdeedc0c 100644 --- a/algorithm/binary_search/leetcode_1608.cpp +++ b/algorithm/binary_search/leetcode_1608.cpp @@ -1,40 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_1608_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include +#include namespace leetcode_1608 { +using std::vector; + +#endif + -int leetcode_1608::specialArray(const vector &nums_) { - vector nums{nums_}; - std::sort(nums.begin(), nums.end()); - const auto nums_size{nums.size()}; - int32_t left{0}, right = std::min(static_cast(nums_size), nums.back()); - while (left < right) { +class Solution { +public: + int32_t specialArray(const vector &nums_) { + vector nums{nums_}; + std::sort(nums.begin(), nums.end()); + const auto nums_size{nums.size()}; + int32_t left{0}, right = std::min(static_cast(nums_size), nums.back()); + while (left < right) { + const auto mid = (right - left) / 2 + left; + const auto num = std::lower_bound(nums.begin(), nums.end(), mid); + const auto diff = std::distance(num,nums.end()); + if (diff > mid) { + left = mid + 1; + } else if (diff < mid) { + right = mid; + } else { + return mid; + } + } const auto mid = (right - left) / 2 + left; const auto num = std::lower_bound(nums.begin(), nums.end(), mid); const auto diff = std::distance(num,nums.end()); - if (diff > mid) { - left = mid + 1; - } else if (diff < mid) { - right = mid; - } else { + if (diff == mid) { return mid; } + // ps, the last step is better for + return -1; } - const auto mid = (right - left) / 2 + left; - const auto num = std::lower_bound(nums.begin(), nums.end(), mid); - const auto diff = std::distance(num,nums.end()); - if (diff == mid) { - return mid; - } - // ps, the last step is better for - return -1; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_1608_test.cpp b/algorithm/binary_search/leetcode_1608_test.cpp new file mode 100644 index 00000000..a15f559a --- /dev/null +++ b/algorithm/binary_search/leetcode_1608_test.cpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag binary search +//@Tag 二分 +//@Level Mid +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1608_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1608_TEST_HPP + +#include "leetcode_1608.cpp" +#include + +namespace leetcode_1608 { +using std::vector; + +TEST_CASE("1 [test_1608]", "[test_1608]") { + const vector nums{3, 5}; + constexpr const auto result{2}; + Solution solution; + CHECK(result == solution.specialArray(nums)); +} + +TEST_CASE("2 [test_1608]", "[test_1608]") { + const vector nums{0, 4, 3, 4, 0}; + constexpr const auto result{3}; + Solution solution; + CHECK(result == solution.specialArray(nums)); +} + +TEST_CASE("3 [test_1608]", "[test_1608]") { + const vector nums{3, 6, 7, 7, 0}; + constexpr const auto result{-1}; + Solution solution; + CHECK(result == solution.specialArray(nums)); +} +} + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1608_TEST_HPP diff --git a/algorithm/binary_search/leetcode_1608_test.hpp b/algorithm/binary_search/leetcode_1608_test.hpp deleted file mode 100644 index 9cdb5a76..00000000 --- a/algorithm/binary_search/leetcode_1608_test.hpp +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag array -//@Tag 数组 -//@Tag binary search -//@Tag 二分 -//@Level Mid -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1608_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1608_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_1608 { -using std::vector; - -namespace leetcode_1608 { -int specialArray(const vector &nums); -} - -using Catch::Matchers::Contains; - -TEST_CASE("1 [test_1608]", "[test_1608]") { - const vector nums{3, 5}; - constexpr const auto result{2}; - CHECK(result == leetcode_1608::specialArray(nums)); -} - -TEST_CASE("2 [test_1608]", "[test_1608]") { - const vector nums{0, 4, 3, 4, 0}; - constexpr const auto result{3}; - CHECK(result == leetcode_1608::specialArray(nums)); -} - -TEST_CASE("3 [test_1608]", "[test_1608]") { - const vector nums{3, 6, 7, 7, 0}; - constexpr const auto result{-1}; - CHECK(result == leetcode_1608::specialArray(nums)); -} -} - -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1608_TEST_HPP diff --git a/algorithm/binary_search/leetcode_162.cpp b/algorithm/binary_search/leetcode_162.cpp index 3766adc4..5bbd29dd 100644 --- a/algorithm/binary_search/leetcode_162.cpp +++ b/algorithm/binary_search/leetcode_162.cpp @@ -1,80 +1,87 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +namespace leetcode_162 { +using std::vector; -*/ -#include "leetcode_162_test.hpp" +#endif -namespace leetcode_162 { -int leetcode_162::findPeakElement(const vector &nums) { - const auto nums_size = nums.size(); - if (nums_size == 1 || nums.front() > nums[1]) { - return 0; - } - if (nums[nums_size - 2] < nums.back()) { - return static_cast(nums_size - 1); - } - size_t left{0}, step{[nums_size] { - size_t step{1}; - while (step < nums_size) { - step *= 2; +class Solution { +public: + int32_t findPeakElement(const vector &nums) { + const auto nums_size = nums.size(); + if (nums_size == 1 || nums.front() > nums[1]) { + return 0; } - return step / 2; - }()}; - const auto judge = [nums, nums_size](size_t order) { - if (order == 0 || order == nums_size - 1) { - return -1; + if (nums[nums_size - 2] < nums.back()) { + return static_cast(nums_size - 1); } - return (nums[order] > nums[order - 1] && nums[order] > nums[order + 1]) ? static_cast(order) - : -1; - }; - while (left < nums_size && step > 0) { - if (judge(left) != -1) { - return static_cast(left); + size_t left{0}, step{[nums_size] { + size_t step{1}; + while (step < nums_size) { + step *= 2; + } + return step / 2; + }()}; + const auto judge = [nums, nums_size](size_t order) { + if (order == 0 || order == nums_size - 1) { + return -1; + } + return (nums[order] > nums[order - 1] && nums[order] > nums[order + 1]) ? static_cast(order) + : -1; + }; + while (left < nums_size && step > 0) { + if (judge(left) != -1) { + return static_cast(left); + } + if (left + step >= 1 && left + step < nums_size && nums[left + step - 1] < nums[left + step] + && left + step + 1 < nums_size && nums[left + step] < nums[left + step + 1]) { + left += step; + } else { + step /= 2; + }// 核心思想,找一个最后一个处于 "上升状态" 的节点 } - if (left + step >= 1 && left + step < nums_size && nums[left + step - 1] < nums[left + step] - && left + step + 1 < nums_size && nums[left + step] < nums[left + step + 1]) { - left += step; - } else { - step /= 2; - }// 核心思想,找一个最后一个处于 "上升状态" 的节点 + return static_cast(left) + 1; } - return static_cast(left) + 1; -} -int32_t leetcode_162::findPeakElement2(const vector &nums) { - constexpr const static auto nege1{static_cast(-1)}; - const auto nums_size = nums.size(); - if (nums_size == 1) { - return 0; - } - if (nums.front() > nums[1]) { - return 0; - } - if (nums[nums_size - 2] < nums.back()) { - return static_cast(nums_size - 1); - } - size_t left{0}, right{nums_size - 1}, mid; - const auto judge = [nums, nums_size](size_t order) { - if (order == 0 || order == nums_size - 1) { - return nege1; + int32_t findPeakElement2(const vector &nums) { + constexpr const static auto nege1{static_cast(-1)}; + const auto nums_size = nums.size(); + if (nums_size == 1) { + return 0; } - return (nums[order] > nums[order - 1] && nums[order] > nums[order + 1]) ? static_cast(order) - : nege1; - }; - while (left < right) { - if (mid = (right - left) / 2 + left;judge(mid) != -1) { - return judge(mid); - } else if (nums[mid] < nums[mid + 1]) { - left = mid + 1; - } else { - right = mid; + if (nums.front() > nums[1]) { + return 0; } - } // 核心思想,先排除边界条件 - // 之后 寻找第一个 - return static_cast(left); -} + if (nums[nums_size - 2] < nums.back()) { + return static_cast(nums_size - 1); + } + size_t left{0}, right{nums_size - 1}, mid; + const auto judge = [nums, nums_size](size_t order) { + if (order == 0 || order == nums_size - 1) { + return nege1; + } + return (nums[order] > nums[order - 1] && nums[order] > nums[order + 1]) ? static_cast(order) + : nege1; + }; + while (left < right) { + if (mid = (right - left) / 2 + left;judge(mid) != -1) { + return judge(mid); + } else if (nums[mid] < nums[mid + 1]) { + left = mid + 1; + } else { + right = mid; + } + } // 核心思想,先排除边界条件 + // 之后 寻找第一个 + return static_cast(left); + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_162_test.hpp b/algorithm/binary_search/leetcode_162_test.cpp similarity index 52% rename from algorithm/binary_search/leetcode_162_test.hpp rename to algorithm/binary_search/leetcode_162_test.cpp index a24b3d95..a7e28bf9 100644 --- a/algorithm/binary_search/leetcode_162_test.hpp +++ b/algorithm/binary_search/leetcode_162_test.cpp @@ -1,46 +1,34 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag binary search //@Tag 二分 //@Level Mid -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_162_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_162_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_162_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_162_TEST_HPP +#include "leetcode_162.cpp" #include -#include -#include -#include namespace leetcode_162 { using std::vector; - -struct leetcode_162 { - static int32_t findPeakElement(const vector &nums); - - static int32_t findPeakElement2(const vector &nums); -}; - using Catch::Matchers::Contains; TEST_CASE("1 [test_162]", "[test_162]") { const vector nums{1, 2, 3, 1}; static constexpr const auto result{2}; - CHECK(result == leetcode_162::findPeakElement2(nums)); - CHECK(result == leetcode_162::findPeakElement(nums)); + Solution solution; + CHECK(result == solution.findPeakElement2(nums)); + CHECK(result == solution.findPeakElement(nums)); } TEST_CASE("2 [test_162]", "[test_162]") { const vector nums{1, 2, 1, 3, 5, 6, 4}; const vector resultList{1, 5}; - const auto v = leetcode_162::findPeakElement(nums); - const auto v2 = leetcode_162::findPeakElement2(nums); + Solution solution; + const auto v = solution.findPeakElement(nums); + const auto v2 = solution.findPeakElement2(nums); CHECK_THAT(resultList, Contains(vector{v})); CHECK_THAT(resultList, Contains(vector{v2})); } @@ -48,18 +36,20 @@ TEST_CASE("2 [test_162]", "[test_162]") { TEST_CASE("3 [test_162]", "[test_162]") { const vector nums{1, 2, 3, 4, 3}; static constexpr const auto result{3}; - CHECK(result == leetcode_162::findPeakElement(nums)); - CHECK(result == leetcode_162::findPeakElement2(nums)); + Solution solution; + CHECK(result == solution.findPeakElement(nums)); + CHECK(result == solution.findPeakElement2(nums)); } TEST_CASE("4 [test_162]", "[test_162]") { const vector nums{1, 2, 1, 3, 5, 6, 4}; const vector resultList{1, 5}; - const auto v = leetcode_162::findPeakElement(nums); - const auto v2 = leetcode_162::findPeakElement2(nums); + Solution solution; + const auto v = solution.findPeakElement(nums); + const auto v2 = solution.findPeakElement2(nums); CHECK_THAT(resultList, Contains(vector{v})); CHECK_THAT(resultList, Contains(vector{v2})); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_162_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_162_TEST_HPP diff --git a/algorithm/binary_search/leetcode_1760.cpp b/algorithm/binary_search/leetcode_1760.cpp index ebdbf661..a889998d 100644 --- a/algorithm/binary_search/leetcode_1760.cpp +++ b/algorithm/binary_search/leetcode_1760.cpp @@ -1,41 +1,49 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_1760_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include +#include +#include namespace leetcode_1760 { -// 开销是数组内的最大值,因此要最小化数组的最大值 -// 因此将1作为最小值,数组内最大值作为最大值, 进行二分 -// 每次二分进行一次判别,返回操作次数 -int32_t judgement(const vector &nums, int32_t value) { - int32_t operations{0}; - for (const auto num: nums) { - const auto[q, r] = std::div(num, value); - if (r != 0) { //剩下就得多分割一次 - operations++; +#endif + +using std::vector; + +class Solution { +private: + // 开销是数组内的最大值,因此要最小化数组的最大值 + // 因此将1作为最小值,数组内最大值作为最大值, 进行二分 + // 每次二分进行一次判别,返回操作次数 + int32_t judgement(const vector &nums, int32_t value) { + int32_t operations{0}; + for (const auto num: nums) { + const auto [q, r] = std::div(num, value); + if (r != 0) { //剩下就得多分割一次 + operations++; + } + operations += (q - 1); // 本来自己是有的,需要划去 } - operations += (q - 1); // 本来自己是有的,需要划去 + return operations; } - return operations; -} -int32_t leetcode_1760::minimumSize(const vector &nums, int32_t maxOperations) { - int32_t minValue{1}; - for (int32_t maxValue{*std::max_element(nums.cbegin(), nums.cend())}; minValue < maxValue;) { - const auto mid = (maxValue - minValue) / 2 + minValue; - const auto result = judgement(nums, mid); - if (result > maxOperations) { - minValue = mid + 1; - } else if (result <= maxOperations) { - maxValue = mid; +public: + int32_t minimumSize(const vector &nums, int32_t maxOperations) { + int32_t minValue{1}; + for (int32_t maxValue{*std::max_element(nums.cbegin(), nums.cend())}; minValue < maxValue;) { + const auto mid = (maxValue - minValue) / 2 + minValue; + const auto result = judgement(nums, mid); + if (result > maxOperations) { + minValue = mid + 1; + } else if (result <= maxOperations) { + maxValue = mid; + } } + return minValue; // should not reach } - return minValue; // should not reach -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_1760_test.cpp b/algorithm/binary_search/leetcode_1760_test.cpp new file mode 100644 index 00000000..7c6711af --- /dev/null +++ b/algorithm/binary_search/leetcode_1760_test.cpp @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag binary search +//@Tag 二分 +//@Level Mid +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1760_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1760_TEST_HPP + +#include "leetcode_1760.cpp" +#include + +namespace leetcode_1760 { +using std::vector; + +TEST_CASE("1 [test_1760]", "[test_1760]") { + const vector nums{9}; + constexpr const auto operations{3}; + constexpr const auto minResult{3}; + Solution solution; + CHECK(minResult == solution.minimumSize(nums, operations)); +} + + +TEST_CASE("2 [test_1760]", "[test_1760]") { + const vector nums{2, 2, 4, 8}; + constexpr const auto operations{4}; + constexpr const auto minResult{2}; + Solution solution; + CHECK(minResult == solution.minimumSize(nums, operations)); +} +} + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1760_TEST_HPP diff --git a/algorithm/binary_search/leetcode_1760_test.hpp b/algorithm/binary_search/leetcode_1760_test.hpp deleted file mode 100644 index 4440f771..00000000 --- a/algorithm/binary_search/leetcode_1760_test.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag array -//@Tag 数组 -//@Tag binary search -//@Tag 二分 -//@Level Mid -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1760_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1760_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_1760 { -using std::vector; - -namespace leetcode_1760 { -int32_t minimumSize(const vector &nums, int32_t maxOperations); -} - -TEST_CASE("1 [test_1760]", "[test_1760]") { - const vector nums{9}; - constexpr const auto operations{3}; - constexpr const auto minResult{3}; - CHECK(minResult == leetcode_1760::minimumSize(nums, operations)); -} - - -TEST_CASE("2 [test_1760]", "[test_1760]") { - const vector nums{2, 2, 4, 8}; - constexpr const auto operations{4}; - constexpr const auto minResult{2}; - CHECK(minResult == leetcode_1760::minimumSize(nums, operations)); -} -} - -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_1760_TEST_HPP diff --git a/algorithm/binary_search/leetcode_33.cpp b/algorithm/binary_search/leetcode_33.cpp index 5c2c0967..c062155a 100644 --- a/algorithm/binary_search/leetcode_33.cpp +++ b/algorithm/binary_search/leetcode_33.cpp @@ -1,50 +1,55 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_33_test.hpp" +#include +#include namespace leetcode_33 { +using std::vector; +#endif -int32_t leetcode_33::search(const vector &nums, int32_t target) { - const auto nums_size{static_cast(nums.size())}; - if (nums.empty()) { - return -1; - } else if (nums_size == 1) { - return (nums[0] == target) ? 0 : -1; - } - int32_t minv{nums.back()}, first{0}, maxv{1}; - while (maxv * 2 < nums_size) { - maxv *= 2; - } - while (maxv != 0) { - //cout << first <<" " << maxv << lastl; - if (first + maxv < nums_size && nums[first + maxv] > minv) { - first += maxv; +class Solution { +public: + int32_t search(const vector &nums, int32_t target) { + const auto nums_size{static_cast(nums.size())}; + if (nums.empty()) { + return -1; + } else if (nums_size == 1) { + return (nums[0] == target) ? 0 : -1; } - maxv /= 2; - } - const auto &binary_search_find_first_equal = [target, &nums](auto begin, auto end) { - int32_t middle{0}; - while (begin < static_cast(end)) { - middle = (end - begin) / 2 + begin; - if (target == nums[middle]) { - return middle; - } else if (target > nums[middle]) { - begin = middle + 1; - } else { - end = middle; + int32_t minv{nums.back()}, first{0}, maxv{1}; + while (maxv * 2 < nums_size) { + maxv *= 2; + } + while (maxv != 0) { + //cout << first <<" " << maxv << lastl; + if (first + maxv < nums_size && nums[first + maxv] > minv) { + first += maxv; + } + maxv /= 2; + } + const auto &binary_search_find_first_equal = [target, &nums](auto begin, auto end) { + int32_t middle{0}; + while (begin < static_cast(end)) { + middle = (end - begin) / 2 + begin; + if (target == nums[middle]) { + return middle; + } else if (target > nums[middle]) { + begin = middle + 1; + } else { + end = middle; + } } + return -1; + }; + if (const int x1{binary_search_find_first_equal(0, first + 1)};x1 != -1) { + return x1; } - return -1; - }; - if (const int x1{binary_search_find_first_equal(0, first + 1)};x1 != -1) { - return x1; + return binary_search_find_first_equal(first + 1, nums.size()); } - return binary_search_find_first_equal(first + 1, nums.size()); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_33_test.hpp b/algorithm/binary_search/leetcode_33_test.cpp similarity index 71% rename from algorithm/binary_search/leetcode_33_test.hpp rename to algorithm/binary_search/leetcode_33_test.cpp index 1b57a1b3..88273084 100644 --- a/algorithm/binary_search/leetcode_33_test.hpp +++ b/algorithm/binary_search/leetcode_33_test.cpp @@ -1,92 +1,89 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag binary search //@Tag 二分 //@Level middle -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_33_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_33_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_33_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_33_TEST_HPP +#include "leetcode_33.cpp" #include -#include -#include -#include namespace leetcode_33 { -using std::vector; - -struct leetcode_33 { - static int32_t search(const vector &nums, int32_t target); -}; TEST_CASE("1 [test_33]", "[test_33]") { const vector input{4, 5, 6, 7, 8, 0, 1, 2}; static constexpr const auto target{8}; static constexpr const auto result{4}; - CHECK(result == leetcode_33::search(input, target)); + Solution solution; + CHECK(result == solution.search(input, target)); } TEST_CASE("2 [test_33]", "[test_33]") { const vector input{4, 5, 6, 7, 8, 9, 0, 1, 2}; static constexpr const auto target{9}; static constexpr const auto result{5}; - CHECK(result == leetcode_33::search(input, target)); + Solution solution; + CHECK(result == solution.search(input, target)); } TEST_CASE("3 [test_33]", "[test_33]") { const vector input{4, 5, 6, 7, 8, 9, 10, 0, 1, 2}; static constexpr const auto target{3}; static constexpr const auto result{-1}; - CHECK(result == leetcode_33::search(input, target)); + Solution solution; + CHECK(result == solution.search(input, target)); } TEST_CASE("4 [test_33]", "[test_33]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2}; static constexpr const auto target{2}; static constexpr const auto result{10}; - CHECK(result == leetcode_33::search(input, target)); + Solution solution; + CHECK(result == solution.search(input, target)); } TEST_CASE("5 [test_33]", "[test_33]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2}; static constexpr const auto target{7}; static constexpr const auto result{3}; - CHECK(result == leetcode_33::search(input, target)); + Solution solution; + CHECK(result == solution.search(input, target)); } TEST_CASE("6 [test_33]", "[test_33]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 1, 2}; static constexpr const auto target{24}; static constexpr const auto result{-1}; - CHECK(result == leetcode_33::search(input, target)); + Solution solution; + CHECK(result == solution.search(input, target)); } TEST_CASE("7 [test_33]", "[test_33]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 1, 2}; static constexpr const auto target{13}; static constexpr const auto result{9}; - CHECK(result == leetcode_33::search(input, target)); + Solution solution; + CHECK(result == solution.search(input, target)); } TEST_CASE("8 [test_33]", "[test_33]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2}; static constexpr const auto target{1}; static constexpr const auto result{13}; - CHECK(result == leetcode_33::search(input, target)); + Solution solution; + CHECK(result == solution.search(input, target)); } TEST_CASE("9 [test_33]", "[test_33]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 1, 2}; static constexpr const auto target{0}; static constexpr const auto result{13}; - CHECK(result == leetcode_33::search(input, target)); + Solution solution; + CHECK(result == solution.search(input, target)); } TEST_CASE("10 [test_33]", "[test_33]") { @@ -99,9 +96,10 @@ TEST_CASE("10 [test_33]", "[test_33]") { 0, 7, 8, 9, 14, 16, 21, 35, 37, 41, 44, 45, 47, 48}; static constexpr const auto target{35}; static constexpr const auto result{88}; - CHECK(result == leetcode_33::search(input, target)); + Solution solution; + CHECK(result == solution.search(input, target)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_33_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_33_TEST_HPP diff --git a/algorithm/binary_search/leetcode_34.cpp b/algorithm/binary_search/leetcode_34.cpp index d1ec6b13..30ec23b6 100644 --- a/algorithm/binary_search/leetcode_34.cpp +++ b/algorithm/binary_search/leetcode_34.cpp @@ -1,25 +1,31 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_34_test.hpp" +#include +#include "basic.hpp" namespace leetcode_34 { + +using std::vector; using binary_search::binary_search_pos; +#endif -vector leetcode_34::searchRange(const vector &nums, int32_t target) { - if (nums.empty()) { - return vector{-1, -1}; +class Solution { +public: + vector searchRange(const vector &nums, int32_t target) { + if (nums.empty()) { + return vector{-1, -1}; + } + if (binary_search_pos(nums, target, 0, static_cast(nums.size())) == -1) { + return vector{-1, -1}; + } + const auto minv{static_cast(std::lower_bound(nums.begin(), nums.end(), target) - nums.begin())}, + maxv{static_cast(std::upper_bound(nums.begin(), nums.end(), target) - nums.begin())}; + return vector{minv, maxv - 1}; } - if (binary_search_pos(nums, target, 0, static_cast(nums.size())) == -1) { - return vector{-1, -1}; - } - const auto minv{static_cast(std::lower_bound(nums.begin(), nums.end(), target) - nums.begin())}, - maxv{static_cast(std::upper_bound(nums.begin(), nums.end(), target) - nums.begin())}; - return vector{minv, maxv - 1}; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_34_test.cpp b/algorithm/binary_search/leetcode_34_test.cpp new file mode 100644 index 00000000..3b04b948 --- /dev/null +++ b/algorithm/binary_search/leetcode_34_test.cpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag binary search +//@Tag 二分 +//@Level Hard +//@Plan 剑指OfferII-I Day04 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_34_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_34_TEST_HPP + +#include "leetcode_34.cpp" +#include + +namespace leetcode_34 { +using std::vector; + +TEST_CASE("test case 1", "[test leetcode_34]") { + const vector vec0{}; + const vector vec1{5, 7, 7, 8, 8, 10}; + Solution solution; + assert(solution.searchRange(vec1, 8)[0] == 3 && solution.searchRange(vec1, 8)[1] == 4); + assert(solution.searchRange(vec1, 6)[0] == -1 && solution.searchRange(vec1, 6)[1] == -1); + assert(solution.searchRange(vec0, 115)[0] == -1 && solution.searchRange(vec0, 6)[1] == -1); +} + +} + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_34_TEST_HPP diff --git a/algorithm/binary_search/leetcode_34_test.hpp b/algorithm/binary_search/leetcode_34_test.hpp deleted file mode 100644 index b83f72b4..00000000 --- a/algorithm/binary_search/leetcode_34_test.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag array -//@Tag 数组 -//@Tag binary search -//@Tag 二分 -//@Level Hard -//@Plan 剑指OfferII-I Day04 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_34_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_34_TEST_HPP - -#include -#include "basic.hpp" -#include - -namespace leetcode_34 { -using std::vector; - -struct leetcode_34 { - static vector searchRange(const vector &nums, int target); -}; - -TEST_CASE("test case 1", "[test leetcode_34]") { - const vector vec0{}; - const vector vec1{5, 7, 7, 8, 8, 10}; - assert(leetcode_34::searchRange(vec1, 8)[0] == 3 && leetcode_34::searchRange(vec1, 8)[1] == 4); - assert(leetcode_34::searchRange(vec1, 6)[0] == -1 && leetcode_34::searchRange(vec1, 6)[1] == -1); - assert(leetcode_34::searchRange(vec0, 115)[0] == -1 && leetcode_34::searchRange(vec0, 6)[1] == -1); -} - -} - - -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_34_TEST_HPP diff --git a/algorithm/binary_search/leetcode_35.cpp b/algorithm/binary_search/leetcode_35.cpp index 907c3eef..a1b29424 100644 --- a/algorithm/binary_search/leetcode_35.cpp +++ b/algorithm/binary_search/leetcode_35.cpp @@ -1,40 +1,48 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_35_test.hpp" +#include +#include #include -// 实质上是寻找第一个大于等于target的数字的下标 -// 如果目标不存在,则返回第一个大于其的位置减一 namespace binary_search::leetcode_35 { +using std::vector; +using std::distance; +#endif -int32_t leetcode_35::searchInsert(const vector &nums, int32_t target) { - const auto n_size = static_cast(nums.size()); - if (nums.empty() || target < nums.front()) { - return 0; // 放到第一个 - } else if (nums.back() < target) { - return n_size; // 放到最后一个 - } - int32_t left{0}, right{n_size - 1}, middle{0}; - while (left < right) { - if (middle = (right - left) / 2 + left; nums[middle] > target) {// 避免溢出 - right = middle; - } else if (nums[middle] < target) { - left = middle + 1;// 只有一处+1 - } else { - return middle; + + +// 实质上是寻找第一个大于等于target的数字的下标 +// 如果目标不存在,则返回第一个大于其的位置减一 +class Solution { +public: + int32_t searchInsert(const vector &nums, int32_t target) { + const auto n_size = static_cast(nums.size()); + if (nums.empty() || target < nums.front()) { + return 0; // 放到第一个 + } else if (nums.back() < target) { + return n_size; // 放到最后一个 + } + int32_t left{0}, right{n_size - 1}, middle{0}; + while (left < right) { + if (middle = (right - left) / 2 + left; nums[middle] > target) {// 避免溢出 + right = middle; + } else if (nums[middle] < target) { + left = middle + 1;// 只有一处+1 + } else { + return middle; + } } + return left; } - return left; -} -int32_t leetcode_35::searchInsert2(const vector &nums, int32_t target) { - const auto diff = std::lower_bound(nums.begin(), nums.end(), target); - return static_cast(distance(nums.begin(), diff)); -} + int32_t searchInsert2(const vector &nums, int32_t target) { + const auto diff = std::lower_bound(nums.begin(), nums.end(), target); + return static_cast(distance(nums.begin(), diff)); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_35_test.cpp b/algorithm/binary_search/leetcode_35_test.cpp new file mode 100644 index 00000000..397d9c28 --- /dev/null +++ b/algorithm/binary_search/leetcode_35_test.cpp @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_35_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_35_TEST_HPP + +#include "leetcode_35.cpp" +#include +// 实质上是寻找第一个大于等于target的数字的下标 +// 如果目标不存在,则返回第一个大于其的位置减一 + +namespace binary_search::leetcode_35 { + +TEST_CASE("test case 1", "[test leetcode_35]") { + const vector input{1, 3, 5, 6}; + static constexpr const auto target{5}, result{2}; + Solution solution; + CHECK(result == solution.searchInsert(input, target)); + CHECK(result == solution.searchInsert2(input, target)); +} + +TEST_CASE("test case 2", "[test leetcode_35]") { + const vector input{1, 3, 5, 6}; + static constexpr const auto target{2}, result{1}; + Solution solution; + CHECK(result == solution.searchInsert(input, target)); + CHECK(result == solution.searchInsert2(input, target)); +} + +TEST_CASE("test case 3", "[test leetcode_35]") { + const vector input{1, 3, 5, 6}; + static constexpr const auto target{7}, result{4}; + Solution solution; + CHECK(result == solution.searchInsert(input, target)); + CHECK(result == solution.searchInsert2(input, target)); +} + +TEST_CASE("test case 4", "[test leetcode_35]") { + const vector input{1, 3, 5, 6}; + static constexpr const auto target{0}, result{0}; + Solution solution; + CHECK(result == solution.searchInsert(input, target)); + CHECK(result == solution.searchInsert2(input, target)); +} + +TEST_CASE("test case 5", "[test leetcode_35]") { + const vector input{1}; + static constexpr const auto target{0}, result{0}; + Solution solution; + CHECK(result == solution.searchInsert(input, target)); + CHECK(result == solution.searchInsert2(input, target)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_35_TEST_HPP + diff --git a/algorithm/binary_search/leetcode_35_test.hpp b/algorithm/binary_search/leetcode_35_test.hpp deleted file mode 100644 index cf786fbd..00000000 --- a/algorithm/binary_search/leetcode_35_test.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_35_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_35_TEST_HPP - -#include -#include -#include -#include -// 实质上是寻找第一个大于等于target的数字的下标 -// 如果目标不存在,则返回第一个大于其的位置减一 - -namespace binary_search::leetcode_35 { -using std::vector; -using num_t = int32_t; - -struct leetcode_35 final { - static int searchInsert(const vector &nums, int target); - - static int searchInsert2(const vector &nums, int target); -}; - -TEST_CASE("test case 1", "[test leetcode_35]") { - const vector input{1, 3, 5, 6}; - static constexpr const auto target{5}, result{2}; - CHECK(result == leetcode_35::searchInsert(input, target)); - CHECK(result == leetcode_35::searchInsert2(input, target)); -} - -TEST_CASE("test case 2", "[test leetcode_35]") { - const vector input{1, 3, 5, 6}; - static constexpr const auto target{2}, result{1}; - CHECK(result == leetcode_35::searchInsert(input, target)); - CHECK(result == leetcode_35::searchInsert2(input, target)); -} - -TEST_CASE("test case 3", "[test leetcode_35]") { - const vector input{1, 3, 5, 6}; - static constexpr const auto target{7}, result{4}; - CHECK(result == leetcode_35::searchInsert(input, target)); - CHECK(result == leetcode_35::searchInsert2(input, target)); -} - -TEST_CASE("test case 4", "[test leetcode_35]") { - const vector input{1, 3, 5, 6}; - static constexpr const auto target{0}, result{0}; - CHECK(result == leetcode_35::searchInsert(input, target)); - CHECK(result == leetcode_35::searchInsert2(input, target)); -} - -TEST_CASE("test case 5", "[test leetcode_35]") { - const vector input{1}; - static constexpr const auto target{0}, result{0}; - CHECK(result == leetcode_35::searchInsert(input, target)); - CHECK(result == leetcode_35::searchInsert2(input, target)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_35_TEST_HPP - diff --git a/algorithm/binary_search/leetcode_4.cpp b/algorithm/binary_search/leetcode_4.cpp index 065274c6..dac439fd 100644 --- a/algorithm/binary_search/leetcode_4.cpp +++ b/algorithm/binary_search/leetcode_4.cpp @@ -1,105 +1,113 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_4_test.hpp" +#include +#include +#include +#include namespace leetcode_4 { +using std::vector; + +#endif -double leetcode_4::findMedianSortedArraysOn(const vector &nums1, const vector &nums2) { - vector merged{}; - merged.reserve(nums1.size() + nums2.size()); - const size_t nums1_size{nums1.size()}, nums2_size{nums2.size()}; - size_t nums1_order{0}, nums2_order{0}; - while (nums1_order < nums1_size && nums2_order < nums2_size) { - if (nums1[nums1_order] < nums2[nums2_order]) { + +class Solution { +public: + double findMedianSortedArraysOn(const vector &nums1, const vector &nums2) { + vector merged{}; + merged.reserve(nums1.size() + nums2.size()); + const size_t nums1_size{nums1.size()}, nums2_size{nums2.size()}; + size_t nums1_order{0}, nums2_order{0}; + while (nums1_order < nums1_size && nums2_order < nums2_size) { + if (nums1[nums1_order] < nums2[nums2_order]) { + merged.push_back(nums1[nums1_order]); + nums1_order++; + } else { + merged.push_back(nums2[nums2_order]); + nums2_order++; + } + } + while (nums1_order < nums1_size) { merged.push_back(nums1[nums1_order]); nums1_order++; - } else { + } + while (nums2_order < nums2_size) { merged.push_back(nums2[nums2_order]); nums2_order++; } - } - while (nums1_order < nums1_size) { - merged.push_back(nums1[nums1_order]); - nums1_order++; - } - while (nums2_order < nums2_size) { - merged.push_back(nums2[nums2_order]); - nums2_order++; - } - if (merged.size() % 2 == 0) { - return static_cast((merged[merged.size() / 2 - 1] + merged[merged.size() / 2])) / 2.0f; - } - const auto mid = merged.size() / 2; - return static_cast(merged[mid]); -} - - -double leetcode_4::findMedianSortedArraysOlogN(const vector &nums1, const vector &nums2) { - const std::function - get_nums = [&get_nums, &nums1, &nums2](size_t begin1, size_t begin2, int k) { - if (begin1 >= nums1.size()) { - return nums2[begin2 + k - 1]; - } else if (begin2 >= nums2.size()) { - return nums1[begin1 + k - 1]; - } else if (k == 1) { - return std::min(nums1[begin1], nums2[begin2]); - } - int half = k / 2; - int newIndex1 = std::min(begin1 + half, nums1.size()) - 1; - int newIndex2 = std::min(begin2 + half, nums2.size()) - 1; - if (nums1[newIndex1] <= nums2[newIndex2]) { - k -= (newIndex1 - begin1 + 1); - begin1 = newIndex1 + 1; - } else { - k -= (newIndex2 - begin2 + 1); - begin2 = newIndex2 + 1; + if (merged.size() % 2 == 0) { + return static_cast((merged[merged.size() / 2 - 1] + merged[merged.size() / 2])) / 2.0f; } - return get_nums(begin1, begin2, k); - }; - auto left = (nums1.size() + nums2.size() + 1) / 2; - auto right = (nums1.size() + nums2.size() + 2) / 2; - return (get_nums(0, 0, left) * 1.0f + - get_nums(0, 0, right) * 1.0f) / 2; - -} + const auto mid = merged.size() / 2; + return static_cast(merged[mid]); + } -double leetcode_4::findMedianSortedArraysOlogN2(const vector &nums1, const vector &nums2) { - const size_t nums1_size{nums1.size()}, nums2_size{nums2.size()}; - const auto getKthElement = [nums1_size, nums2_size, & nums1, & nums2](size_t k) { - k += 1; - size_t nums1_order{0}, nums2_order{0}; - while (nums1_order < nums1_size && nums2_order < nums2_size && k != 1) { - // 正常情况 - const auto half{k / 2}; - const size_t next_nums1_order{std::min(nums1_order + half, nums1_size) - 1}, - next_nums2_order{std::min(nums2_order + half, nums2_size) - 1}; - const auto v1{nums1[next_nums1_order]}, v2{nums2[next_nums2_order]}; - if (v1 <= v2) { - k -= next_nums1_order - nums1_order + 1; - nums1_order = next_nums1_order + 1; + double findMedianSortedArraysOlogN(const vector &nums1, const vector &nums2) { + const std::function + get_nums = [&get_nums, &nums1, &nums2](size_t begin1, size_t begin2, int k) { + if (begin1 >= nums1.size()) { + return nums2[begin2 + k - 1]; + } else if (begin2 >= nums2.size()) { + return nums1[begin1 + k - 1]; + } else if (k == 1) { + return std::min(nums1[begin1], nums2[begin2]); + } + int half = k / 2; + int newIndex1 = std::min(begin1 + half, nums1.size()) - 1; + int newIndex2 = std::min(begin2 + half, nums2.size()) - 1; + if (nums1[newIndex1] <= nums2[newIndex2]) { + k -= (newIndex1 - begin1 + 1); + begin1 = newIndex1 + 1; } else { - k -= next_nums2_order - nums2_order + 1; - nums2_order = next_nums2_order + 1; + k -= (newIndex2 - begin2 + 1); + begin2 = newIndex2 + 1; } + return get_nums(begin1, begin2, k); + }; + auto left = (nums1.size() + nums2.size() + 1) / 2; + auto right = (nums1.size() + nums2.size() + 2) / 2; + return (get_nums(0, 0, left) * 1.0f + + get_nums(0, 0, right) * 1.0f) / 2; + } + + double findMedianSortedArraysOlogN2(const vector &nums1, const vector &nums2) { + const size_t nums1_size{nums1.size()}, nums2_size{nums2.size()}; + const auto getKthElement = [nums1_size, nums2_size, & nums1, & nums2](size_t k) { + k += 1; + size_t nums1_order{0}, nums2_order{0}; + while (nums1_order < nums1_size && nums2_order < nums2_size && k != 1) { + // 正常情况 + const auto half{k / 2}; + const size_t next_nums1_order{std::min(nums1_order + half, nums1_size) - 1}, + next_nums2_order{std::min(nums2_order + half, nums2_size) - 1}; + const auto v1{nums1[next_nums1_order]}, v2{nums2[next_nums2_order]}; + if (v1 <= v2) { + k -= next_nums1_order - nums1_order + 1; + nums1_order = next_nums1_order + 1; + } else { + k -= next_nums2_order - nums2_order + 1; + nums2_order = next_nums2_order + 1; + } + } + // 边界情况 + if (nums1_order == nums1_size) { + return nums2[nums2_order + k - 1]; + } + if (nums2_order == nums2_size) { + return nums1[nums1_order + k - 1]; + } + return std::min(nums1[nums1_order], nums2[nums2_order]); + }; + size_t totalLength{nums1_size + nums2_size}; + if (totalLength % 2 == 0) { + return (getKthElement(totalLength / 2) + getKthElement(totalLength / 2 - 1)) / 2.0; } - // 边界情况 - if (nums1_order == nums1_size) { - return nums2[nums2_order + k - 1]; - } - if (nums2_order == nums2_size) { - return nums1[nums1_order + k - 1]; - } - return std::min(nums1[nums1_order], nums2[nums2_order]); - }; - size_t totalLength{nums1_size + nums2_size}; - if (totalLength % 2 == 0) { - return (getKthElement(totalLength / 2) + getKthElement(totalLength / 2 - 1)) / 2.0; + return getKthElement(totalLength / 2); } - return getKthElement(totalLength / 2); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_4_test.cpp b/algorithm/binary_search/leetcode_4_test.cpp new file mode 100644 index 00000000..96701260 --- /dev/null +++ b/algorithm/binary_search/leetcode_4_test.cpp @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag array +//@Tag 数组 +//@Tag binary search +//@Tag 二分 +//@Level Hard +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_4_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_4_TEST_HPP + +#include "leetcode_4.cpp" +#include + +namespace leetcode_4 { +using std::vector; + +TEST_CASE("1 [test_4]", "[test_4]") { + const vector num1{1, 3}; + const vector num2{2}; + Solution solution; + CHECK(solution.findMedianSortedArraysOn(num1, num2) == 2); + CHECK(solution.findMedianSortedArraysOlogN(num1, num2) == 2); + CHECK(solution.findMedianSortedArraysOlogN2(num1, num2) == 2); +} + +TEST_CASE("2 [test_4]", "[test_4]") { + const vector num1{1, 3}; + const vector num2{2, 4}; + Solution solution; + CHECK(solution.findMedianSortedArraysOn(num1, num2) == 2.5f); + CHECK(solution.findMedianSortedArraysOlogN(num1, num2) == 2.5f); + CHECK(solution.findMedianSortedArraysOlogN2(num1, num2) == 2.5f); +} + +TEST_CASE("3 [test_4]", "[test_4]") { + const vector num1{0, 0}; + const vector num2{0, 0}; + Solution solution; + CHECK(solution.findMedianSortedArraysOn(num1, num2) == 0); + CHECK(solution.findMedianSortedArraysOlogN(num1, num2) == 0); + CHECK(solution.findMedianSortedArraysOlogN2(num1, num2) == 0); +} + +TEST_CASE("4 [test_4]", "[test_4]") { + const vector num1{1}; + const vector num2{}; + Solution solution; + CHECK(solution.findMedianSortedArraysOn(num1, num2) == 1); + CHECK(solution.findMedianSortedArraysOlogN(num1, num2) == 1); + CHECK(solution.findMedianSortedArraysOlogN2(num1, num2) == 1); +} + +TEST_CASE("5 [test_4]", "[test_4]") { + const vector num1{2}; + const vector num2{}; + Solution solution; + CHECK(solution.findMedianSortedArraysOn(num1, num2) == 2); + CHECK(solution.findMedianSortedArraysOlogN(num1, num2) == 2); + CHECK(solution.findMedianSortedArraysOlogN2(num1, num2) == 2); +} + +TEST_CASE("6 [test_4]", "[test_4]") { + const vector num1{2, 2, 4, 4}; + const vector num2{2, 2, 4, 4}; + Solution solution; + CHECK(solution.findMedianSortedArraysOlogN(num1, num2) == 3.0f); + CHECK(solution.findMedianSortedArraysOlogN2(num1, num2) == 3.0f); +} +} + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_4_TEST_HPP diff --git a/algorithm/binary_search/leetcode_4_test.hpp b/algorithm/binary_search/leetcode_4_test.hpp deleted file mode 100644 index 9b49222b..00000000 --- a/algorithm/binary_search/leetcode_4_test.hpp +++ /dev/null @@ -1,81 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag array -//@Tag 数组 -//@Tag binary search -//@Tag 二分 -//@Level Hard -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_4_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_4_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_4 { -using std::vector; - -struct leetcode_4 { - static double findMedianSortedArraysOn(const vector &nums1, const vector &nums2); - - static double findMedianSortedArraysOlogN(const vector &nums1, const vector &nums2); - - static double findMedianSortedArraysOlogN2(const vector &nums1, const vector &nums2); -}; - -TEST_CASE("1 [test_4]", "[test_4]") { - const vector num1{1, 3}; - const vector num2{2}; - CHECK(leetcode_4::findMedianSortedArraysOn(num1, num2) == 2); - CHECK(leetcode_4::findMedianSortedArraysOlogN(num1, num2) == 2); - CHECK(leetcode_4::findMedianSortedArraysOlogN2(num1, num2) == 2); -} - -TEST_CASE("2 [test_4]", "[test_4]") { - const vector num1{1, 3}; - const vector num2{2, 4}; - CHECK(leetcode_4::findMedianSortedArraysOn(num1, num2) == 2.5f); - CHECK(leetcode_4::findMedianSortedArraysOlogN(num1, num2) == 2.5f); - CHECK(leetcode_4::findMedianSortedArraysOlogN2(num1, num2) == 2.5f); -} - -TEST_CASE("3 [test_4]", "[test_4]") { - const vector num1{0, 0}; - const vector num2{0, 0}; - CHECK(leetcode_4::findMedianSortedArraysOn(num1, num2) == 0); - CHECK(leetcode_4::findMedianSortedArraysOlogN(num1, num2) == 0); - CHECK(leetcode_4::findMedianSortedArraysOlogN2(num1, num2) == 0); -} - -TEST_CASE("4 [test_4]", "[test_4]") { - const vector num1{1}; - const vector num2{}; - CHECK(leetcode_4::findMedianSortedArraysOn(num1, num2) == 1); - CHECK(leetcode_4::findMedianSortedArraysOlogN(num1, num2) == 1); - CHECK(leetcode_4::findMedianSortedArraysOlogN2(num1, num2) == 1); -} - -TEST_CASE("5 [test_4]", "[test_4]") { - const vector num1{2}; - const vector num2{}; - CHECK(leetcode_4::findMedianSortedArraysOn(num1, num2) == 2); - CHECK(leetcode_4::findMedianSortedArraysOlogN(num1, num2) == 2); - CHECK(leetcode_4::findMedianSortedArraysOlogN2(num1, num2) == 2); -} - -TEST_CASE("6 [test_4]", "[test_4]") { - const vector num1{2, 2, 4, 4}; - const vector num2{2, 2, 4, 4}; - CHECK(leetcode_4::findMedianSortedArraysOlogN(num1, num2) == 3.0f); - CHECK(leetcode_4::findMedianSortedArraysOlogN2(num1, num2) == 3.0f); -} -} - - -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_4_TEST_HPP diff --git a/algorithm/binary_search/leetcode_69.cpp b/algorithm/binary_search/leetcode_69.cpp index ed46475e..c290fcaf 100644 --- a/algorithm/binary_search/leetcode_69.cpp +++ b/algorithm/binary_search/leetcode_69.cpp @@ -1,40 +1,44 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_69_test.hpp" #include #include +#include // 实质上是寻找第一个大于等于target的数字的下标 // 如果目标不存在,则返回第一个大于其的位置减一 namespace leetcode_69 { using std::vector; -int32_t leetcode_69::mySqrt(int32_t x) { - if (x == 0) { - return 0; - } else if (x <= 3) { - return 1; - } - size_t begin{1}, end{static_cast(x - 1)}, middle{0}; - while (begin <= end) { - middle = begin + (end - begin) / 2; - const size_t mul{middle * middle}, - mul2{mul + (middle << 1) + 1}; - if (mul <= static_cast(x) && static_cast(x) < mul2) { - return static_cast(middle); +#endif + + +class Solution { +public: + int32_t mySqrt(int32_t x) { + if (x == 0) { + return 0; + } else if (x <= 3) { + return 1; } - if (mul > static_cast(x)) { - end = middle - 1; - } else if (mul < static_cast(x)) { - begin = middle + 1; + size_t begin{1}, end{static_cast(x - 1)}, middle{0}; + while (begin <= end) { + middle = begin + (end - begin) / 2; + const size_t mul{middle * middle}, + mul2{mul + (middle << 1) + 1}; + if (mul <= static_cast(x) && static_cast(x) < mul2) { + return static_cast(middle); + } + if (mul > static_cast(x)) { + end = middle - 1; + } else if (mul < static_cast(x)) { + begin = middle + 1; + } } + return -1; } - return -1; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_69_test.cpp b/algorithm/binary_search/leetcode_69_test.cpp new file mode 100644 index 00000000..b80b68f6 --- /dev/null +++ b/algorithm/binary_search/leetcode_69_test.cpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_69_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_69_TEST_HPP + +#include "leetcode_69.cpp" +#include + +// 实质上是寻找第一个大于等于target的数字的下标 +// 如果目标不存在,则返回第一个大于其的位置减一 + +namespace leetcode_69 { + +TEST_CASE("test case 0", "[test leetcode_69]") { + Solution solution; + CHECK(0 == solution.mySqrt(0)); + CHECK(1 == solution.mySqrt(1)); + CHECK(1 == solution.mySqrt(1)); + CHECK(1 == solution.mySqrt(1)); +} + +TEST_CASE("test case 1", "[test leetcode_69]") { + static constexpr const auto input{4}, result{2}; + Solution solution; + CHECK(result == solution.mySqrt(input)); +} + +TEST_CASE("test case 2", "[test leetcode_69]") { + static constexpr const auto input{8}, result{2}; + Solution solution; + CHECK(result == solution.mySqrt(input)); +} + +TEST_CASE("test case 3", "[test leetcode_69]") { + static constexpr const auto input{9}, result{3}; + Solution solution; + CHECK(result == solution.mySqrt(input)); +} + +TEST_CASE("test case 4", "[test leetcode_69]") { + static constexpr const auto input{6}, result{2}; + Solution solution; + CHECK(result == solution.mySqrt(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_69_TEST_HPP + diff --git a/algorithm/binary_search/leetcode_69_test.hpp b/algorithm/binary_search/leetcode_69_test.hpp deleted file mode 100644 index dac1ea47..00000000 --- a/algorithm/binary_search/leetcode_69_test.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_69_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_69_TEST_HPP - -#include -#include -#include - -// 实质上是寻找第一个大于等于target的数字的下标 -// 如果目标不存在,则返回第一个大于其的位置减一 - -namespace leetcode_69 { -struct leetcode_69 final { - static int32_t mySqrt(int32_t x); -}; - -TEST_CASE("test case 0", "[test leetcode_69]") { - CHECK(0 == leetcode_69::mySqrt(0)); - CHECK(1 == leetcode_69::mySqrt(1)); - CHECK(1 == leetcode_69::mySqrt(1)); - CHECK(1 == leetcode_69::mySqrt(1)); -} - -TEST_CASE("test case 1", "[test leetcode_69]") { - static constexpr const auto input{4}, result{2}; - CHECK(result == leetcode_69::mySqrt(input)); -} - -TEST_CASE("test case 2", "[test leetcode_69]") { - static constexpr const auto input{8}, result{2}; - CHECK(result == leetcode_69::mySqrt(input)); -} - -TEST_CASE("test case 3", "[test leetcode_69]") { - static constexpr const auto input{9}, result{3}; - CHECK(result == leetcode_69::mySqrt(input)); -} - -TEST_CASE("test case 4", "[test leetcode_69]") { - static constexpr const auto input{6}, result{2}; - CHECK(result == leetcode_69::mySqrt(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_69_TEST_HPP - diff --git a/algorithm/binary_search/leetcode_81.cpp b/algorithm/binary_search/leetcode_81.cpp index 7db6e6b0..62165880 100644 --- a/algorithm/binary_search/leetcode_81.cpp +++ b/algorithm/binary_search/leetcode_81.cpp @@ -1,50 +1,56 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +namespace leetcode_81 { +using std::vector; -*/ -#include "leetcode_81_test.hpp" +#endif -namespace leetcode_81 { -bool leetcode_81::search(const vector &nums, int32_t target) { - const auto nums_size{nums.size()}; - if (nums.empty()) { - return false; - } else if (nums_size == 1) { - return nums[0] == target; - } - size_t first{0}, maxv{1}; - while (maxv * 2 < nums_size) { - maxv *= 2; - } - while (first < nums_size && 0 < maxv) { - if (const auto next{first + maxv};next >= nums_size || nums[next] < nums[first]) { - maxv /= 2; - } else if (nums[next] == nums[first]) { - first++; - } else if (nums[next] > nums[first]) { - first = next; +class Solution { +public: + bool search(const vector &nums, int32_t target) { + const auto nums_size{nums.size()}; + if (nums.empty()) { + return false; + } else if (nums_size == 1) { + return nums[0] == target; } - } - const auto &binary_search_find_first_equal = [target, &nums](auto begin, auto end) { - int32_t middle{0}; - while (begin < end) { - middle = (end - begin) / 2 + begin; - if (target == nums[middle]) { - return true; - } else if (target > nums[middle]) { - begin = middle + 1; - } else { - end = middle; + size_t first{0}, maxv{1}; + while (maxv * 2 < nums_size) { + maxv *= 2; + } + while (first < nums_size && 0 < maxv) { + if (const auto next{first + maxv};next >= nums_size || nums[next] < nums[first]) { + maxv /= 2; + } else if (nums[next] == nums[first]) { + first++; + } else if (nums[next] > nums[first]) { + first = next; } } - return false; - }; - return binary_search_find_first_equal(static_cast(0), first + 1) || - binary_search_find_first_equal(first + 1, nums.size()); -} + const auto &binary_search_find_first_equal = [target, &nums](auto begin, auto end) { + int32_t middle{0}; + while (begin < end) { + middle = (end - begin) / 2 + begin; + if (target == nums[middle]) { + return true; + } else if (target > nums[middle]) { + begin = middle + 1; + } else { + end = middle; + } + } + return false; + }; + return binary_search_find_first_equal(static_cast(0), first + 1) || + binary_search_find_first_equal(first + 1, nums.size()); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_81_test.hpp b/algorithm/binary_search/leetcode_81_test.cpp similarity index 69% rename from algorithm/binary_search/leetcode_81_test.hpp rename to algorithm/binary_search/leetcode_81_test.cpp index b20059d7..25529b7a 100644 --- a/algorithm/binary_search/leetcode_81_test.hpp +++ b/algorithm/binary_search/leetcode_81_test.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag array //@Tag 数组 //@Tag binary search @@ -12,74 +7,77 @@ Copyright (C) 2020-2023 nanos //@Level middle //@Related 33 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_81_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_81_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_81_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_81_TEST_HPP +#include "leetcode_81.cpp" #include -#include -#include -#include namespace leetcode_81 { using std::vector; -struct leetcode_81 { - static bool search(const vector &nums, int32_t target); -}; - TEST_CASE("1 [test_81]", "[test_81]") { const vector input{4, 5, 6, 7, 8, 0, 1, 2}; static constexpr const auto target{8}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("2 [test_81]", "[test_81]") { const vector input{4, 5, 6, 7, 8, 9, 0, 1, 2}; static constexpr const auto target{9}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("3 [test_81]", "[test_81]") { const vector input{4, 5, 6, 7, 8, 9, 10, 0, 1, 2}; static constexpr const auto target{3}; - CHECK_FALSE(leetcode_81::search(input, target)); + Solution solution; + CHECK_FALSE(solution.search(input, target)); } TEST_CASE("4 [test_81]", "[test_81]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2}; static constexpr const auto target{2}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("5 [test_81]", "[test_81]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2}; static constexpr const auto target{7}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("6 [test_81]", "[test_81]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 1, 2}; static constexpr const auto target{24}; - CHECK_FALSE(leetcode_81::search(input, target)); + Solution solution; + CHECK_FALSE(solution.search(input, target)); } TEST_CASE("7 [test_81]", "[test_81]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 1, 2}; static constexpr const auto target{13}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("8 [test_81]", "[test_81]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2}; static constexpr const auto target{1}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("9 [test_81]", "[test_81]") { const vector input{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 1, 2}; static constexpr const auto target{0}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("10 [test_81]", "[test_81]") { @@ -91,58 +89,66 @@ TEST_CASE("10 [test_81]", "[test_81]") { 256, 261, 266, 267, 272, 275, 286, 289, 291, 296, 299, 0, 7, 8, 9, 14, 16, 21, 35, 37, 41, 44, 45, 47, 48}; static constexpr const auto target{35}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("11 [test_81]", "[test_81]") { const vector input{2, 5, 6, 0, 0, 1, 2}; static constexpr const auto target{0}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("12 [test_81]", "[test_81]") { const vector input{2, 5, 6, 0, 0, 1, 2}; static constexpr const auto target{3}; - CHECK_FALSE(leetcode_81::search(input, target)); + Solution solution; + CHECK_FALSE(solution.search(input, target)); } TEST_CASE("13 [test_81]", "[test_81]") { const vector input{2, 2, 2, 3, 2, 2, 2}; static constexpr const auto target{3}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("14 [test 81]", "[test 81]") { const vector input{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1}; static constexpr const auto target{2}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("15 [test 81]", "[test 81]") { const vector input{1, 0, 1, 1, 1}; static constexpr const auto target{0}; - CHECK(leetcode_81::search(input, target)); + Solution solution; + CHECK(solution.search(input, target)); } TEST_CASE("16 [test 81]", "[test 81]") { const vector input{1, 1}; static constexpr const auto target{0}; - CHECK_FALSE(leetcode_81::search(input, target)); + Solution solution; + CHECK_FALSE(solution.search(input, target)); } TEST_CASE("17 [test 81]", "[test 81]") { const vector input{1, 1, 1, 3}; static constexpr const auto target{2}; - CHECK_FALSE(leetcode_81::search(input, target)); + Solution solution; + CHECK_FALSE(solution.search(input, target)); } TEST_CASE("18 [test 81]", "[test 81]") { const vector input{1, 0, 1, 1, 1}; static constexpr const auto target{2}; - CHECK_FALSE(leetcode_81::search(input, target)); + Solution solution; + CHECK_FALSE(solution.search(input, target)); } } - -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_81_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_TEST_81_TEST_HPP diff --git a/algorithm/binary_search/leetcode_so_53ii.cpp b/algorithm/binary_search/leetcode_so_53ii.cpp index 93d08b4e..f0edb0f6 100644 --- a/algorithm/binary_search/leetcode_so_53ii.cpp +++ b/algorithm/binary_search/leetcode_so_53ii.cpp @@ -1,32 +1,38 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_so_53ii_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include namespace leetcode_so_53ii { +#endif -int32_t leetcode_so_53ii::missingNumber(const vector &nums) { - if (nums.empty()) { - return 0; - } - const int32_t size{static_cast(nums.size())}; - if (nums.back() + 1 == size) { - return size; - } - for (int32_t fst{0}, last{size - 1}; fst < last;) { - if (const int32_t mid{fst + (last - fst) / 2}; nums[mid] == mid) { - fst = mid + 1; - if (nums[mid + 1] - nums[mid] == 2) { - return mid + 1; +using std::vector; + +class Solution { +public: + int32_t missingNumber(const vector &nums) { + if (nums.empty()) { + return 0; + } + const int32_t size{static_cast(nums.size())}; + if (nums.back() + 1 == size) { + return size; + } + for (int32_t fst{0}, last{size - 1}; fst < last;) { + if (const int32_t mid{fst + (last - fst) / 2}; nums[mid] == mid) { + fst = mid + 1; + if (nums[mid + 1] - nums[mid] == 2) { + return mid + 1; + } + } else { + last = mid; } - } else { - last = mid; } + return 0; } - return 0; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/binary_search/leetcode_so_53ii_test.hpp b/algorithm/binary_search/leetcode_so_53ii_test.cpp similarity index 52% rename from algorithm/binary_search/leetcode_so_53ii_test.hpp rename to algorithm/binary_search/leetcode_so_53ii_test.cpp index 09b7c230..2ac9755e 100644 --- a/algorithm/binary_search/leetcode_so_53ii_test.hpp +++ b/algorithm/binary_search/leetcode_so_53ii_test.cpp @@ -1,50 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag binary-search //@Tag 二分搜索 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_SO_53II_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_SO_53II_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_SO_53II_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_SO_53II_HPP +#include "leetcode_so_53ii.cpp" #include -#include -#include -#include namespace leetcode_so_53ii { using std::vector; -struct leetcode_so_53ii { - static int32_t missingNumber(const vector &nums); -}; - TEST_CASE("test case 1 [test_so_53ii]", "[test_so_53ii]") { const vector input{0, 1}; static constexpr const auto result{2}; - CHECK(result == leetcode_so_53ii::missingNumber(input)); + Solution solution; + CHECK(result == solution.missingNumber(input)); } TEST_CASE("test case 2 [test_so_53ii]", "[test_so_53ii]") { const vector input{1}; static constexpr const auto result{0}; - CHECK(result == leetcode_so_53ii::missingNumber(input)); + Solution solution; + CHECK(result == solution.missingNumber(input)); } TEST_CASE("test case 3 [test_so_53ii]", "[test_so_53ii]") { const vector input{0, 1}; static constexpr const auto result{2}; - CHECK(result == leetcode_so_53ii::missingNumber(input)); + Solution solution; + CHECK(result == solution.missingNumber(input)); } TEST_CASE("test case 4 [test_so_53ii]", "[test_so_53ii]") { const vector input{0}; static constexpr const auto result{1}; - CHECK(result == leetcode_so_53ii::missingNumber(input)); + Solution solution; + CHECK(result == solution.missingNumber(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_SO_53II_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_BINARY_SEARCH_LEETCODE_SO_53II_HPP diff --git a/algorithm/binary_search/rotate_array.cpp b/algorithm/binary_search/rotate_array_test.cpp similarity index 90% rename from algorithm/binary_search/rotate_array.cpp rename to algorithm/binary_search/rotate_array_test.cpp index ae16dcd4..5436fc38 100644 --- a/algorithm/binary_search/rotate_array.cpp +++ b/algorithm/binary_search/rotate_array_test.cpp @@ -1,16 +1,5 @@ -/* - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanoseeds - * @Date: 2020-08-01 17:39:45 - * @LastEditors: nanoseeds - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds // refer https://leetcode-cn.com/problems/rotate-array/ // 189 #include diff --git a/algorithm/binary_search/triple_search.cpp b/algorithm/binary_search/triple_search_test.cpp similarity index 95% rename from algorithm/binary_search/triple_search.cpp rename to algorithm/binary_search/triple_search_test.cpp index b0d415ae..2ae3a499 100644 --- a/algorithm/binary_search/triple_search.cpp +++ b/algorithm/binary_search/triple_search_test.cpp @@ -1,16 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanoseeds - * @Date: 2020-08-01 17:33:49 - * @LastEditors: nanoseeds - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include diff --git a/algorithm/cs302/banker/CMakeLists.txt b/algorithm/cs302/banker/CMakeLists.txt index cba40c28..381b74ee 100644 --- a/algorithm/cs302/banker/CMakeLists.txt +++ b/algorithm/cs302/banker/CMakeLists.txt @@ -6,7 +6,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") enable_testing() add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/banker.cpp) -target_link_libraries(${PROJECT_NAME}_test CS203_DSAA_template_INCLUDE) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test algorithm_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) MESSAGE(STATUS "${PROJECT_NAME} from ${CMAKE_CURRENT_SOURCE_DIR}/banker.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) diff --git a/algorithm/cs302/banker/banker.cpp b/algorithm/cs302/banker/banker.cpp index 4a0dff74..b1b3199d 100644 --- a/algorithm/cs302/banker/banker.cpp +++ b/algorithm/cs302/banker/banker.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include "banker_base.hpp" #include diff --git a/algorithm/cs302/banker/banker_base.hpp b/algorithm/cs302/banker/banker_base.hpp index 355e1dc5..ca44d775 100644 --- a/algorithm/cs302/banker/banker_base.hpp +++ b/algorithm/cs302/banker/banker_base.hpp @@ -1,10 +1,8 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_CS302_BANKER_BANKER_BASE_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_CS302_BANKER_BANKER_BASE_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_CS302_BANKER_BANKER_BASE_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_CS302_BANKER_BANKER_BASE_HPP #include #include @@ -89,4 +87,4 @@ std::string getFilePath() noexcept { } const std::string CS203_redirect::file_paths = getFilePath(); -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_CS302_BANKER_BANKER_BASE_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_CS302_BANKER_BANKER_BASE_HPP diff --git a/algorithm/cs302/cache/CMakeLists.txt b/algorithm/cs302/cache/CMakeLists.txt index 46824e3a..50f42a5c 100644 --- a/algorithm/cs302/cache/CMakeLists.txt +++ b/algorithm/cs302/cache/CMakeLists.txt @@ -6,11 +6,11 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") enable_testing() -set(dependencies lru no fifo fifo_sc clock min) +set(dependencies lru no fifo fifo_sc clock min s3fifo) foreach (elementName IN LISTS dependencies) add_executable(${PROJECT_NAME}_${elementName}_test ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_cache.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName}_test CS203_DSAA_template_INCLUDE) - target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE CS203_DSAA_TEST_MACRO) + target_link_libraries(${PROJECT_NAME}_${elementName}_test algorithm_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE ALGORITHM_TEST_MACRO) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_cache.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}_test) endforeach () diff --git a/algorithm/cs302/cache/cache_base.hpp b/algorithm/cs302/cache/cache_base.hpp index b3bcee9b..e1da6c4f 100644 --- a/algorithm/cs302/cache/cache_base.hpp +++ b/algorithm/cs302/cache/cache_base.hpp @@ -1,9 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_CACHE_CACHE_BASE_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_CACHE_CACHE_BASE_HPP +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_CACHE_CACHE_BASE_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_CACHE_CACHE_BASE_HPP #include #include @@ -53,4 +51,4 @@ std::string getFilePath() noexcept { } const std::string CS203_redirect::file_paths = getFilePath(); -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_CACHE_CACHE_BASE_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_CACHE_CACHE_BASE_HPP diff --git a/algorithm/cs302/cache/clock_cache.cpp b/algorithm/cs302/cache/clock_cache.cpp index 2ee716c4..9fb66a0a 100644 --- a/algorithm/cs302/cache/clock_cache.cpp +++ b/algorithm/cs302/cache/clock_cache.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "cache_base.hpp" @@ -21,27 +19,27 @@ static constexpr const auto init = true; namespace initFalse { static constexpr const std::array, 8> pairs{ { - {5, "4.data.in"}, {2, "sample.data.in"}, - {1177, "1.data.in"}, - {11848, "2.data.in"}, - {82382, "3.data.in"}, + {5, "4.data.in"}, {5, "5.data.in"}, {6, "6.data.in"}, {1, "7.data.in"}, + {1177, "1.data.in"}, + {11848, "2.data.in"}, + {82382, "3.data.in"}, }}; } namespace initTrue { static constexpr const std::array, 8> pairs{ { - {2, "4.data.in"}, {1, "sample.data.in"}, - {1193, "1.data.in"}, - {11826, "2.data.in"}, - {82382, "3.data.in"}, + {2, "4.data.in"}, {5, "5.data.in"}, {4, "6.data.in"}, {2, "7.data.in"}, + {1193, "1.data.in"}, + {11826, "2.data.in"}, + {82382, "3.data.in"}, }}; } namespace On { diff --git a/algorithm/cs302/cache/fifo_cache.cpp b/algorithm/cs302/cache/fifo_cache.cpp index f3763d1c..33e8dca6 100644 --- a/algorithm/cs302/cache/fifo_cache.cpp +++ b/algorithm/cs302/cache/fifo_cache.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "cache_base.hpp" @@ -17,13 +15,13 @@ using std::array; static constexpr const std::array, 8> pairs{ { {1, "sample.data.in"}, - {1198, "1.data.in"}, - {11854, "2.data.in"}, - {82363, "3.data.in"}, {2, "4.data.in"}, {5, "5.data.in"}, {4, "6.data.in"}, {2, "7.data.in"}, + {1198, "1.data.in"}, + {11854, "2.data.in"}, + {82363, "3.data.in"}, }}; namespace On { diff --git a/algorithm/cs302/cache/fifo_sc_cache.cpp b/algorithm/cs302/cache/fifo_sc_cache.cpp index 1a66c14c..c7fa9719 100644 --- a/algorithm/cs302/cache/fifo_sc_cache.cpp +++ b/algorithm/cs302/cache/fifo_sc_cache.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "cache_base.hpp" @@ -16,14 +14,14 @@ namespace cache::fifo_sc { using std::array; static constexpr const std::array, 8> pairs{ { - {5, "4.data.in"}, {2, "sample.data.in"}, - {1177, "1.data.in"}, - {11848, "2.data.in"}, - {82382, "3.data.in"}, + {5, "4.data.in"}, {5, "5.data.in"}, {6, "6.data.in"}, {1, "7.data.in"}, + {1177, "1.data.in"}, + {11848, "2.data.in"}, + {82382, "3.data.in"}, }}; namespace On { diff --git a/algorithm/cs302/cache/lru_cache.cpp b/algorithm/cs302/cache/lru_cache.cpp index b022fb85..0e0adc1d 100644 --- a/algorithm/cs302/cache/lru_cache.cpp +++ b/algorithm/cs302/cache/lru_cache.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "cache_base.hpp" @@ -33,13 +31,13 @@ using std::array; static constexpr const std::array, 8> pairs{ { {1, "sample.data.in"}, - {1176, "1.data.in"}, - {11847, "2.data.in"}, - {82394, "3.data.in"}, {4, "4.data.in"}, {3, "5.data.in"}, {5, "6.data.in"}, {1, "7.data.in"}, + {1176, "1.data.in"}, + {11847, "2.data.in"}, + {82394, "3.data.in"}, }}; namespace On { diff --git a/algorithm/cs302/cache/min_cache.cpp b/algorithm/cs302/cache/min_cache.cpp index ff446fee..58f9a6ea 100644 --- a/algorithm/cs302/cache/min_cache.cpp +++ b/algorithm/cs302/cache/min_cache.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "cache_base.hpp" @@ -17,13 +15,13 @@ using std::array; static constexpr const std::array, 8> pairs{ { {2, "sample.data.in"}, - {4240, "1.data.in"}, - {43265, "2.data.in"}, - {88583, "3.data.in"}, {7, "4.data.in"}, {5, "5.data.in"}, {9, "6.data.in"}, {3, "7.data.in"}, + {4240, "1.data.in"}, + {43265, "2.data.in"}, + {88583, "3.data.in"}, }}; /** @@ -98,6 +96,7 @@ TEST_CASE("min test 1") { const auto input = inputs::read_input(); const auto inputAll = [&input] { vector vec{}; + vec.reserve(input.querys.size()); for (const auto ori: input.querys) { vec.push_back(ori); } diff --git a/algorithm/cs302/cache/no_cache.cpp b/algorithm/cs302/cache/no_cache.cpp index 084260bf..758ef14f 100644 --- a/algorithm/cs302/cache/no_cache.cpp +++ b/algorithm/cs302/cache/no_cache.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "cache_base.hpp" diff --git a/algorithm/cs302/cache/s3fifo_cache.cpp b/algorithm/cs302/cache/s3fifo_cache.cpp new file mode 100644 index 00000000..88dffd05 --- /dev/null +++ b/algorithm/cs302/cache/s3fifo_cache.cpp @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO + +#include +#include +#include +#include "cache_base.hpp" + +namespace cache::s3fifo { +using std::array; +static constexpr const std::array, 8> pairs{ + { + {1, "sample.data.in"}, + {4, "4.data.in"}, + {1, "5.data.in"}, + {4, "6.data.in"}, + {0, "7.data.in"}, + {1110, "1.data.in"}, + {11873, "2.data.in"}, + {82132, "3.data.in"}, + // 这种大规模数据集对比lru只差一点点, 性能很好. + // 更贴合实际的数据集应该能更好. + } +}; + +namespace Origin { +// algorithm come from +// https://blog.jasony.me/system/cache/2023/08/01/s3fifo +class fifo_cache final { +public: + std::deque> fifo{}; + size_t max_size{0}; + + explicit fifo_cache(size_t size) { + max_size = std::max(size_t(1), size); + } + + bool exists_const(size_t page) const { + const auto pointer = std::find_if(std::begin(fifo), std::end(fifo), + [page](const std::pair &pair) { + return pair.first == page; + }); + return pointer != std::end(fifo); + } + + bool exists(size_t page) { + const auto pointer = std::find_if(std::begin(fifo), std::end(fifo), + [page](const std::pair &pair) { + return pair.first == page; + }); + if (pointer == std::end(fifo)) { + return false; + } + pointer->second = std::min(3, pointer->second + 1); + return true; + } + + bool isFull() const { + return fifo.size() == max_size; + } + + bool isEmpty() const { + return fifo.empty(); + } + + std::pair pop() { + assert(!fifo.empty()); + const auto result = fifo.front(); + fifo.pop_front(); + return result; + } + + void insert(size_t page, size_t times) { + if (!isFull()) { + fifo.emplace_back(page, times); + } + } +}; + +class s3fifo_cache final : public cache_base { +private: + fifo_cache small; + fifo_cache main; + fifo_cache ghost; + + void insertToSmall(size_t page) { + if (small.isFull()) { + evictSmall(); + } + small.insert(page, 0); + } + + void insertToMain(size_t page, uint8_t times) { + if (main.isFull()) { + evictMain(); + } + main.insert(page, times); + } + + void insertToGhost(size_t page) { + if (!ghost.exists_const(page)) { + // 直接驱逐最后一个 + if (ghost.isFull()) { + ghost.pop(); + } + ghost.insert(page, 0); + } + } + + void evictSmall() { + bool evicted = false; + while (!evicted && !small.isEmpty()) { + const auto result = small.pop(); + if (result.second > 1) { + if (main.isFull()) { + evictMain(); + insertToMain(result.first, 0); + } + } else { + insertToGhost(result.first); + evicted = true; + } + } + } + + void evictMain() { + bool evicted = false; + while (!evicted && !main.isEmpty()) { + const auto result = main.pop(); + if (result.second > 0) { + insertToMain(result.first, result.second - 1); + } else { + evicted = true; + } + } + } + +public: + explicit s3fifo_cache(size_t page) : cache_base(page), small(page / 10), main(page * 9 / 10), + ghost(page * 9 / 10) {} + + virtual bool exists(size_t value) const override { + if (small.exists_const(value) || main.exists_const(value)) { + return true; + } + return false; + } + + // read true if match + virtual bool read(size_t page) override { + if (small.exists(page) || main.exists(page)) { + return true; + } // cache miss + if (ghost.exists_const(page)) { + insertToMain(page, 0); + } else { + insertToSmall(page); + } + return false; + } + + +}; + +TEST_CASE("fifo test n") { + for (const auto &[result, file_name]: pairs) { + const CS203_redirect cr{file_name}; + const auto input = inputs::read_input(); + const auto cache = std::make_unique(input.cacheSize); + size_t hits{0}; + for (const auto iter: input.querys) { + const auto exist = cache->read(iter); + hits += exist; + } + CHECK(result == hits); + } +} +} + +} +#endif diff --git a/algorithm/cs302/disk/CMakeLists.txt b/algorithm/cs302/disk/CMakeLists.txt index 3e5deedd..a751a7e6 100644 --- a/algorithm/cs302/disk/CMakeLists.txt +++ b/algorithm/cs302/disk/CMakeLists.txt @@ -8,8 +8,8 @@ enable_testing() set(dependencies fcfs sstf scan cscan look clook) foreach (elementName IN LISTS dependencies) add_executable(${PROJECT_NAME}_${elementName}_test ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_schedule_disk.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName}_test CS203_DSAA_template_INCLUDE) - target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE CS203_DSAA_TEST_MACRO) + target_link_libraries(${PROJECT_NAME}_${elementName}_test algorithm_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE ALGORITHM_TEST_MACRO) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_schedule_disk.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}_test) endforeach () diff --git a/algorithm/cs302/disk/clook_schedule_disk.cpp b/algorithm/cs302/disk/clook_schedule_disk.cpp index b60e3bd5..c5ca788f 100644 --- a/algorithm/cs302/disk/clook_schedule_disk.cpp +++ b/algorithm/cs302/disk/clook_schedule_disk.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "disk_schedule_base.hpp" diff --git a/algorithm/cs302/disk/cscan_schedule_disk.cpp b/algorithm/cs302/disk/cscan_schedule_disk.cpp index 1d628f56..7eddd1b5 100644 --- a/algorithm/cs302/disk/cscan_schedule_disk.cpp +++ b/algorithm/cs302/disk/cscan_schedule_disk.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "disk_schedule_base.hpp" diff --git a/algorithm/cs302/disk/disk_schedule_base.hpp b/algorithm/cs302/disk/disk_schedule_base.hpp index 45891c17..6b149b64 100644 --- a/algorithm/cs302/disk/disk_schedule_base.hpp +++ b/algorithm/cs302/disk/disk_schedule_base.hpp @@ -1,9 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DISK_SCHEDULE_BASE_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DISK_SCHEDULE_BASE_HPP +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DISK_SCHEDULE_BASE_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DISK_SCHEDULE_BASE_HPP #include #include @@ -61,4 +59,4 @@ std::string getFilePath() noexcept { } const std::string CS203_redirect::file_paths = getFilePath(); -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DISK_SCHEDULE_BASE_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DISK_SCHEDULE_BASE_HPP diff --git a/algorithm/cs302/disk/fcfs_schedule_disk.cpp b/algorithm/cs302/disk/fcfs_schedule_disk.cpp index 0005bc7b..3ef4a319 100644 --- a/algorithm/cs302/disk/fcfs_schedule_disk.cpp +++ b/algorithm/cs302/disk/fcfs_schedule_disk.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "disk_schedule_base.hpp" diff --git a/algorithm/cs302/disk/look_schedule_disk.cpp b/algorithm/cs302/disk/look_schedule_disk.cpp index d245284f..6355a55b 100644 --- a/algorithm/cs302/disk/look_schedule_disk.cpp +++ b/algorithm/cs302/disk/look_schedule_disk.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "disk_schedule_base.hpp" diff --git a/algorithm/cs302/disk/scan_schedule_disk.cpp b/algorithm/cs302/disk/scan_schedule_disk.cpp index a983474d..8bb09cc1 100644 --- a/algorithm/cs302/disk/scan_schedule_disk.cpp +++ b/algorithm/cs302/disk/scan_schedule_disk.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "disk_schedule_base.hpp" diff --git a/algorithm/cs302/disk/sstf_schedule_disk.cpp b/algorithm/cs302/disk/sstf_schedule_disk.cpp index 84afd501..ee7a9896 100644 --- a/algorithm/cs302/disk/sstf_schedule_disk.cpp +++ b/algorithm/cs302/disk/sstf_schedule_disk.cpp @@ -1,8 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2022-2023 nanoseeds -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include "disk_schedule_base.hpp" diff --git a/algorithm/disjoint_set/CMakeLists.txt b/algorithm/disjoint_set/CMakeLists.txt index 3800de95..5baefa46 100644 --- a/algorithm/disjoint_set/CMakeLists.txt +++ b/algorithm/disjoint_set/CMakeLists.txt @@ -5,21 +5,21 @@ set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") add_library(${PROJECT_NAME}_lib ${LIB_WAY} ${CMAKE_CURRENT_SOURCE_DIR}/disjoint_set.cpp) -target_link_libraries(${PROJECT_NAME}_lib PRIVATE CS203_DSAA_template_INCLUDE) +target_link_libraries(${PROJECT_NAME}_lib PRIVATE algorithm_template_INCLUDE) enable_testing() set(dependencies 684 200 130 399 1361) LIST(TRANSFORM dependencies PREPEND leetcode_) -LIST(APPEND dependencies disjoint_set_lnkedlist) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName} ${PROJECT_NAME}_lib CS203_DSAA_template_INCLUDE) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_link_libraries(${PROJECT_NAME}_${elementName} ${PROJECT_NAME}_lib algorithm_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) unset(elementName) endforeach () unset(dependencies) - - +add_executable(${PROJECT_NAME}_lib_set_linkedlist ${CMAKE_CURRENT_SOURCE_DIR}/disjoint_set_linkedlist.cpp) +target_link_libraries(${PROJECT_NAME}_lib_set_linkedlist PRIVATE algorithm_template_INCLUDE) \ No newline at end of file diff --git a/algorithm/disjoint_set/disjoint_set.hpp b/algorithm/disjoint_set/disjoint_set.hpp index 2852f504..41661c69 100644 --- a/algorithm/disjoint_set/disjoint_set.hpp +++ b/algorithm/disjoint_set/disjoint_set.hpp @@ -1,12 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_HPP #include #include @@ -16,7 +11,7 @@ Copyright (C) 2020-2023 nanos namespace disjoint_set { using std::vector; -class disjoint_set : private nonCopyMoveAble{ +class disjoint_set : private nonCopyMoveAble { public: virtual ~disjoint_set() = default; @@ -32,4 +27,4 @@ std::unique_ptr getDisjointSet(size_t x); } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_HPP diff --git a/algorithm/disjoint_set/disjoint_set_lnkedlist.cpp b/algorithm/disjoint_set/disjoint_set_linkedlist.cpp similarity index 99% rename from algorithm/disjoint_set/disjoint_set_lnkedlist.cpp rename to algorithm/disjoint_set/disjoint_set_linkedlist.cpp index 348fd8c9..9d1646d3 100644 --- a/algorithm/disjoint_set/disjoint_set_lnkedlist.cpp +++ b/algorithm/disjoint_set/disjoint_set_linkedlist.cpp @@ -2,9 +2,10 @@ // Created by nanos on 2021/11/9. // +#include "disjoint_set_linkedlist.hpp" #include #include -#include "disjoint_set_linkedlist.hpp" +#include namespace disjoint_set { namespace linkedlist { diff --git a/algorithm/disjoint_set/disjoint_set_linkedlist.hpp b/algorithm/disjoint_set/disjoint_set_linkedlist.hpp index 633fef13..f196bb9f 100644 --- a/algorithm/disjoint_set/disjoint_set_linkedlist.hpp +++ b/algorithm/disjoint_set/disjoint_set_linkedlist.hpp @@ -1,16 +1,13 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_LINKEDLIST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_LINKEDLIST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_LINKEDLIST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_LINKEDLIST_HPP #include -#include +#include +#include +#include "class_helper/nonable.hpp" namespace disjoint_set { namespace linkedlist { @@ -34,4 +31,4 @@ class base { }; } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_LINKEDLIST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DISJOINT_SET_DISJOINT_SET_LINKEDLIST_HPP diff --git a/algorithm/disjoint_set/leetcode_130.cpp b/algorithm/disjoint_set/leetcode_130.cpp index a2a8a196..5345de7a 100644 --- a/algorithm/disjoint_set/leetcode_130.cpp +++ b/algorithm/disjoint_set/leetcode_130.cpp @@ -1,74 +1,90 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_130_test.hpp" #include "disjoint_set.hpp" +#include "disjoint_set.cpp" #include #include #include +#include +#include namespace leetcode_130 { using std::string; using disjoint_set::disjoint_set; using std::unordered_set, std::stack; +using std::vector; +#endif -void leetcode_130::solve(vector> &board) { - if (board.empty() || board.front().empty()) { - return; - } - const auto x_size{board.size()}, - y_size{board.front().size()}; - vector> results{board}; - const auto visit = [&results, x_size, y_size](auto x, auto y) { - if (results[x][y] != GRID::LAND) { +enum GRID : char { + WATER = 'X', + LAND = 'O', + KEEP_LAND = 'K', +}; + +class Solution { +public: + void solve(vector> &board) { + if (board.empty() || board.front().empty()) { return; } - results[x][y] = GRID::KEEP_LAND; - stack> points{{{x, y}}}; - while (!points.empty()) { - const auto head = points.top(); - points.pop(); - vector> will_visit{}; - if (head.first > 0) { - will_visit.emplace_back(head.first - 1, head.second); - } - if (head.first < x_size - 1) { - will_visit.emplace_back(head.first + 1, head.second); + const auto x_size{board.size()}, + y_size{board.front().size()}; + vector> results{board}; + const auto visit = [&results, x_size, y_size](auto x, auto y) { + if (results[x][y] != GRID::LAND) { + return; } - if (head.second > 0) { - will_visit.emplace_back(head.first, head.second - 1); - } - if (head.second < y_size - 1) { - will_visit.emplace_back(head.first, head.second + 1); - } - for (const auto &point: will_visit) { - const auto[x1, y1] = point; - if (results[x1][y1] == GRID::LAND) { - results[x1][y1] = GRID::KEEP_LAND; - points.emplace(x1, y1); + results[x][y] = GRID::KEEP_LAND; + stack> points{{{x, y}}}; + while (!points.empty()) { + const auto head = points.top(); + points.pop(); + vector> will_visit{}; + if (head.first > 0) { + will_visit.emplace_back(head.first - 1, head.second); + } + if (head.first < x_size - 1) { + will_visit.emplace_back(head.first + 1, head.second); + } + if (head.second > 0) { + will_visit.emplace_back(head.first, head.second - 1); + } + if (head.second < y_size - 1) { + will_visit.emplace_back(head.first, head.second + 1); + } + for (const auto &point: will_visit) { + const auto [x1, y1] = point; + if (results[x1][y1] == GRID::LAND) { + results[x1][y1] = GRID::KEEP_LAND; + points.emplace(x1, y1); + } } } + }; + for (size_t i{0}; i < y_size; i++) { + visit(0, i); + visit(x_size - 1, i); } - }; - for (size_t i{0}; i < y_size; i++) { - visit(0, i); - visit(x_size - 1, i); - } - for (size_t i{1}; i < x_size - 1; i++) { // // [0,0] => [0,y_size-1] - visit(i, 0); - visit(i, y_size - 1); - } - for (size_t i{0}; i < x_size; i++) { - for (size_t j{0}; j < y_size; j++) { - if (results[i][j] == GRID::LAND) { - board[i][j] = GRID::WATER; + for (size_t i{1}; i < x_size - 1; i++) { // // [0,0] => [0,y_size-1] + visit(i, 0); + visit(i, y_size - 1); + } + for (size_t i{0}; i < x_size; i++) { + for (size_t j{0}; j < y_size; j++) { + if (results[i][j] == GRID::LAND) { + board[i][j] = GRID::WATER; + } } } } -} +}; +/* +if the number is not so big, it's better to use brute force, +if number > 50,choose hashmap. + */ +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/disjoint_set/leetcode_130_test.cpp b/algorithm/disjoint_set/leetcode_130_test.cpp new file mode 100644 index 00000000..6c1432d5 --- /dev/null +++ b/algorithm/disjoint_set/leetcode_130_test.cpp @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag disjoint_set +//@Tag 深度优先搜索 +//@Tag DFS +//@Tag 广度优先搜索 +//@Tag BFS + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_130_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_130_TEST_CPP + +#include +#include "leetcode_130.cpp" + +namespace leetcode_130 { +using std::vector; + +using Catch::Matchers::Equals; + +TEST_CASE("1 [test_130]", "[test_130]") { + vector> edges{ + {GRID::WATER, GRID::WATER, GRID::WATER, GRID::WATER}, + {GRID::WATER, GRID::LAND, GRID::LAND, GRID::WATER}, + {GRID::WATER, GRID::WATER, GRID::LAND, GRID::WATER}, + {GRID::WATER, GRID::LAND, GRID::WATER, GRID::WATER}, + }; + const vector> results{ + {GRID::WATER, GRID::WATER, GRID::WATER, GRID::WATER}, + {GRID::WATER, GRID::WATER, GRID::WATER, GRID::WATER}, + {GRID::WATER, GRID::WATER, GRID::WATER, GRID::WATER}, + {GRID::WATER, GRID::LAND, GRID::WATER, GRID::WATER}, + }; + Solution solution; + solution.solve(edges); + CHECK_THAT(results, Equals(edges)); +} + +TEST_CASE("2 [test_130]", "[test_130]") { + vector> edges{ + {GRID::WATER} + }; + const vector> results{ + {GRID::WATER} + }; + Solution solution; + solution.solve(edges); + CHECK_THAT(results, Equals(edges)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_130_TEST_CPP diff --git a/algorithm/disjoint_set/leetcode_130_test.hpp b/algorithm/disjoint_set/leetcode_130_test.hpp deleted file mode 100644 index 6b5255f0..00000000 --- a/algorithm/disjoint_set/leetcode_130_test.hpp +++ /dev/null @@ -1,65 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag disjoint_set -//@Tag 深度优先搜索 -//@Tag DFS -//@Tag 广度优先搜索 -//@Tag BFS - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_130_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_130_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_130 { -using std::vector; -enum GRID : char { - WATER = 'X', - LAND = 'O', - KEEP_LAND = 'K', -}; - -struct leetcode_130 { - static void solve(vector> &board); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("1 [test_130]", "[test_130]") { - vector> edges{ - {WATER, WATER, WATER, WATER}, - {WATER, LAND, LAND, WATER}, - {WATER, WATER, LAND, WATER}, - {WATER, LAND, WATER, WATER}, - }; - const vector> results{ - {WATER, WATER, WATER, WATER}, - {WATER, WATER, WATER, WATER}, - {WATER, WATER, WATER, WATER}, - {WATER, LAND, WATER, WATER}, - }; - leetcode_130::solve(edges); - CHECK_THAT(results, Equals(edges)); -} - -TEST_CASE("2 [test_130]", "[test_130]") { - vector> edges{ - {WATER} - }; - const vector> results{ - {WATER} - }; - leetcode_130::solve(edges); - CHECK_THAT(results, Equals(edges)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_130_TEST_CPP diff --git a/algorithm/disjoint_set/leetcode_1361.cpp b/algorithm/disjoint_set/leetcode_1361.cpp index ce09c277..5d5ed299 100644 --- a/algorithm/disjoint_set/leetcode_1361.cpp +++ b/algorithm/disjoint_set/leetcode_1361.cpp @@ -1,17 +1,18 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_1361_test.hpp" #include "disjoint_set.hpp" +#include "disjoint_set.cpp" #include +#include +#include namespace leetcode_1361 { using ::disjoint_set::disjoint_set; using ::disjoint_set::getDisjointSet; +using std::vector; +#endif // 二叉树上x个节点应该有x-1条边 bool simpleCheck(int32_t n, const vector &leftChild, const vector &rightChild) { @@ -22,57 +23,62 @@ bool simpleCheck(int32_t n, const vector &leftChild, const vector &leftChild, const vector &rightChild) { - if (!simpleCheck(n, leftChild, rightChild)) { - return false; - } - vector in_position(n, -1); - for (int32_t i{0}; i < n; i++) { - if (leftChild[i] != -1) { - if (in_position[leftChild[i]] == -1) { - in_position[leftChild[i]] = i; - } else { - return false; - } +class Solution { +public: + bool + validateBinaryTreeNodes(int32_t n, const vector &leftChild, const vector &rightChild) { + if (!simpleCheck(n, leftChild, rightChild)) { + return false; } - if (rightChild[i] != -1) { - if (in_position[rightChild[i]] != -1) { - return false; + vector in_position(n, -1); + for (int32_t i{0}; i < n; i++) { + if (leftChild[i] != -1) { + if (in_position[leftChild[i]] == -1) { + in_position[leftChild[i]] = i; + } else { + return false; + } } - in_position[rightChild[i]] = i; - } - } // 父节点不能有多个 - // O(n) - int32_t count{-1}; - for (int32_t i{0}; i < n; i++) { - if (in_position[i] == -1) { - if (count != -1) {// 循环节点不会被扫描到, 因为它们有子节点也有父节点 - return false; + if (rightChild[i] != -1) { + if (in_position[rightChild[i]] != -1) { + return false; + } + in_position[rightChild[i]] = i; + } + } // 父节点不能有多个 + // O(n) + int32_t count{-1}; + for (int32_t i{0}; i < n; i++) { + if (in_position[i] == -1) { + if (count != -1) {// 循环节点不会被扫描到, 因为它们有子节点也有父节点 + return false; + } + count = i; + } + }// 只能有一个根节点 + // count must be root + // O(n) + int32_t visit_nums{0}; + for (std::queue que{{count}}; !que.empty();) { + const auto head = que.front(); + que.pop(); + visit_nums += 1; + if (leftChild[head] != -1) { + que.push(leftChild[head]); + } + if (rightChild[head] != -1) { + que.push(rightChild[head]); } - count = i; - } - }// 只能有一个根节点 - // count must be root - // O(n) - int32_t visit_nums{0}; - for (std::queue que{{count}}; !que.empty();) { - const auto head = que.front(); - que.pop(); - visit_nums += 1; - if (leftChild[head] != -1) { - que.push(leftChild[head]); } - if (rightChild[head] != -1) { - que.push(rightChild[head]); + // O(n) + //根节点遍历必须得能遍历到所有节点 + if (visit_nums != n) { + return false; } + return true; } - // O(n) - //根节点遍历必须得能遍历到所有节点 - if (visit_nums != n) { - return false; - } - return true; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/disjoint_set/leetcode_1361_test.hpp b/algorithm/disjoint_set/leetcode_1361_test.cpp similarity index 55% rename from algorithm/disjoint_set/leetcode_1361_test.hpp rename to algorithm/disjoint_set/leetcode_1361_test.cpp index ef71358a..a4db513b 100644 --- a/algorithm/disjoint_set/leetcode_1361_test.hpp +++ b/algorithm/disjoint_set/leetcode_1361_test.cpp @@ -1,68 +1,63 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanos - -*/ +// SPDX-FileCopyrightText: 2023-2025 nanoseeds //@Tag disjoint_set //@Tag 并查集 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1361_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1361_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1361_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1361_TEST_CPP #include -#include -#include -#include +#include "leetcode_1361.cpp" namespace leetcode_1361 { using std::vector; -namespace leetcode_1361 { -bool validateBinaryTreeNodes(int32_t n, const vector &leftChild, const vector &rightChild); - -} - TEST_CASE("1 [test_1361]", "[test_1361]") { constexpr const auto n{4}; const vector left{1, -1, 3, -1}, right{2, -1, -1, -1}; - CHECK(leetcode_1361::validateBinaryTreeNodes(n, left, right)); + Solution solution; + CHECK(solution.validateBinaryTreeNodes(n, left, right)); } TEST_CASE("2 [test_1361]", "[test_1361]") { constexpr const auto n{4}; const vector left{1, -1, 3, -1}, right{2, 3, -1, -1}; - CHECK_FALSE(leetcode_1361::validateBinaryTreeNodes(n, left, right)); + Solution solution; + CHECK_FALSE(solution.validateBinaryTreeNodes(n, left, right)); } TEST_CASE("3 [test_1361]", "[test_1361]") { constexpr const auto n{2}; const vector left{1, 0}, right{-1, -1}; - CHECK_FALSE(leetcode_1361::validateBinaryTreeNodes(n, left, right)); + Solution solution; + CHECK_FALSE(solution.validateBinaryTreeNodes(n, left, right)); } TEST_CASE("4 [test_1361]", "[test_1361]") { constexpr const auto n{6}; const vector left{1, -1, -1, 4, -1, -1}, right{2, -1, -1, 5, -1, -1}; - CHECK_FALSE(leetcode_1361::validateBinaryTreeNodes(n, left, right)); + Solution solution; + CHECK_FALSE(solution.validateBinaryTreeNodes(n, left, right)); } TEST_CASE("5 [test_1361]", "[test_1361]") { constexpr const auto n{3}; const vector left{1, -1, -1}, right{-1, -1, 1}; - CHECK_FALSE(leetcode_1361::validateBinaryTreeNodes(n, left, right)); + Solution solution; + CHECK_FALSE(solution.validateBinaryTreeNodes(n, left, right)); } TEST_CASE("6 [test_1361]", "[test_1361]") { constexpr const auto n{4}; const vector left{3, -1, 1, -1}, right{-1, -1, 0, -1}; - CHECK(leetcode_1361::validateBinaryTreeNodes(n, left, right)); + Solution solution; + CHECK(solution.validateBinaryTreeNodes(n, left, right)); } TEST_CASE("7 [test_1361]", "[test_1361]") { constexpr const auto n{4}; const vector left{1, 0, 3, -1}, right{-1, -1, -1, -1}; - CHECK_FALSE(leetcode_1361::validateBinaryTreeNodes(n, left, right)); + Solution solution; + CHECK_FALSE(solution.validateBinaryTreeNodes(n, left, right)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1361_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1361_TEST_CPP diff --git a/algorithm/disjoint_set/leetcode_200.cpp b/algorithm/disjoint_set/leetcode_200.cpp index 3d6d5799..0cdad0f3 100644 --- a/algorithm/disjoint_set/leetcode_200.cpp +++ b/algorithm/disjoint_set/leetcode_200.cpp @@ -1,58 +1,69 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_200_test.hpp" #include "disjoint_set.hpp" +#include "disjoint_set.cpp" #include #include +#include +#include namespace leetcode_200 { using std::string; using ::disjoint_set::disjoint_set; using ::disjoint_set::getDisjointSet; using std::unordered_set; +using std::vector; +#endif -int leetcode_200::numIslands(const vector> &grid) { - if (grid.empty() || grid.back().empty()) { - return 0; - } - const auto x_size{grid.size()}, y_size{grid.back().size()}; - vector> grids(x_size + 1, vector(y_size + 1, 0)); - for (size_t i{0}; i < x_size; i++) { - for (size_t j{0}; j < y_size; j++) { - grids[i][j] = grid[i][j]; +enum GRID : char { + WATER = '0', + LAND = '1' +}; + +class Solution { +public: + int numIslands(const vector> &grid) { + if (grid.empty() || grid.back().empty()) { + return 0; } - } - const auto x_size2{x_size + 1}, y_size2{y_size + 1}, grid_size2{x_size2 * y_size2}; - const auto loca = [y_size2](auto x, auto y) { - return x * y_size2 + y + 1; - }; - const auto jset = getDisjointSet(grid_size2); - for (size_t i{0}; i < x_size; ++i) { - for (size_t j{0}; j < y_size; ++j) { - if (grids[i][j] == GRID::LAND) { - if (grids[i + 1][j] == GRID::LAND) { - jset->merge(loca(i + 1, j), loca(i, j)); - } - if (grids[i][j + 1] == GRID::LAND) { - jset->merge(loca(i, j + 1), loca(i, j)); + const auto x_size{grid.size()}, y_size{grid.back().size()}; + vector> grids(x_size + 1, vector(y_size + 1, 0)); + for (size_t i{0}; i < x_size; i++) { + for (size_t j{0}; j < y_size; j++) { + grids[i][j] = grid[i][j]; + } + } + const auto x_size2{x_size + 1}, y_size2{y_size + 1}, grid_size2{x_size2 * y_size2}; + const auto loca = [y_size2](auto x, auto y) { + return x * y_size2 + y + 1; + }; + const auto jset = getDisjointSet(grid_size2); + for (size_t i{0}; i < x_size; ++i) { + for (size_t j{0}; j < y_size; ++j) { + if (grids[i][j] == GRID::LAND) { + if (grids[i + 1][j] == GRID::LAND) { + jset->merge(loca(i + 1, j), loca(i, j)); + } + if (grids[i][j + 1] == GRID::LAND) { + jset->merge(loca(i, j + 1), loca(i, j)); + } } } } - } - std::unordered_set uset; - for (size_t i{0}; i < x_size; ++i) { - for (size_t j{0}; j < y_size; ++j) { - if (grids[i][j] == GRID::LAND) { - uset.insert(jset->find(loca(i, j))); + std::unordered_set uset; + for (size_t i{0}; i < x_size; ++i) { + for (size_t j{0}; j < y_size; ++j) { + if (grids[i][j] == GRID::LAND) { + uset.insert(jset->find(loca(i, j))); + } } } + return uset.size(); } - return uset.size(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/disjoint_set/leetcode_200_test.cpp b/algorithm/disjoint_set/leetcode_200_test.cpp new file mode 100644 index 00000000..fc01b225 --- /dev/null +++ b/algorithm/disjoint_set/leetcode_200_test.cpp @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag disjoint_set +//@Tag 并查集 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_200_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_200_TEST_CPP + +#include +#include "leetcode_200.cpp" + +namespace leetcode_200 { +using std::vector; + +using Catch::Matchers::Equals; + +TEST_CASE("1 [test_200]", "[test_200]") { + vector> edges{ + {GRID::LAND, GRID::LAND, GRID::LAND, GRID::LAND, GRID::WATER}, + {GRID::LAND, GRID::LAND, GRID::WATER, GRID::LAND, GRID::WATER}, + {GRID::LAND, GRID::LAND, GRID::WATER, GRID::WATER, GRID::WATER}, + {GRID::WATER, GRID::WATER, GRID::WATER, GRID::WATER, GRID::WATER}, + }; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.numIslands(edges)); + +} + +TEST_CASE("2 [test_200]", "[test_200]") { + const vector> edges{ + {GRID::LAND, GRID::LAND, GRID::WATER, GRID::WATER, GRID::WATER}, + {GRID::LAND, GRID::LAND, GRID::WATER, GRID::WATER, GRID::WATER}, + {GRID::WATER, GRID::WATER, GRID::LAND, GRID::WATER, GRID::WATER}, + {GRID::WATER, GRID::WATER, GRID::WATER, GRID::LAND, GRID::LAND} + }; + static constexpr const auto result{3}; + Solution solution; + CHECK(result == solution.numIslands(edges)); +} + +TEST_CASE("3 [test_200]", "[test_200]") { + const vector> edges{ + {GRID::LAND, GRID::WATER, GRID::WATER}, + {GRID::WATER, GRID::WATER, GRID::WATER}, + {GRID::WATER, GRID::WATER, GRID::LAND} + }; + static constexpr const auto result{2}; + Solution solution; + CHECK(result == solution.numIslands(edges)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_200_TEST_CPP diff --git a/algorithm/disjoint_set/leetcode_200_test.hpp b/algorithm/disjoint_set/leetcode_200_test.hpp deleted file mode 100644 index 11b2b6c1..00000000 --- a/algorithm/disjoint_set/leetcode_200_test.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag disjoint_set -//@Tag 并查集 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_200_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_200_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_200 { -using std::vector; -enum GRID : char { - WATER = '0', - LAND = '1' -}; - -struct leetcode_200 { - static int numIslands(const vector> &grid); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("1 [test_200]", "[test_200]") { - vector> edges{ - {LAND, LAND, LAND, LAND, WATER}, - {LAND, LAND, WATER, LAND, WATER}, - {LAND, LAND, WATER, WATER, WATER}, - {WATER, WATER, WATER, WATER, WATER}, - }; - static constexpr const auto result{1}; - CHECK(result == leetcode_200::numIslands(edges)); - -} - -TEST_CASE("2 [test_200]", "[test_200]") { - const vector> edges{ - {LAND, LAND, WATER, WATER, WATER}, - {LAND, LAND, WATER, WATER, WATER}, - {WATER, WATER, LAND, WATER, WATER}, - {WATER, WATER, WATER, LAND, LAND} - }; - static constexpr const auto result{3}; - CHECK(result == leetcode_200::numIslands(edges)); -} - -TEST_CASE("3 [test_200]", "[test_200]") { - const vector> edges{ - {LAND, WATER, WATER}, - {WATER, WATER, WATER}, - {WATER, WATER, LAND} - }; - static constexpr const auto result{2}; - CHECK(result == leetcode_200::numIslands(edges)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_200_TEST_CPP diff --git a/algorithm/disjoint_set/leetcode_399.cpp b/algorithm/disjoint_set/leetcode_399.cpp index c0b3b8aa..b2dde715 100644 --- a/algorithm/disjoint_set/leetcode_399.cpp +++ b/algorithm/disjoint_set/leetcode_399.cpp @@ -1,13 +1,19 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_399_test.hpp" #include #include +#include +#include +#include +#include + +namespace leetcode_399 { +using std::unordered_map; +using std::string; +using std::vector; +#endif namespace disjoint_set_weight { // 节点之间是一张 有向无环图 @@ -55,50 +61,50 @@ class disjoint_set final { }; } -namespace leetcode_399 { -using disjoint_set_weight::disjoint_set; -using std::unordered_map; - -vector leetcode_399::calcEquation(const vector> &equations, const vector &values, - const vector> &queries) { - unordered_map str_to_num{}; - for (const auto &pair: equations) { - for (const auto &str: pair) { - if (str_to_num.count(str) == 0) { - str_to_num.emplace(str, str_to_num.size() + 1); +class Solution { +public: + vector calcEquation(const vector> &equations, const vector &values, + const vector> &queries) { + unordered_map str_to_num{}; + for (const auto &pair: equations) { + for (const auto &str: pair) { + if (str_to_num.count(str) == 0) { + str_to_num.emplace(str, str_to_num.size() + 1); + } } } - } - disjoint_set dset(str_to_num.size()); - for (size_t i{0}; i < equations.size(); i++) { - const auto &pair = equations[i]; - const auto first{str_to_num[pair[0]]}, - second{str_to_num[pair[1]]}; - dset.merge(first, second, values[i]); - } - vector results(queries.size(), -1); - for (size_t i{0}; i < queries.size(); i++) { - const auto &query{queries[i]}; - const auto &first{query[0]}, second{query[1]}; - if (str_to_num.count(first) == 0 || str_to_num.count(second) == 0) { - continue; + disjoint_set_weight::disjoint_set dset(str_to_num.size()); + for (size_t i{0}; i < equations.size(); i++) { + const auto &pair = equations[i]; + const auto first{str_to_num[pair[0]]}, + second{str_to_num[pair[1]]}; + dset.merge(first, second, values[i]); } - const auto firstNum{str_to_num[first]}, - secondNum{str_to_num[second]}; - if (dset.find(firstNum) != dset.find(secondNum)) { - continue; - } - if (firstNum == secondNum) { - results[i] = 1.0f; - continue; + vector results(queries.size(), -1); + for (size_t i{0}; i < queries.size(); i++) { + const auto &query{queries[i]}; + const auto &first{query[0]}, second{query[1]}; + if (str_to_num.count(first) == 0 || str_to_num.count(second) == 0) { + continue; + } + const auto firstNum{str_to_num[first]}, + secondNum{str_to_num[second]}; + if (dset.find(firstNum) != dset.find(secondNum)) { + continue; + } + if (firstNum == secondNum) { + results[i] = 1.0f; + continue; + } + auto multiOne{dset.findWeight(firstNum)}, + multiTwo{dset.findWeight(secondNum)}; + results[i] = multiOne / multiTwo; } - auto multiOne{dset.findWeight(firstNum)}, - multiTwo{dset.findWeight(secondNum)}; - results[i] = multiOne / multiTwo; - } - - return results; -} + return results; + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/disjoint_set/leetcode_399_test.hpp b/algorithm/disjoint_set/leetcode_399_test.cpp similarity index 71% rename from algorithm/disjoint_set/leetcode_399_test.hpp rename to algorithm/disjoint_set/leetcode_399_test.cpp index 73957ab3..e4a60ca9 100644 --- a/algorithm/disjoint_set/leetcode_399_test.hpp +++ b/algorithm/disjoint_set/leetcode_399_test.cpp @@ -1,32 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag disjoint_set //@Tag 并查集 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_399_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_399_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_399_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_399_TEST_CPP #include -#include -#include -#include -#include -#include +#include "leetcode_399.cpp" namespace leetcode_399 { using std::string; using std::vector; -struct leetcode_399 { - static vector - calcEquation(const vector> &equations, const vector &values, - const vector> &queries); -}; - using Catch::Matchers::ApproxMatcher; using Catch::Matchers::Approx; @@ -44,7 +29,8 @@ TEST_CASE("1 [test_399]", "[test_399]") { {"x", "x"}, }; const vector results{6.0f, 0.5f, -1.0f, 1.0f, -1.0f}; - CHECK_THAT(results, Approx(leetcode_399::calcEquation(edges, values, queries)).epsilon(0.01f)); + Solution solution; + CHECK_THAT(results, Approx(solution.calcEquation(edges, values, queries)).epsilon(0.01f)); } TEST_CASE("2 [test_399]", "[test_399]") { @@ -59,7 +45,8 @@ TEST_CASE("2 [test_399]", "[test_399]") { {"x", "y"}, }; const vector results{0.5f, 2.0f, -1.0f, -1.0f}; - CHECK_THAT(results, Approx(leetcode_399::calcEquation(edges, values, queries)).epsilon(0.01f)); + Solution solution; + CHECK_THAT(results, Approx(solution.calcEquation(edges, values, queries)).epsilon(0.01f)); } TEST_CASE("3 [test_399]", "[test_399]") { @@ -76,7 +63,8 @@ TEST_CASE("3 [test_399]", "[test_399]") { {"cd", "bc"}, }; const vector results{3.75f, 0.4f, 5.0f, 0.2f}; - CHECK_THAT(results, Approx(leetcode_399::calcEquation(edges, values, queries)).epsilon(0.01f)); + Solution solution; + CHECK_THAT(results, Approx(solution.calcEquation(edges, values, queries)).epsilon(0.01f)); } @@ -100,7 +88,8 @@ TEST_CASE("5 [test_399]", "[test_399]") { {"x0", "x0"}, }; const vector results{1.13333, 16.8, 1.5, 1.0, 0.05952, 2.26667, 0.44118, -1.0, -1.0}; - CHECK_THAT(results, Approx(leetcode_399::calcEquation(edges, values, queries)).epsilon(0.01f)); + Solution solution; + CHECK_THAT(results, Approx(solution.calcEquation(edges, values, queries)).epsilon(0.01f)); } TEST_CASE("4 [test_399]", "[test_399]") { @@ -115,7 +104,8 @@ TEST_CASE("4 [test_399]", "[test_399]") { {"x", "x"}, }; const vector results{1.3333f, 1.0f, -1.0f}; - CHECK_THAT(results, Approx(leetcode_399::calcEquation(edges, values, queries)).epsilon(0.01f)); + Solution solution; + CHECK_THAT(results, Approx(solution.calcEquation(edges, values, queries)).epsilon(0.01f)); } TEST_CASE("6 [test_399]", "[test_399]") { @@ -130,7 +120,8 @@ TEST_CASE("6 [test_399]", "[test_399]") { {"x", "x"}, }; const vector results{1.3333f, 1.0f, -1.0f}; - CHECK_THAT(results, Approx(leetcode_399::calcEquation(edges, values, queries)).epsilon(0.01f)); + Solution solution; + CHECK_THAT(results, Approx(solution.calcEquation(edges, values, queries)).epsilon(0.01f)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_399_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_399_TEST_CPP diff --git a/algorithm/disjoint_set/leetcode_684.cpp b/algorithm/disjoint_set/leetcode_684.cpp index 6be5d1db..b8f54181 100644 --- a/algorithm/disjoint_set/leetcode_684.cpp +++ b/algorithm/disjoint_set/leetcode_684.cpp @@ -1,28 +1,34 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_684_test.hpp" #include "disjoint_set.hpp" +#include "disjoint_set.cpp" + +#include namespace leetcode_684 { using ::disjoint_set::disjoint_set; using ::disjoint_set::getDisjointSet; +using std::vector; +#endif -vector leetcode_684::findRedundantConnection(const vector> &edges) { - const auto edge_sizes{edges.size()}; - const auto jset = getDisjointSet(edge_sizes); - for (const auto &edge: edges) { - if (jset->find(edge[0]) != jset->find(edge[1])) { - jset->merge(edge[0], edge[1]); - } else { - return edge; +class Solution { +public: + vector findRedundantConnection(const vector> &edges) { + const auto edge_sizes{edges.size()}; + const auto jset = getDisjointSet(edge_sizes); + for (const auto &edge: edges) { + if (jset->find(edge[0]) != jset->find(edge[1])) { + jset->merge(edge[0], edge[1]); + } else { + return edge; + } } + return {}; } - return {}; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/disjoint_set/leetcode_684_test.hpp b/algorithm/disjoint_set/leetcode_684_test.cpp similarity index 56% rename from algorithm/disjoint_set/leetcode_684_test.hpp rename to algorithm/disjoint_set/leetcode_684_test.cpp index caf5c814..ac3a404a 100644 --- a/algorithm/disjoint_set/leetcode_684_test.hpp +++ b/algorithm/disjoint_set/leetcode_684_test.cpp @@ -1,27 +1,16 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag disjoint_set //@Tag 并查集 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_684_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_684_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_684_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_684_TEST_CPP #include -#include -#include -#include +#include "leetcode_684.cpp" namespace leetcode_684 { using std::vector; -struct leetcode_684 { - static vector findRedundantConnection(const vector> &edges); -}; - using Catch::Matchers::Equals; TEST_CASE("1 [test_684]", "[test_684]") { @@ -29,7 +18,8 @@ TEST_CASE("1 [test_684]", "[test_684]") { {1, 3}, {2, 3}}; const vector results{2, 3}; - CHECK_THAT(leetcode_684::findRedundantConnection(edges), Equals(results)); + Solution solution; + CHECK_THAT(solution.findRedundantConnection(edges), Equals(results)); } TEST_CASE("2 [test_684]", "[test_684]") { @@ -39,8 +29,9 @@ TEST_CASE("2 [test_684]", "[test_684]") { {1, 4}, {1, 5}}; const vector results{1, 4}; - CHECK_THAT(leetcode_684::findRedundantConnection(edges), Equals(results)); + Solution solution; + CHECK_THAT(solution.findRedundantConnection(edges), Equals(results)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_684_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_684_TEST_CPP diff --git a/algorithm/divide_merge/CMakeLists.txt b/algorithm/divide_merge/CMakeLists.txt index e4f8028f..9e9f158f 100644 --- a/algorithm/divide_merge/CMakeLists.txt +++ b/algorithm/divide_merge/CMakeLists.txt @@ -9,9 +9,10 @@ set(dependencies 53) LIST(TRANSFORM dependencies PREPEND leetcode_) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) unset(elementName) endforeach () diff --git a/algorithm/divide_merge/leetcode_53.cpp b/algorithm/divide_merge/leetcode_53.cpp index 38985630..2c6c441b 100644 --- a/algorithm/divide_merge/leetcode_53.cpp +++ b/algorithm/divide_merge/leetcode_53.cpp @@ -1,54 +1,67 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_53_test.hpp" +#include +#include +#include +#include +#include namespace leetcode_53 { -// [begin,end) -int32_t maxSubArray(const vector &nums, size_t begin, size_t end) { - if (begin + 1 == end) { - return nums[begin]; - } - const auto half{begin + (end - begin) / 2}; - const auto left{maxSubArray(nums, begin, half)}, - right{maxSubArray(nums, half, end)}; - int32_t max_left{-0x3f3f3f3f}, left_sum{0}, max_right{-0x3f3f3f3f}, right_sum{0}; - for (size_t left_order{half}; left_order >= begin + 1; left_order--) { - // 无符号数判断的时候不要-1 > 0, 而是用 > 1 - left_sum += nums[left_order - 1]; - max_left = std::max(max_left, left_sum); - } - for (size_t right_order{half}; right_order < end; right_order++) { - right_sum += nums[right_order]; - max_right = std::max(max_right, right_sum); - } - return std::max({left, right, max_left + max_right}); -} +using std::string; +using std::vector; +using std::max; +#endif -int32_t leetcode_53::maxSubArray(const vector &nums) { - return ::leetcode_53::maxSubArray(nums, 0, nums.size()); -} +class Solution { +private: + // [begin,end) + int32_t maxSubArrayHelper(const vector &nums, size_t begin, size_t end) { + if (begin + 1 == end) { + return nums[begin]; + } + const auto half{begin + (end - begin) / 2}; + const auto left{maxSubArrayHelper(nums, begin, half)}, + right{maxSubArrayHelper(nums, half, end)}; + int32_t max_left{-0x3f3f3f3f}, left_sum{0}, max_right{-0x3f3f3f3f}, right_sum{0}; + for (size_t left_order{half}; left_order >= begin + 1; left_order--) { + // 无符号数判断的时候不要-1 > 0, 而是用 > 1 + left_sum += nums[left_order - 1]; + max_left = std::max(max_left, left_sum); + } + for (size_t right_order{half}; right_order < end; right_order++) { + right_sum += nums[right_order]; + max_right = std::max(max_right, right_sum); + } + return std::max({left, right, max_left + max_right}); + } -int32_t leetcode_53::maxSubArray2(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size == 1) { - return nums[0]; +public: + int32_t maxSubArray(const vector &nums) { + return maxSubArrayHelper(nums, 0, nums.size()); } - vector dp(nums_size + 1, 0); - // dp[i] 考虑前第i个的最大值 X 带有第i个的最大值 √(不然不能直接用dp[i-1]+nums[i-1]) - // 若带前面的,则为 dp[i-1]+nums[i-1] - // 若不带前面的,则为 nums[i-1] - dp[0] = 0; // 选0个一定为0 - dp[1] = nums[0]; // 只选一个肯定是nums[0] - int32_t maxV{nums[0]}; - for (size_t i{2}; i <= nums_size; i++) { - dp[i] = std::max(nums[i - 1], dp[i - 1] + nums[i - 1]); - maxV = std::max(maxV, dp[i]); + + int32_t maxSubArray2(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size == 1) { + return nums[0]; + } + vector dp(nums_size + 1, 0); + // dp[i] 考虑前第i个的最大值 X 带有第i个的最大值 √(不然不能直接用dp[i-1]+nums[i-1]) + // 若带前面的,则为 dp[i-1]+nums[i-1] + // 若不带前面的,则为 nums[i-1] + dp[0] = 0; // 选0个一定为0 + dp[1] = nums[0]; // 只选一个肯定是nums[0] + int32_t maxV{nums[0]}; + for (size_t i{2}; i <= nums_size; i++) { + dp[i] = std::max(nums[i - 1], dp[i - 1] + nums[i - 1]); + maxV = std::max(maxV, dp[i]); + } + return maxV; } - return maxV; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/divide_merge/leetcode_53_test.cpp b/algorithm/divide_merge/leetcode_53_test.cpp new file mode 100644 index 00000000..6c969065 --- /dev/null +++ b/algorithm/divide_merge/leetcode_53_test.cpp @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag divide_merge +//@Tag 分治 +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day5 +//@Plan 数据结构入门 Day1 +//@Plan 剑指OfferII-I Day09 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DIVIDE_MERGE_LEETCODE_53_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DIVIDE_MERGE_LEETCODE_53_TEST_CPP + +#include +#include "leetcode_53.cpp" + +namespace leetcode_53 { +using std::string; +using std::vector; + +TEST_CASE("1 [test_53]", "[test_53]") { + const vector input{-2, 1, -3, 4, -1, 2, 1, -5, 4}; + static constexpr const int32_t output{6}; + Solution solution; + CHECK(solution.maxSubArray(input) == output); + CHECK(solution.maxSubArray2(input) == output); +} + +TEST_CASE("2 [test_53]", "[test_53]") { + const vector input{1}; + static constexpr const int32_t output{1}; + Solution solution; + CHECK(solution.maxSubArray2(input) == output); + CHECK(solution.maxSubArray(input) == output); +} + +TEST_CASE("3 [test_53]", "[test_53]") { + const vector input{0}; + static constexpr const int32_t output{0}; + Solution solution; + CHECK(solution.maxSubArray(input) == output); + CHECK(solution.maxSubArray2(input) == output); +} + +TEST_CASE("4 [test_53]", "[test_53]") { + const vector input{-1}; + static constexpr const int32_t output{-1}; + Solution solution; + CHECK(solution.maxSubArray(input) == output); + CHECK(solution.maxSubArray2(input) == output); +} + +TEST_CASE("5 [test_53]", "[test_53]") { + const vector input{-100000}; + static constexpr const int32_t output{-100000}; + Solution solution; + CHECK(solution.maxSubArray(input) == output); + CHECK(solution.maxSubArray2(input) == output); +} + +TEST_CASE("6 [test_53]", "[test_53]") { + const vector input{-2, -1}; + static constexpr const int32_t output{-1}; + Solution solution; + CHECK(solution.maxSubArray(input) == output); + CHECK(solution.maxSubArray2(input) == output); +} + +TEST_CASE("7 [test_53]", "[test_53]") { + const vector input{5, 4, -1, 7, 8}; + static constexpr const int32_t output{23}; + Solution solution; + CHECK(solution.maxSubArray(input) == output); + CHECK(solution.maxSubArray2(input) == output); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DIVIDE_MERGE_LEETCODE_53_TEST_CPP diff --git a/algorithm/divide_merge/leetcode_53_test.hpp b/algorithm/divide_merge/leetcode_53_test.hpp deleted file mode 100644 index 9b5c493d..00000000 --- a/algorithm/divide_merge/leetcode_53_test.hpp +++ /dev/null @@ -1,83 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag divide_merge -//@Tag 分治 -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day5 -//@Plan 数据结构入门 Day1 -//@Plan 剑指OfferII-I Day09 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DIVIDE_MERGE_LEETCODE_53_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DIVIDE_MERGE_LEETCODE_53_TEST_CPP - -#include -#include -#include -#include -#include - -namespace leetcode_53 { -using std::string; -using std::vector; - -struct leetcode_53 { - static int32_t maxSubArray(const vector &nums); - - static int32_t maxSubArray2(const vector &nums); -}; - -TEST_CASE("1 [test_53]", "[test_53]") { - const vector input{-2, 1, -3, 4, -1, 2, 1, -5, 4}; - static constexpr const int32_t output{6}; - CHECK(leetcode_53::maxSubArray(input) == output); - CHECK(leetcode_53::maxSubArray2(input) == output); -} - -TEST_CASE("2 [test_53]", "[test_53]") { - const vector input{1}; - static constexpr const int32_t output{1}; - CHECK(leetcode_53::maxSubArray2(input) == output); - CHECK(leetcode_53::maxSubArray(input) == output); -} - -TEST_CASE("3 [test_53]", "[test_53]") { - const vector input{0}; - static constexpr const int32_t output{0}; - CHECK(leetcode_53::maxSubArray(input) == output); - CHECK(leetcode_53::maxSubArray2(input) == output); -} - -TEST_CASE("4 [test_53]", "[test_53]") { - const vector input{-1}; - static constexpr const int32_t output{-1}; - CHECK(leetcode_53::maxSubArray(input) == output); - CHECK(leetcode_53::maxSubArray2(input) == output); -} - -TEST_CASE("5 [test_53]", "[test_53]") { - const vector input{-100000}; - static constexpr const int32_t output{-100000}; - CHECK(leetcode_53::maxSubArray(input) == output); - CHECK(leetcode_53::maxSubArray2(input) == output); -} - -TEST_CASE("6 [test_53]", "[test_53]") { - const vector input{-2, -1}; - static constexpr const int32_t output{-1}; - CHECK(leetcode_53::maxSubArray(input) == output); - CHECK(leetcode_53::maxSubArray2(input) == output); -} - -TEST_CASE("7 [test_53]", "[test_53]") { - const vector input{5, 4, -1, 7, 8}; - static constexpr const int32_t output{23}; - CHECK(leetcode_53::maxSubArray(input) == output); - CHECK(leetcode_53::maxSubArray2(input) == output); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DIVIDE_MERGE_LEETCODE_53_TEST_CPP diff --git a/algorithm/dp/CMakeLists.txt b/algorithm/dp/CMakeLists.txt index 346e5f61..b87e4f38 100644 --- a/algorithm/dp/CMakeLists.txt +++ b/algorithm/dp/CMakeLists.txt @@ -9,12 +9,12 @@ enable_testing() set(dependencies package divide_bar matrix_multiply) set(leetcode_order 1143 5 10 44 45) -LIST(APPEND leetcode_order 63 62 64 70_746) -LIST(APPEND leetcode_order 97 322 509_1137 416) -LIST(APPEND leetcode_order 198_213 740 55 918) +LIST(APPEND leetcode_order 63 62 64 70 746) +LIST(APPEND leetcode_order 97 322 509 1137 416) +LIST(APPEND leetcode_order 198 213 740 55 918) LIST(APPEND leetcode_order 152 120 1567 1014 121) LIST(APPEND leetcode_order 122 309 714 139 413) -LIST(APPEND leetcode_order 91 264 931 304_1314 221) +LIST(APPEND leetcode_order 91 264 931 304 1314 221) LIST(APPEND leetcode_order 516 300 174 376 643) LIST(APPEND leetcode_order 392 72 518 377 279) LIST(APPEND leetcode_order so_46 435 1025 1044 1277) @@ -26,10 +26,10 @@ unset(leetcode_order) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) - target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE CS203_DSAA_TEST_MACRO) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) endforeach () unset(dependencies) diff --git a/algorithm/dp/divide_bar.cpp b/algorithm/dp/divide_bar.cpp index 571cd467..cbeb3b96 100644 --- a/algorithm/dp/divide_bar.cpp +++ b/algorithm/dp/divide_bar.cpp @@ -1,71 +1,76 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "divide_bar_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include - +#include +#include namespace dp { namespace divide_bar { // Introduction to Algorithms Edition3 Chapter15.1 + namespace iter { -int64_t maxProfit(const vector ÷_profits, size_t length) { - const auto minIter{std::min(divide_profits.size(), length)}; - vector profits_table(length + 1, -0x3f3f3f); - profits_table[0] = 0; - for (size_t i{0}; i < minIter; ++i) { - profits_table[i + 1] = divide_profits[i]; - } - for (size_t i{2}; i <= length; ++i) { - for (size_t j{1}; j < (i / 2 + 1); ++j) { - profits_table[i] = std::max(profits_table[i], profits_table[j] + profits_table[i - j]); +class Solution { +public: + int64_t maxProfit(const std::vector ÷_profits, size_t length) { + const auto minIter{std::min(divide_profits.size(), length)}; + std::vector profits_table(length + 1, -0x3f3f3f); + profits_table[0] = 0; + for (size_t i{0}; i < minIter; ++i) { + profits_table[i + 1] = divide_profits[i]; + } + for (size_t i{2}; i <= length; ++i) { + for (size_t j{1}; j < (i / 2 + 1); ++j) { + profits_table[i] = std::max(profits_table[i], profits_table[j] + profits_table[i - j]); + } } + return profits_table.back(); } - return profits_table.back(); +}; } namespace with_solution { -std::tuple> maxProfit(const vector ÷_profits, size_t length) { - const auto minIter{std::min(divide_profits.size(), length)}; - vector profits_table(length + 1, -0x3f3f3f); - vector> segment_table(length + 1); - profits_table[0] = 0; - segment_table[0] = {}; - for (size_t i{0}; i < minIter; ++i) { - profits_table[i + 1] = divide_profits[i]; - segment_table[i + 1].push_back(static_cast(i + 1)); - } - for (size_t i{2}; i <= length; ++i) { - size_t left{0}, right{0}; - for (size_t j{1}; j < (i / 2 + 1); ++j) { - const auto sums = profits_table[j] + profits_table[i - j]; - if (sums > profits_table[i]) { // 相对倾向于保留大块 - profits_table[i] = sums; - left = j; - right = i - j; - } +class Solution { +public: + std::tuple> maxProfit(const std::vector ÷_profits, size_t length) { + const auto minIter{std::min(divide_profits.size(), length)}; + std::vector profits_table(length + 1, -0x3f3f3f); + std::vector> segment_table(length + 1); + profits_table[0] = 0; + segment_table[0] = {}; + for (size_t i{0}; i < minIter; ++i) { + profits_table[i + 1] = divide_profits[i]; + segment_table[i + 1].push_back(static_cast(i + 1)); } - if (left != 0 && right != 0) { - auto mid = segment_table[left]; - mid.insert(mid.end(), segment_table[right].cbegin(), segment_table[right].cend()); - segment_table[i] = mid; // 操作完成之后赋值,防止操作自己 + for (size_t i{2}; i <= length; ++i) { + size_t left{0}, right{0}; + for (size_t j{1}; j < (i / 2 + 1); ++j) { + const auto sums = profits_table[j] + profits_table[i - j]; + if (sums > profits_table[i]) { // 相对倾向于保留大块 + profits_table[i] = sums; + left = j; + right = i - j; + } + } + if (left != 0 && right != 0) { + auto mid = segment_table[left]; + mid.insert(mid.end(), segment_table[right].cbegin(), segment_table[right].cend()); + segment_table[i] = mid; // 操作完成之后赋值,防止操作自己 + } } + return std::make_tuple(profits_table.back(), segment_table.back()); } - return std::make_tuple(profits_table.back(), segment_table.back()); -} +}; } -} namespace rec { -int64_t maxProfit(const vector ÷_profits, size_t length) { - return 0; -} +class Solution { +public: + int64_t maxProfit(const std::vector ÷_profits, size_t length) { + return 0; + } +}; } } diff --git a/algorithm/dp/divide_bar_test.hpp b/algorithm/dp/divide_bar_test.cpp similarity index 70% rename from algorithm/dp/divide_bar_test.hpp rename to algorithm/dp/divide_bar_test.cpp index 1c0535d7..4e3aa90e 100644 --- a/algorithm/dp/divide_bar_test.hpp +++ b/algorithm/dp/divide_bar_test.cpp @@ -1,33 +1,30 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_DIVIDE_BAR_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_DIVIDE_BAR_TEST_HPP -*/ - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_DIVIDE_BAR_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_DIVIDE_BAR_TEST_HPP - -#include "package.hpp" #include +#include "divide_bar.cpp" namespace dp { namespace divide_bar { +using std::vector; + namespace iter { -int64_t maxProfit(const vector ÷_profits, size_t length); TEST_CASE("1 [test_divide_bar]", "[test_divide_bar]") { const vector profits{1, 5, 8, 9, 10, 17, 17, 20, 24, 30}; const vector results{0, 1, 5, 8, 10, 13, 17, 18, 22, 25, 30}; const auto maxLength{results.size()}; + Solution solution; for (size_t i{0}; i < maxLength; ++i) { - CHECK(results[i] == maxProfit(profits, i)); + CHECK(results[i] == solution.maxProfit(profits, i)); } } +} namespace with_solution { -std::tuple> maxProfit(const vector ÷_profits, size_t length); using Catch::Matchers::Equals; @@ -47,20 +44,17 @@ TEST_CASE("1 [test_divide_bar::iter::with_solution]", "[test_divide_bar]") { std::make_tuple(30, vector{10}), // instead of {2,2,6} }; const auto maxLength{results.size()}; + Solution solution; for (size_t i{0}; i < maxLength; ++i) { const auto [resultProfit, resultNums] = results[i]; - const auto [outputProfit, outputNums] = maxProfit(profits, i); + const auto [outputProfit, outputNums] = solution.maxProfit(profits, i); CHECK(resultProfit == outputProfit); CHECK_THAT(resultNums, Equals(outputNums)); } } } -} - -namespace rec { -int64_t maxProfit(const vector ÷_profits, size_t length); } } -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_DIVIDE_BAR_TEST_HPP + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_DIVIDE_BAR_TEST_HPP diff --git a/algorithm/dp/leetcode_10.cpp b/algorithm/dp/leetcode_10.cpp index ff05461b..92033abb 100644 --- a/algorithm/dp/leetcode_10.cpp +++ b/algorithm/dp/leetcode_10.cpp @@ -1,38 +1,44 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_10_test.hpp" #include +#include +#include -namespace lcs_10 { +#ifdef ALGORITHM_TEST_MACRO +namespace leetcode_10 { using std::vector; +using std::string; +#endif -bool leetcode_10::isMatch(const string &s, const string &p) { - static constexpr const auto func = [](const auto x, const auto y) { - return y == '.' || x == y; - }; - const auto s_size{s.size()}, p_size{p.size()}; - vector> DP(s_size + 1, vector(p_size + 1, false)); - DP[0][0] = true; - for (size_t j{1}; j <= p_size; ++j) { - DP[0][j] = (p[j - 1] == '*' && DP[0][j - 2]); - } - for (size_t i{1}; i <= s_size; ++i) { - const auto s_char{s[i - 1]}; +class Solution { +public: + bool isMatch(const string &s, const string &p) { + static constexpr const auto func = [](const auto x, const auto y) { + return y == '.' || x == y; + }; + const auto s_size{s.size()}, p_size{p.size()}; + vector> DP(s_size + 1, vector(p_size + 1, false)); + DP[0][0] = true; for (size_t j{1}; j <= p_size; ++j) { - const auto p_char{p[j - 1]}; - if (p[j - 1] == '*') { // p[0], j =1 will not appear '*' - const auto p_last_char{p[j - 2]}; - DP[i][j] = DP[i][j - 2] || (func(s_char, p_last_char) && DP[i - 1][j]); - } else if (func(s_char, p_char)) { - DP[i][j] = DP[i - 1][j - 1]; + DP[0][j] = (p[j - 1] == '*' && DP[0][j - 2]); + } + for (size_t i{1}; i <= s_size; ++i) { + const auto s_char{s[i - 1]}; + for (size_t j{1}; j <= p_size; ++j) { + const auto p_char{p[j - 1]}; + if (p[j - 1] == '*') { // p[0], j =1 will not appear '*' + const auto p_last_char{p[j - 2]}; + DP[i][j] = DP[i][j - 2] || (func(s_char, p_last_char) && DP[i - 1][j]); + } else if (func(s_char, p_char)) { + DP[i][j] = DP[i - 1][j - 1]; + } } } + return DP.back().back(); } - return DP.back().back(); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_1014.cpp b/algorithm/dp/leetcode_1014.cpp index 9d9787f1..396ed90e 100644 --- a/algorithm/dp/leetcode_1014.cpp +++ b/algorithm/dp/leetcode_1014.cpp @@ -1,38 +1,44 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_1014_test.hpp" +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1014 { +using std::vector; +#endif -int32_t leetcode_1014::maxScoreSightseeingPair(const vector &nums) noexcept { - const int32_t nums_size = nums.size(); - if (nums_size <= 1) { - return 0x3f3f3f3f; - } - vector dp(nums_size + 1, 0); - // dp[i] => 前个里哪一个充当 values[i]+i里的i - dp[0] = 0; // can not match pair - dp[1] = 0; // 还没成对 - dp[2] = 0; // 第二个(1th)之前的i序号为0 - int32_t maxDiff{nums[0] + 0 + nums[1] - 1}; - for (int32_t j{3}; j <= nums_size; j++) { - const auto i = dp[j - 1]; - const int32_t base = nums[j - 1] - j + 1; - const int32_t diff1 = base + nums[i] + i; - const int32_t diff2 = base + nums[j - 2] + j - 2; - if (diff2 > diff1) { - dp[j] = j - 2; - } else { - dp[j] = i; +class Solution { +public: + int32_t maxScoreSightseeingPair(const vector &nums) noexcept { + const int32_t nums_size = nums.size(); + if (nums_size <= 1) { + return 0x3f3f3f3f; } - maxDiff = std::max({maxDiff, diff1, diff2}); + vector dp(nums_size + 1, 0); + // dp[i] => 前个里哪一个充当 values[i]+i里的i + dp[0] = 0; // can not match pair + dp[1] = 0; // 还没成对 + dp[2] = 0; // 第二个(1th)之前的i序号为0 + int32_t maxDiff{nums[0] + 0 + nums[1] - 1}; + for (int32_t j{3}; j <= nums_size; j++) { + const auto i = dp[j - 1]; + const int32_t base = nums[j - 1] - j + 1; + const int32_t diff1 = base + nums[i] + i; + const int32_t diff2 = base + nums[j - 2] + j - 2; + if (diff2 > diff1) { + dp[j] = j - 2; + } else { + dp[j] = i; + } + maxDiff = std::max({maxDiff, diff1, diff2}); + } + return maxDiff; } - return maxDiff; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_1014_test.cpp b/algorithm/dp/leetcode_1014_test.cpp new file mode 100644 index 00000000..b6445cc8 --- /dev/null +++ b/algorithm/dp/leetcode_1014_test.cpp @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day7 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1014_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1014_TEST_CPP + +#include +#include "leetcode_1014.cpp" + +namespace leetcode_1014 { +using std::vector; + +TEST_CASE("3 [test_1014]", "[test_1014]") { + const vector input{4, 7, 5, 8}; + static constexpr const auto result{13}; + Solution solution; + CHECK(result == solution.maxScoreSightseeingPair(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1014_TEST_CPP diff --git a/algorithm/dp/leetcode_1014_test.hpp b/algorithm/dp/leetcode_1014_test.hpp deleted file mode 100644 index c75a362e..00000000 --- a/algorithm/dp/leetcode_1014_test.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day7 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1014_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1014_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_1014 { -using std::vector; - -struct leetcode_1014 { - static int32_t maxScoreSightseeingPair(const vector &values) noexcept; -}; - -TEST_CASE("3 [test_1014]", "[test_1014]") { - const vector input{4, 7, 5, 8}; - static constexpr const auto result{13}; - CHECK(result == leetcode_1014::maxScoreSightseeingPair(input)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1014_TEST_CPP diff --git a/algorithm/dp/leetcode_1025.cpp b/algorithm/dp/leetcode_1025.cpp index be831dc3..1fe9eff7 100644 --- a/algorithm/dp/leetcode_1025.cpp +++ b/algorithm/dp/leetcode_1025.cpp @@ -1,31 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_1025_test.hpp" +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1025 { +using std::vector; +#endif -bool leetcode_1025::divisorGame(int32_t n) { - vector status(n + 3, false); - status[1] = false; - status[2] = true; - for (size_t i{3}; i < n + 3; ++i) { - for (size_t j{1}; j < i; ++j) { - if (i % j == 0 && status[i - j] == false) { - status[i] = true; - break; +class Solution { +public: + bool divisorGame(int32_t n) { + vector status(n + 3, false); + status[1] = false; + status[2] = true; + for (size_t i{3}; i < n + 3; ++i) { + for (size_t j{1}; j < i; ++j) { + if (i % j == 0 && status[i - j] == false) { + status[i] = true; + break; + } } } + return status[n]; } - return status[n]; -} -bool leetcode_1025::divisorGame2(int32_t n) { - return !(n & 1); -} + bool divisorGame2(int32_t n) { + return !(n & 1); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_1025_test.cpp b/algorithm/dp/leetcode_1025_test.cpp new file mode 100644 index 00000000..a04cf010 --- /dev/null +++ b/algorithm/dp/leetcode_1025_test.cpp @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Tag 位运算 +//@Tag 数学归纳法 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1025_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1025_TEST_CPP + +#include +#include "leetcode_1025.cpp" + +namespace leetcode_1025 { + +TEST_CASE("1 [test_1025]", "[test_1025]") { + static constexpr const auto input{1}; + Solution solution; + CHECK_FALSE(solution.divisorGame(input)); + CHECK_FALSE(solution.divisorGame2(input)); +} + +TEST_CASE("2 [test_1025]", "[test_1025]") { + static constexpr const auto input{2}; + Solution solution; + CHECK(solution.divisorGame(input)); + CHECK(solution.divisorGame2(input)); +} + +TEST_CASE("3 [test_1025]", "[test_1025]") { + static constexpr const auto input{11}; + Solution solution; + CHECK_FALSE(solution.divisorGame(input)); + CHECK_FALSE(solution.divisorGame2(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1025_TEST_CPP diff --git a/algorithm/dp/leetcode_1025_test.hpp b/algorithm/dp/leetcode_1025_test.hpp deleted file mode 100644 index 5dd1b808..00000000 --- a/algorithm/dp/leetcode_1025_test.hpp +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Tag 位运算 -//@Tag 数学归纳法 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1025_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1025_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_1025 { -using std::vector; - -struct leetcode_1025 { - static bool divisorGame(int32_t n); - - static bool divisorGame2(int32_t n); -}; - -TEST_CASE("1 [test_1025]", "[test_1025]") { - static constexpr const auto input{1}; - CHECK_FALSE(leetcode_1025::divisorGame(input)); - CHECK_FALSE(leetcode_1025::divisorGame2(input)); -} - -TEST_CASE("2 [test_1025]", "[test_1025]") { - static constexpr const auto input{2}; - CHECK(leetcode_1025::divisorGame(input)); - CHECK(leetcode_1025::divisorGame2(input)); -} - -TEST_CASE("3 [test_1025]", "[test_1025]") { - static constexpr const auto input{11}; - CHECK_FALSE(leetcode_1025::divisorGame(input)); - CHECK_FALSE(leetcode_1025::divisorGame2(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1025_TEST_CPP diff --git a/algorithm/dp/leetcode_1044.cpp b/algorithm/dp/leetcode_1044.cpp index 9ae46186..26300c47 100644 --- a/algorithm/dp/leetcode_1044.cpp +++ b/algorithm/dp/leetcode_1044.cpp @@ -1,53 +1,62 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_1044_test.hpp" +#include +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1044 { +using std::string; +using std::vector; +#endif -// 缺点在于很慢,对拍可以用 -// 由于实际上最长公共子串包括字符串自己 -// 因此,排除掉之后,所有的公共子串信息实际上是副产物 -// 题目相当于要求返回次长的字串. 所以效率提不上去 -// 因此,如果有意的把自己和自己重复的场景去掉, 就可以提高效率 -string longestDupSubstringN2(const string &s) { - const auto ssize{s.size()}; - vector> dp(ssize + 1, vector(ssize + 1, 0)); - // dp[i][j], from i to j's longest dup substring - size_t max_value{0}; - for (size_t i{1}; i <= ssize; ++i) { - for (size_t j{1}; j <= ssize; ++j) { - if (i == j) { - dp[i][j] = 0; - continue; - } - if (s[i - 1] == s[j - 1]) { - dp[i][j] = dp[i - 1][j - 1] + 1; - max_value = std::max(max_value, dp[i][j]); - } else { - dp[i][j] = 0; +class Solution { +private: + // 缺点在于很慢,对拍可以用 + // 由于实际上最长公共子串包括字符串自己 + // 因此,排除掉之后,所有的公共子串信息实际上是副产物 + // 题目相当于要求返回次长的字串. 所以效率提不上去 + // 因此,如果有意的把自己和自己重复的场景去掉, 就可以提高效率 + string longestDupSubstringN2(const string &s) { + const auto ssize{s.size()}; + vector> dp(ssize + 1, vector(ssize + 1, 0)); + // dp[i][j], from i to j's longest dup substring + size_t max_value{0}; + for (size_t i{1}; i <= ssize; ++i) { + for (size_t j{1}; j <= ssize; ++j) { + if (i == j) { + dp[i][j] = 0; + continue; + } + if (s[i - 1] == s[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + max_value = std::max(max_value, dp[i][j]); + } else { + dp[i][j] = 0; + } } } - } - if (max_value < 2) { - return ""; - } - for (size_t i{1}; i <= ssize; ++i) { - for (size_t j{1}; j <= ssize; ++j) { - if (dp[i][j] == max_value) { - return s.substr(i - max_value, max_value); + if (max_value < 2) { + return ""; + } + for (size_t i{1}; i <= ssize; ++i) { + for (size_t j{1}; j <= ssize; ++j) { + if (dp[i][j] == max_value) { + return s.substr(i - max_value, max_value); + } } } + return ""; } - return ""; -} -string leetcode_1044::longestDupSubstring(const string &s) { - return longestDupSubstringN2(s); // TODO,优化,估计会挪到二分或者hash那边去? -} +public: + string longestDupSubstring(const string &s) { + return longestDupSubstringN2(s); // TODO,优化,估计会挪到二分或者hash那边去? + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_1044_test.hpp b/algorithm/dp/leetcode_1044_test.cpp similarity index 54% rename from algorithm/dp/leetcode_1044_test.hpp rename to algorithm/dp/leetcode_1044_test.cpp index 56269194..ee72dbba 100644 --- a/algorithm/dp/leetcode_1044_test.hpp +++ b/algorithm/dp/leetcode_1044_test.cpp @@ -1,48 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Description 最长公共字串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1044_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1044_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1044_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1044_TEST_CPP #include -#include -#include +#include "leetcode_1044.cpp" namespace leetcode_1044 { using std::string; -namespace leetcode_1044 { -string longestDupSubstring(const string &s); -} - TEST_CASE("3 [test_1044]", "[test_1044]") { constexpr const char *const input{"banana"}; constexpr const char *const output{"ana"}; - const string result{leetcode_1044::longestDupSubstring(input)}; + Solution solution; + const string result{solution.longestDupSubstring(input)}; CHECK(result == output); } TEST_CASE("2 [test_1044]", "[test_1044]") { constexpr const char *const input{"abcd"}; constexpr const char *const output{""}; - const string result{leetcode_1044::longestDupSubstring(input)}; + Solution solution; + const string result{solution.longestDupSubstring(input)}; CHECK(result == output); } TEST_CASE("1 [test_1044]", "[test_1044]") { constexpr const char *const input{"efg"}; constexpr const char *const output{""}; - const string result{leetcode_1044::longestDupSubstring(input)}; + Solution solution; + const string result{solution.longestDupSubstring(input)}; CHECK(result == output); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1044_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1044_TEST_CPP diff --git a/algorithm/dp/leetcode_10_test.cpp b/algorithm/dp/leetcode_10_test.cpp new file mode 100644 index 00000000..4cb95ef5 --- /dev/null +++ b/algorithm/dp/leetcode_10_test.cpp @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_10_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_10_TEST_CPP + +#include +#include "leetcode_10.cpp" + +namespace leetcode_10 { +using std::string; + +TEST_CASE("test case 1", "[test_10]") { + Solution solution; + CHECK_FALSE(solution.isMatch("aa", "a")); + CHECK(solution.isMatch("aa", "a*")); + CHECK(solution.isMatch("ab", ".*")); + CHECK(solution.isMatch("aab", "c*a*b")); + CHECK_FALSE(solution.isMatch("mississippi", "mis*is*p*.")); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_10_TEST_CPP diff --git a/algorithm/dp/leetcode_10_test.hpp b/algorithm/dp/leetcode_10_test.hpp deleted file mode 100644 index 883906ce..00000000 --- a/algorithm/dp/leetcode_10_test.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_10_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_10_TEST_CPP - -#include -#include -#include -#include - -namespace lcs_10 { -using std::string; - -struct leetcode_10 { - static bool isMatch(const string &s, const string &p); -}; - -TEST_CASE("test case 1", "[test_10]") { - CHECK_FALSE(leetcode_10::isMatch("aa", "a")); - CHECK(leetcode_10::isMatch("aa", "a*")); - CHECK(leetcode_10::isMatch("ab", ".*")); - CHECK(leetcode_10::isMatch("aab", "c*a*b")); - CHECK_FALSE(leetcode_10::isMatch("mississippi", "mis*is*p*.")); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_10_TEST_CPP diff --git a/algorithm/dp/leetcode_1137.cpp b/algorithm/dp/leetcode_1137.cpp new file mode 100644 index 00000000..a09d5b04 --- /dev/null +++ b/algorithm/dp/leetcode_1137.cpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + +#ifdef ALGORITHM_TEST_MACRO + +#include +#include +#include + +namespace leetcode_1137 { +using std::array; +#endif + + +class Solution { +private: + static constexpr const size_t maxV{38}; + + static constexpr auto func() { + array fib{0}; + fib[1] = 1; + fib[2] = 1; + for (size_t i{3}; i < maxV; i++) { + fib[i] = fib[i - 1] + fib[i - 2] + fib[i - 3]; + } + return fib; + } + +public: + int32_t tribonacci(int32_t n) { + static constexpr const array arr = func(); + return arr[n]; + } +}; + +#ifdef ALGORITHM_TEST_MACRO +} +#endif diff --git a/algorithm/dp/leetcode_1137_test.cpp b/algorithm/dp/leetcode_1137_test.cpp new file mode 100644 index 00000000..b247fe9d --- /dev/null +++ b/algorithm/dp/leetcode_1137_test.cpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day1 +//@Plan 剑指OfferII-I Day08 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1137_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1137_TEST_CPP + +#include +#include "leetcode_1137.cpp" + +namespace leetcode_1137 { +using std::array; + + +TEST_CASE("1 [test_1137]", "[test_1137]") { + static constexpr const auto input{4}; + static constexpr const auto result{4}; + Solution solution; + CHECK(result == solution.tribonacci(input)); +} + +TEST_CASE("2 [test_1137]", "[test_1137]") { + static constexpr const auto input{0}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.tribonacci(input)); +} + +TEST_CASE("3 [test_1137]", "[test_1137]") { + static constexpr const auto input{1}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.tribonacci(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1137_TEST_CPP diff --git a/algorithm/dp/leetcode_1143.cpp b/algorithm/dp/leetcode_1143.cpp index 2f9edeb2..04477abf 100644 --- a/algorithm/dp/leetcode_1143.cpp +++ b/algorithm/dp/leetcode_1143.cpp @@ -1,46 +1,53 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_1143_test.hpp" #include +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1143 { using std::vector; +using std::string; +#endif -int32_t leetcode_1143::longestCommonSubsequence2(const string &text1, const string &text2) { - const auto fst_size{text1.size()}, snd_size{text2.size()}; - vector> dp(fst_size + 1, vector(snd_size + 1, 0)); - // init vector for 0 can except init [0][...],[...][0] to 0 - for (size_t i{1}; i <= fst_size; i++) { - for (size_t j{1}; j <= snd_size; j++) { - if (text1[i - 1] == text2[j - 1]) { - dp[i][j] = dp[i - 1][j - 1] + 1; - } else { - dp[i][j] = std::max(dp[i][j - 1], dp[i - 1][j]); +class Solution { +public: + int32_t longestCommonSubsequence2(const string &text1, const string &text2) { + const auto fst_size{text1.size()}, snd_size{text2.size()}; + vector> dp(fst_size + 1, vector(snd_size + 1, 0)); + // init vector for 0 can except init [0][...],[...][0] to 0 + for (size_t i{1}; i <= fst_size; i++) { + for (size_t j{1}; j <= snd_size; j++) { + if (text1[i - 1] == text2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = std::max(dp[i][j - 1], dp[i - 1][j]); + } } } + return dp.back().back(); } - return dp.back().back(); -} -int32_t leetcode_1143::longestCommonSubsequence(const string &text1, const string &text2) { - const auto fst_size{text1.size()}, snd_size{text2.size()}; - vector fst(snd_size + 1, 0), snd(snd_size + 1, 0); - // init vector for 0 can except init [0][...],[...][0] to 0 - for (size_t i{1}; i <= fst_size; i++) { - for (size_t j{1}; j <= snd_size; j++) { - if (text1[i - 1] == text2[j - 1]) { - snd[j] = fst[j - 1] + 1; - } else { - snd[j] = std::max(snd[j - 1], fst[j]); + int32_t longestCommonSubsequence(const string &text1, const string &text2) { + const auto fst_size{text1.size()}, snd_size{text2.size()}; + vector fst(snd_size + 1, 0), snd(snd_size + 1, 0); + // init vector for 0 can except init [0][...],[...][0] to 0 + for (size_t i{1}; i <= fst_size; i++) { + for (size_t j{1}; j <= snd_size; j++) { + if (text1[i - 1] == text2[j - 1]) { + snd[j] = fst[j - 1] + 1; + } else { + snd[j] = std::max(snd[j - 1], fst[j]); + } } + std::swap(fst, snd); } - std::swap(fst, snd); + return fst.back(); } - return fst.back(); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_1143_test.hpp b/algorithm/dp/leetcode_1143_test.cpp similarity index 67% rename from algorithm/dp/leetcode_1143_test.hpp rename to algorithm/dp/leetcode_1143_test.cpp index 8b488a71..92e6edc6 100644 --- a/algorithm/dp/leetcode_1143_test.hpp +++ b/algorithm/dp/leetcode_1143_test.cpp @@ -1,60 +1,51 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Description 最长公共子序列 //@Plan 动态规划入门 Day19 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1143_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1143_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1143_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1143_TEST_CPP #include -#include -#include -#include +#include "leetcode_1143.cpp" namespace leetcode_1143 { using std::string; -struct leetcode_1143 { - static int32_t longestCommonSubsequence(const string &text1, const string &text2); - - static int32_t longestCommonSubsequence2(const string &text1, const string &text2); -}; - using Catch::Matchers::Equals; TEST_CASE("1 [test_1143]", "[test_1143]") { static constexpr const char *const input1{"abcde"}, *const input2{"ace"}; static constexpr const auto result{3}; - CHECK(result == leetcode_1143::longestCommonSubsequence(input1, input2)); - CHECK(result == leetcode_1143::longestCommonSubsequence2(input1, input2)); + Solution solution; + CHECK(result == solution.longestCommonSubsequence(input1, input2)); + CHECK(result == solution.longestCommonSubsequence2(input1, input2)); } TEST_CASE("2 [test_1143]", "[test_1143]") { static constexpr const char *const input1{"abc"}, *const input2{"abc"}; static constexpr const auto result{3}; - CHECK(result == leetcode_1143::longestCommonSubsequence(input1, input2)); - CHECK(result == leetcode_1143::longestCommonSubsequence2(input1, input2)); + Solution solution; + CHECK(result == solution.longestCommonSubsequence(input1, input2)); + CHECK(result == solution.longestCommonSubsequence2(input1, input2)); } TEST_CASE("3 [test_1143]", "[test_1143]") { static constexpr const char *const input1{"abc"}, *const input2{"degf"}; static constexpr const auto result{0}; - CHECK(result == leetcode_1143::longestCommonSubsequence(input1, input2)); - CHECK(result == leetcode_1143::longestCommonSubsequence2(input1, input2)); + Solution solution; + CHECK(result == solution.longestCommonSubsequence(input1, input2)); + CHECK(result == solution.longestCommonSubsequence2(input1, input2)); } TEST_CASE("4 [test_1143]", "[test_1143]") { static constexpr const char *const input1{"a"}, *const input2{"aba"}; static constexpr const auto result{1}; - CHECK(result == leetcode_1143::longestCommonSubsequence(input1, input2)); - CHECK(result == leetcode_1143::longestCommonSubsequence2(input1, input2)); + Solution solution; + CHECK(result == solution.longestCommonSubsequence(input1, input2)); + CHECK(result == solution.longestCommonSubsequence2(input1, input2)); } TEST_CASE("5 [test_1143]", "[test_1143]") { @@ -63,29 +54,33 @@ TEST_CASE("5 [test_1143]", "[test_1143]") { static constexpr const char *const input2{ "nohgdazargvalupetizezqpklktojqtqdivcpsfgjopaxwbkvujilqbclehulatshehmjqhyfkpcfwxovajkvankjkvevgdovazmbgtqfwvejczsnmbchkdibstklkxarwjqbqxwvixavkhylqvghqpifijohudenozotejoxavkfkzcdqnoxydynavwdylwhatslyrwlejwdwrmpevmtwpahatwlaxmjmdgrebmfyngdcbmbgjcvqpcbadujkxaxujudmbejcrevuvcdobolcbstifedcvmngnqhudixgzktcdqngxmruhcxqxypwhahobudelivgvynefkjqdyvalmvudcdivmhghqrelurodwdsvuzmjixgdexonwjczghalsjopixsrwjixuzmjgxydqnipelgrivkzkxgjchibgnqbknstspujwdydszohqjsfuzstyjgnwhsrebmlwzkzijgnmnczmrehspihspyfedabotwvwxwpspypctizyhcxypqzctwlspszonsrmnyvmhsvqtkbyhmhwjmvazaviruzqxmbczaxmtqjexmdudypovkjklynktahupanujylylgrajozobsbwpwtohkfsxeverqxylwdwtojoxydepybavwhgdehafurqtcxqhuhkdwxkdojipolctcvcrsvczcxedglgrejerqdgrsvsxgjodajatsnixutihwpivihadqdotsvyrkxehodybapwlsjexixgponcxifijchejoxgxebmbclczqvkfuzgxsbshqvgfcraxytaxeviryhexmvqjybizivyjanwxmpojgxgbyhcruvqpafwjslkbohqlknkdqjixsfsdurgbsvclmrcrcnulinqvcdqhcvwdaxgvafwravunurqvizqtozuxinytafopmhchmxsxgfanetmdcjalmrolejidylkjktunqhkxchyjmpkvsfgnybsjedmzkrkhwryzan"}; static constexpr const auto result{323}; - CHECK(result == leetcode_1143::longestCommonSubsequence(input1, input2)); - CHECK(result == leetcode_1143::longestCommonSubsequence2(input1, input2)); + Solution solution; + CHECK(result == solution.longestCommonSubsequence(input1, input2)); + CHECK(result == solution.longestCommonSubsequence2(input1, input2)); } TEST_CASE("6 [test_1143]", "[test_1143]") { static constexpr const char *const input1{"bsbininm"}, *const input2{"jmjkbkjkv"}; static constexpr const auto result{1}; - CHECK(result == leetcode_1143::longestCommonSubsequence(input1, input2)); - CHECK(result == leetcode_1143::longestCommonSubsequence2(input1, input2)); + Solution solution; + CHECK(result == solution.longestCommonSubsequence(input1, input2)); + CHECK(result == solution.longestCommonSubsequence2(input1, input2)); } TEST_CASE("7 [test_1143]", "[test_1143]") { static constexpr const char *const input1{"horse"}, *const input2{"ros"}; static constexpr const auto result{2}; - CHECK(result == leetcode_1143::longestCommonSubsequence(input1, input2)); - CHECK(result == leetcode_1143::longestCommonSubsequence2(input1, input2)); + Solution solution; + CHECK(result == solution.longestCommonSubsequence(input1, input2)); + CHECK(result == solution.longestCommonSubsequence2(input1, input2)); } TEST_CASE("8 [test_1143]", "[test_1143]") { static constexpr const char *const input1{"intention"}, *const input2{"execution"}; static constexpr const auto result{5}; // etion - CHECK(result == leetcode_1143::longestCommonSubsequence(input1, input2)); - CHECK(result == leetcode_1143::longestCommonSubsequence2(input1, input2)); + Solution solution; + CHECK(result == solution.longestCommonSubsequence(input1, input2)); + CHECK(result == solution.longestCommonSubsequence2(input1, input2)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1143_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1143_TEST_CPP diff --git a/algorithm/dp/leetcode_120.cpp b/algorithm/dp/leetcode_120.cpp index 0c05e014..2df1c7b8 100644 --- a/algorithm/dp/leetcode_120.cpp +++ b/algorithm/dp/leetcode_120.cpp @@ -1,30 +1,38 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_120_test.hpp" +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_120 { +using std::vector; +#endif -int32_t leetcode_120::minimumTotal(const vector> &triangle) { - const size_t tri_height{triangle.size()}; - if (tri_height == 0) { - return 0; - } else if (tri_height == 1) { - return triangle[0][0]; - } - vector dps(tri_height, 0); - dps[0] = triangle.front().front(); - for (size_t i{1}; i < tri_height; i++) { - dps[i] = dps[i - 1] + triangle[i][i]; - for (size_t r{i - 1}; r > 0; r--) { - dps[r] = std::min(dps[r - 1], dps[r]) + triangle[i][r]; +class Solution { +public: + int32_t minimumTotal(const vector> &triangle) { + const size_t tri_height{triangle.size()}; + if (tri_height == 0) { + return 0; + } else if (tri_height == 1) { + return triangle[0][0]; + } + vector dps(tri_height, 0); + dps[0] = triangle.front().front(); + for (size_t i{1}; i < tri_height; i++) { + dps[i] = dps[i - 1] + triangle[i][i]; + for (size_t r{i - 1}; r > 0; r--) { + dps[r] = std::min(dps[r - 1], dps[r]) + triangle[i][r]; + } + dps[0] = dps[0] + triangle[i][0]; } - dps[0] = dps[0] + triangle[i][0]; + return *std::min_element(dps.cbegin(), dps.cend()); } - return *std::min_element(dps.cbegin(), dps.cend()); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif + diff --git a/algorithm/dp/leetcode_120_test.hpp b/algorithm/dp/leetcode_120_test.cpp similarity index 50% rename from algorithm/dp/leetcode_120_test.hpp rename to algorithm/dp/leetcode_120_test.cpp index c902cc70..0b834d70 100644 --- a/algorithm/dp/leetcode_120_test.hpp +++ b/algorithm/dp/leetcode_120_test.cpp @@ -1,35 +1,24 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day13 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_120_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_120_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_120_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_120_TEST_CPP #include -#include -#include -#include -#include +#include "leetcode_120.cpp" namespace leetcode_120 { using std::vector; -struct leetcode_120 final { - static int32_t minimumTotal(const vector> &triangle); -}; - TEST_CASE("1 [test_120]", "[test_120]") { const vector> input{ {1}, }; static constexpr const auto result{1}; - CHECK(result == leetcode_120::minimumTotal(input)); + Solution solution; + CHECK(result == solution.minimumTotal(input)); } TEST_CASE("2 [test_120]", "[test_120]") { @@ -40,8 +29,9 @@ TEST_CASE("2 [test_120]", "[test_120]") { {4, 1, 8, 3}, }; static constexpr const auto result{11}; - CHECK(result == leetcode_120::minimumTotal(input)); + Solution solution; + CHECK(result == solution.minimumTotal(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_120_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_120_TEST_CPP diff --git a/algorithm/dp/leetcode_121.cpp b/algorithm/dp/leetcode_121.cpp index cca151e6..f2c05970 100644 --- a/algorithm/dp/leetcode_121.cpp +++ b/algorithm/dp/leetcode_121.cpp @@ -1,42 +1,50 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_121_test.hpp" +#include +#include +#include namespace leetcode_121 { +using std::vector; +#endif -int32_t leetcode_121::maxProfit(const vector &prices) { - const auto p_size{prices.size()}; - if (p_size <= 1) { - return 0; - } - vector dp(p_size + 1, 0); - // dp[i] 当天之前的最低价格 - dp[0] = 0; // in the 0th day, nothing happen - dp[1] = prices[0]; // buy and sell, do not earn - int32_t will_return{0}; - for (size_t i{2}; i <= p_size; i++) { - will_return = std::max(prices[i - 1] - dp[i - 1], will_return); - dp[i] = std::min(dp[i - 1], prices[i - 1]); +class Solution { +public: + int32_t maxProfit(const vector &prices) { + const auto p_size{prices.size()}; + if (p_size <= 1) { + return 0; + } + vector dp(p_size + 1, 0); + // dp[i] 当天之前的最低价格 + dp[0] = 0; // in the 0th day, nothing happen + dp[1] = prices[0]; // buy and sell, do not earn + int32_t will_return{0}; + for (size_t i{2}; i <= p_size; i++) { + will_return = std::max(prices[i - 1] - dp[i - 1], will_return); + dp[i] = std::min(dp[i - 1], prices[i - 1]); + } + return will_return; } - return will_return; -} -int32_t leetcode_121::maxProfit2(const vector &prices) { - const auto p_size{prices.size()}; - if (p_size <= 1) { - return 0; - } - // dpLast 包括前一天的最低价格 - int32_t dpLast{prices[0]}, will_return{0}; - for (size_t i{2}; i <= p_size; i++) { - will_return = std::max(prices[i - 1] - dpLast, will_return); - dpLast = std::min(dpLast, prices[i - 1]); + int32_t maxProfit2(const vector &prices) { + const auto p_size{prices.size()}; + if (p_size <= 1) { + return 0; + } + // dpLast 包括前一天的最低价格 + int32_t dpLast{prices[0]}, will_return{0}; + for (size_t i{2}; i <= p_size; i++) { + will_return = std::max(prices[i - 1] - dpLast, will_return); + dpLast = std::min(dpLast, prices[i - 1]); + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif + diff --git a/algorithm/dp/leetcode_121_test.cpp b/algorithm/dp/leetcode_121_test.cpp new file mode 100644 index 00000000..c04d19c3 --- /dev/null +++ b/algorithm/dp/leetcode_121_test.cpp @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day7 +//@Plan 数据结构入门 Day3 +//@Plan 剑指OfferII-I Day08 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_121_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_121_TEST_CPP + +#include +#include "leetcode_121.cpp" + +namespace leetcode_121 { +using std::vector; + +TEST_CASE("1 [test_121]", "[test_121]") { + const vector input{7, 1, 5, 3, 6, 4}; + static constexpr const auto result{5}; + Solution solution; + CHECK(result == solution.maxProfit(input)); + CHECK(result == solution.maxProfit2(input)); +} + +TEST_CASE("2 [test_121]", "[test_121]") { + const vector input{7, 6, 4, 3, 1}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.maxProfit(input)); + CHECK(result == solution.maxProfit2(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_121_TEST_CPP diff --git a/algorithm/dp/leetcode_121_test.hpp b/algorithm/dp/leetcode_121_test.hpp deleted file mode 100644 index 439ac317..00000000 --- a/algorithm/dp/leetcode_121_test.hpp +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day7 -//@Plan 数据结构入门 Day3 -//@Plan 剑指OfferII-I Day08 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_121_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_121_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_121 { -using std::vector; - -struct leetcode_121 final { - static int32_t maxProfit(const vector &prices); - - static int32_t maxProfit2(const vector &prices); -}; - - -TEST_CASE("1 [test_121]", "[test_121]") { - const vector input{7, 1, 5, 3, 6, 4}; - static constexpr const auto result{5}; - CHECK(result == leetcode_121::maxProfit(input)); - CHECK(result == leetcode_121::maxProfit2(input)); -} - -TEST_CASE("2 [test_121]", "[test_121]") { - const vector input{7, 6, 4, 3, 1}; - static constexpr const auto result{0}; - CHECK(result == leetcode_121::maxProfit(input)); - CHECK(result == leetcode_121::maxProfit2(input)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_121_TEST_CPP diff --git a/algorithm/dp/leetcode_122.cpp b/algorithm/dp/leetcode_122.cpp index 1f3d0a48..81b64267 100644 --- a/algorithm/dp/leetcode_122.cpp +++ b/algorithm/dp/leetcode_122.cpp @@ -1,95 +1,101 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_122_test.hpp" +#include #include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_122 { +using std::vector; using std::stack; +#endif -int32_t leetcode_122::maxProfit(const vector &prices) { - const auto p_size{prices.size()}; - if (p_size <= 1) { - return 0; - } - // 样例 1-2-3-4-5 - // 不考虑1买入,2卖出 - // 而是考虑 1买入, - // 2卖出,2买入 - // 3卖出,3买入 - // 4卖出,4买入 - // 5卖出 - // 这样的一串流程,并且只在卖出时计费 - int32_t will_return{0}; - stack sta; - for (size_t i{0}; i < p_size; i++) { - int32_t perf{0}; - const auto price = prices[i]; - if (!sta.empty() && price > sta.top()) { - perf = price - sta.top(); - sta.pop(); +class Solution { +public: + int32_t maxProfit(const vector &prices) { + const auto p_size{prices.size()}; + if (p_size <= 1) { + return 0; } - sta.push(price); - will_return += perf; + // 样例 1-2-3-4-5 + // 不考虑1买入,2卖出 + // 而是考虑 1买入, + // 2卖出,2买入 + // 3卖出,3买入 + // 4卖出,4买入 + // 5卖出 + // 这样的一串流程,并且只在卖出时计费 + int32_t will_return{0}; + stack sta; + for (size_t i{0}; i < p_size; i++) { + int32_t perf{0}; + const auto price = prices[i]; + if (!sta.empty() && price > sta.top()) { + perf = price - sta.top(); + sta.pop(); + } + sta.push(price); + will_return += perf; + } + return will_return; } - return will_return; -} -int32_t leetcode_122::maxProfit2(const vector &prices) { - const auto p_size{prices.size()}; - if (p_size <= 1) { - return 0; - } - int32_t willreturn{0}, temp{0}; - for (size_t i{1}; i < p_size; i++) { - temp = prices[i] - prices[i - 1]; - if (temp > 0) { - willreturn += temp; + int32_t maxProfit2(const vector &prices) { + const auto p_size{prices.size()}; + if (p_size <= 1) { + return 0; + } + int32_t willreturn{0}, temp{0}; + for (size_t i{1}; i < p_size; i++) { + temp = prices[i] - prices[i - 1]; + if (temp > 0) { + willreturn += temp; + } } + return willreturn; } - return willreturn; -} -int32_t leetcode_122::maxProfit3(const vector &prices) { - const auto p_size{prices.size()}; - if (p_size <= 1) { - return 0; - } - vector dpBuy(p_size + 1, 0), dpSell(p_size + 1, 0); - // dpBuy[i], 第i天之后, 购入股票状态下的最大收益 - // dpSell[i], 第i天之后, 出售股票状态下的最大收益 - dpBuy[0] = 0; // 0 day之前无法有任何操作 - dpSell[0] = 0; // 0 day之前无法有任何操作 - dpBuy[1] = -prices[0]; // 1 day 购入 - dpSell[1] = 0; // 无法sell,没东西 - for (size_t i{2}; i <= p_size; i++) { - const auto price{prices[i - 1]}; - dpBuy[i] = std::max(dpBuy[i - 1], dpSell[i - 1] - price); // - dpSell[i] = std::max(dpSell[i - 1], dpBuy[i - 1] + price); + int32_t maxProfit3(const vector &prices) { + const auto p_size{prices.size()}; + if (p_size <= 1) { + return 0; + } + vector dpBuy(p_size + 1, 0), dpSell(p_size + 1, 0); + // dpBuy[i], 第i天之后, 购入股票状态下的最大收益 + // dpSell[i], 第i天之后, 出售股票状态下的最大收益 + dpBuy[0] = 0; // 0 day之前无法有任何操作 + dpSell[0] = 0; // 0 day之前无法有任何操作 + dpBuy[1] = -prices[0]; // 1 day 购入 + dpSell[1] = 0; // 无法sell,没东西 + for (size_t i{2}; i <= p_size; i++) { + const auto price{prices[i - 1]}; + dpBuy[i] = std::max(dpBuy[i - 1], dpSell[i - 1] - price); // + dpSell[i] = std::max(dpSell[i - 1], dpBuy[i - 1] + price); + } + return dpSell.back(); } - return dpSell.back(); -} -int32_t leetcode_122::maxProfit4(const vector &prices) { - const auto p_size{prices.size()}; - if (p_size <= 1) { - return 0; - } - // 忽略掉了第0天 => 第一天的变动 - int32_t buyLast{-prices[0]}, buyNow{0}; - int32_t sellLast{0}, sellNow{0}; - // dpBuy[i], 第i天之后, 购入股票状态下的最大收益 - // dpSell[i], 第i天之后, 出售股票状态下的最大收益 - for (size_t i{1}; i < p_size; i++, sellLast = sellNow, buyLast = buyNow) { - const auto price{prices[i]}; - buyNow = std::max(buyLast, sellLast - price); // - sellNow = std::max(sellLast, buyLast + price); + int32_t maxProfit4(const vector &prices) { + const auto p_size{prices.size()}; + if (p_size <= 1) { + return 0; + } + // 忽略掉了第0天 => 第一天的变动 + int32_t buyLast{-prices[0]}, buyNow{0}; + int32_t sellLast{0}, sellNow{0}; + // dpBuy[i], 第i天之后, 购入股票状态下的最大收益 + // dpSell[i], 第i天之后, 出售股票状态下的最大收益 + for (size_t i{1}; i < p_size; i++, sellLast = sellNow, buyLast = buyNow) { + const auto price{prices[i]}; + buyNow = std::max(buyLast, sellLast - price); // + sellNow = std::max(sellLast, buyLast + price); + } + return sellNow; } - return sellNow; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_122_test.cpp b/algorithm/dp/leetcode_122_test.cpp new file mode 100644 index 00000000..966526a1 --- /dev/null +++ b/algorithm/dp/leetcode_122_test.cpp @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Tag stack +//@Tag 单调栈 +//@Linked 121 +//@Plan 动态规划入门 Day7 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_122_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_122_TEST_CPP + +#include +#include "leetcode_122.cpp" + +namespace leetcode_122 { +using std::vector; + +TEST_CASE("1 [test_122]", "[test_122]") { + const vector input{7, 1, 5, 3, 6, 4}; + static constexpr const auto result{7}; + Solution solution; + CHECK(result == solution.maxProfit(input)); + CHECK(result == solution.maxProfit2(input)); + CHECK(result == solution.maxProfit3(input)); + CHECK(result == solution.maxProfit4(input)); +} + +TEST_CASE("2 [test_122]", "[test_122]") { + const vector input{7, 6, 4, 3, 1}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.maxProfit(input)); + CHECK(result == solution.maxProfit2(input)); + CHECK(result == solution.maxProfit3(input)); + CHECK(result == solution.maxProfit4(input)); +} + +TEST_CASE("3 [test_122]", "[test_122]") { + const vector input{1, 2, 3, 4, 5}; + static constexpr const auto result{4}; + Solution solution; + CHECK(result == solution.maxProfit(input)); + CHECK(result == solution.maxProfit2(input)); + CHECK(result == solution.maxProfit3(input)); + CHECK(result == solution.maxProfit4(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_122_TEST_CPP diff --git a/algorithm/dp/leetcode_122_test.hpp b/algorithm/dp/leetcode_122_test.hpp deleted file mode 100644 index 601bc00b..00000000 --- a/algorithm/dp/leetcode_122_test.hpp +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Tag stack -//@Tag 单调栈 -//@Linked 121 -//@Plan 动态规划入门 Day7 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_122_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_122_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_122 { -using std::vector; - -struct leetcode_122 final { - static int32_t maxProfit(const vector &prices); - - static int32_t maxProfit2(const vector &prices); - - static int32_t maxProfit3(const vector &prices); - - static int32_t maxProfit4(const vector &prices); -}; - - -TEST_CASE("1 [test_122]", "[test_122]") { - const vector input{7, 1, 5, 3, 6, 4}; - static constexpr const auto result{7}; - CHECK(result == leetcode_122::maxProfit(input)); - CHECK(result == leetcode_122::maxProfit2(input)); - CHECK(result == leetcode_122::maxProfit3(input)); - CHECK(result == leetcode_122::maxProfit4(input)); -} - -TEST_CASE("2 [test_122]", "[test_122]") { - const vector input{7, 6, 4, 3, 1}; - static constexpr const auto result{0}; - CHECK(result == leetcode_122::maxProfit(input)); - CHECK(result == leetcode_122::maxProfit2(input)); - CHECK(result == leetcode_122::maxProfit3(input)); - CHECK(result == leetcode_122::maxProfit4(input)); -} - -TEST_CASE("3 [test_122]", "[test_122]") { - const vector input{1, 2, 3, 4, 5}; - static constexpr const auto result{4}; - CHECK(result == leetcode_122::maxProfit(input)); - CHECK(result == leetcode_122::maxProfit2(input)); - CHECK(result == leetcode_122::maxProfit3(input)); - CHECK(result == leetcode_122::maxProfit4(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_122_TEST_CPP diff --git a/algorithm/dp/leetcode_1277.cpp b/algorithm/dp/leetcode_1277.cpp index e3f298ec..f1e73483 100644 --- a/algorithm/dp/leetcode_1277.cpp +++ b/algorithm/dp/leetcode_1277.cpp @@ -1,54 +1,59 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanos - -*/ -#include "leetcode_1277_test.hpp" #include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1277 { using std::vector; +#endif -int32_t leetcode_1277::countSquares(const vector> &matrix) { - const auto row{matrix.size()}; - if (0 == row) { - return 0; - } - const auto column{matrix.front().size()}; - if (0 == column) { - return 0; - } - vector> dp(row, vector(column, 0)); - // dp[i][j] 代表以dp[i][j]这个点为右下角的最大正方形的面积 - // dp[0][j],dp[i][0] 最大值都是1 - int32_t will_return{0}; - for (size_t i{0}; i < column; ++i) { - dp[0][i] = (matrix[0][i] == 1 ? 1 : 0); - will_return += dp[0][i]; - } - for (size_t j{1}; j < row; ++j) { - dp[j][0] = (matrix[j][0] == 1 ? 1 : 0); - will_return += dp[j][0]; - } - for (size_t i{1}; i < row; ++i) { - for (size_t j{1}; j < column; ++j) { - if (matrix[i][j] == 0) { - dp[i][j] = 0; - } else { - // 这里是重点,决定递推关系 - // 首先,判断递推顺序,换句话讲, 查看已有信息 - // 很常见的推论: dp[i][j] 依赖dp[i-1][j-1],dp[i][j-1],dp[i-1][j] - // 接着要拿到递推关系式, 先分别将三个依赖取到0,其他任意,会发现此时dp[i][j]只能取1 - // 再将三个依赖分别取到极大值, 其他的任意,会发现dp[i][j]依赖于其中的最小值 - // 得出:1. 三个值和位置无关,可以替换; 2. 和最小值有关 - // 得出结论 - dp[i][j] = std::min({dp[i][j - 1], dp[i - 1][j - 1], dp[i - 1][j]}) + 1; - will_return += dp[i][j]; +class Solution { +public: + int32_t countSquares(const vector> &matrix) { + const auto row{matrix.size()}; + if (0 == row) { + return 0; + } + const auto column{matrix.front().size()}; + if (0 == column) { + return 0; + } + vector> dp(row, vector(column, 0)); + // dp[i][j] 代表以dp[i][j]这个点为右下角的最大正方形的面积 + // dp[0][j],dp[i][0] 最大值都是1 + int32_t will_return{0}; + for (size_t i{0}; i < column; ++i) { + dp[0][i] = (matrix[0][i] == 1 ? 1 : 0); + will_return += dp[0][i]; + } + for (size_t j{1}; j < row; ++j) { + dp[j][0] = (matrix[j][0] == 1 ? 1 : 0); + will_return += dp[j][0]; + } + for (size_t i{1}; i < row; ++i) { + for (size_t j{1}; j < column; ++j) { + if (matrix[i][j] == 0) { + dp[i][j] = 0; + } else { + // 这里是重点,决定递推关系 + // 首先,判断递推顺序,换句话讲, 查看已有信息 + // 很常见的推论: dp[i][j] 依赖dp[i-1][j-1],dp[i][j-1],dp[i-1][j] + // 接着要拿到递推关系式, 先分别将三个依赖取到0,其他任意,会发现此时dp[i][j]只能取1 + // 再将三个依赖分别取到极大值, 其他的任意,会发现dp[i][j]依赖于其中的最小值 + // 得出:1. 三个值和位置无关,可以替换; 2. 和最小值有关 + // 得出结论 + dp[i][j] = std::min({dp[i][j - 1], dp[i - 1][j - 1], dp[i - 1][j]}) + 1; + will_return += dp[i][j]; + } } } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_1277_test.cpp b/algorithm/dp/leetcode_1277_test.cpp new file mode 100644 index 00000000..e14c399d --- /dev/null +++ b/algorithm/dp/leetcode_1277_test.cpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1277_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1277_TEST_CPP + +#include +#include "leetcode_1277.cpp" + +namespace leetcode_1277 { +using std::string; + +using Catch::Matchers::Equals; + +TEST_CASE("1 [test_1277]", "[test_1277]") { + const vector> matrix{ + {0, 1, 1}, + {1, 1, 0}, + {1, 0, 1} + }; + constexpr const auto result{6}; + Solution solution; + const auto output{solution.countSquares(matrix)}; + CHECK(output == result); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1277_TEST_CPP diff --git a/algorithm/dp/leetcode_1277_test.hpp b/algorithm/dp/leetcode_1277_test.hpp deleted file mode 100644 index dabe8ff2..00000000 --- a/algorithm/dp/leetcode_1277_test.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanos - -*/ -//@Tag DP -//@Tag 动态规划 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1277_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1277_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_1277 { -using std::string; - -namespace leetcode_1277 { -int32_t countSquares(const vector> &matrix); -} - -using Catch::Matchers::Equals; - -TEST_CASE("1 [test_1277]", "[test_1277]") { - const vector> matrix{ - {0, 1, 1}, - {1, 1, 0}, - {1, 0, 1} - }; - constexpr const auto result{6}; - const auto output{leetcode_1277::countSquares(matrix)}; - CHECK(output == result); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1277_TEST_CPP diff --git a/algorithm/dp/leetcode_1314.cpp b/algorithm/dp/leetcode_1314.cpp new file mode 100644 index 00000000..86b6ab36 --- /dev/null +++ b/algorithm/dp/leetcode_1314.cpp @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + +#ifdef ALGORITHM_TEST_MACRO + +#include +#include +#include + +namespace leetcode_1314 { +using std::vector; +#endif + +class Solution { +private: + vector> init(const vector> &matrix) { + if (matrix.empty() || matrix.front().empty()) { + return {}; + } + const auto row{matrix.size()}, col{matrix.front().size()}; + vector> range(row + 1, vector(col + 1)); + for (size_t i{0}; i < row; i++) { + for (size_t j{0}; j < col; j++) { + range[i + 1][j + 1] = range[i][j + 1] + range[i + 1][j] - range[i][j] + matrix[i][j]; + } + } + return range; + } + +public: + vector> matrixBlockSum(const vector> &mat, int32_t K) { + if (mat.empty() || mat.front().empty()) { + return {}; + } + const auto k = static_cast(K); + const auto row{mat.size()}, col{mat.front().size()}; + const vector> dp{init(mat)}; + vector> will_return(row, vector(col)); + for (size_t i{0}; i < row; ++i) { + const size_t left{i > k ? i - k : 0}; + const size_t right{std::min(i + k, row - 1)}; + for (size_t j{0}; j < col; ++j) { + const size_t head{j > k ? j - k : 0}; + const size_t loot{std::min(j + k, col - 1)}; + will_return[i][j] = dp[right + 1][loot + 1] - dp[left][loot + 1] - dp[right + 1][head] + + dp[left][head]; + } + } + return will_return; + } +}; + +#ifdef ALGORITHM_TEST_MACRO +} +#endif diff --git a/algorithm/dp/leetcode_304_1314_test.hpp b/algorithm/dp/leetcode_1314_test.cpp similarity index 51% rename from algorithm/dp/leetcode_304_1314_test.hpp rename to algorithm/dp/leetcode_1314_test.cpp index 763e1bb2..4d9aa268 100644 --- a/algorithm/dp/leetcode_304_1314_test.hpp +++ b/algorithm/dp/leetcode_1314_test.cpp @@ -1,30 +1,18 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Description 经典小学数学题,交叉部分算面积 //@Plan 动态规划入门 Day14 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1314_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1314_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1314_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1314_TEST_CPP #include -#include -#include -#include -#include +#include "leetcode_1314.cpp" namespace leetcode_1314 { using std::vector; -struct leetcode_1314 { - static vector> matrixBlockSum(const vector> &mat, int32_t K); -}; - using Catch::Matchers::Equals; TEST_CASE("1 [test_1314]", "[test_1314]") { @@ -35,12 +23,13 @@ TEST_CASE("1 [test_1314]", "[test_1314]") { const vector> result1{{12, 21, 16}, {27, 45, 33,}, {24, 39, 28}}; - CHECK_THAT(result1, Equals(leetcode_1314::matrixBlockSum(input, k1))); + Solution solution; + CHECK_THAT(result1, Equals(solution.matrixBlockSum(input, k1))); static constexpr const auto k2{2}; const vector> result2{{45, 45, 45}, {45, 45, 45,}, {45, 45, 45}}; - CHECK_THAT(result2, Equals(leetcode_1314::matrixBlockSum(input, k2))); + CHECK_THAT(result2, Equals(solution.matrixBlockSum(input, k2))); } TEST_CASE("2 [test_1314]", "[test_1314]") { @@ -55,35 +44,10 @@ TEST_CASE("2 [test_1314]", "[test_1314]") { {383, 522, 335}, {340, 486, 343}, {212, 312, 251}}; - CHECK_THAT(result, Equals(leetcode_1314::matrixBlockSum(input, k))); -} - -} - -namespace leetcode_304 { -class NumMatrix : private nonCopyMoveAble { -private: - const vector> sumRange; -public: - explicit NumMatrix(const vector> &matrix); - - int32_t sumRegion(int32_t row1, int32_t col1, int32_t row2, int32_t col2) const; -}; - -TEST_CASE("1 [test_304]", "[test_304]") { - const vector> input{ - {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}}; - const auto matrix{std::make_unique(input)}; - static constexpr const auto result1{8}, result2{11}, result3{12}; - CHECK(result1 == matrix->sumRegion(2, 1, 4, 3)); - CHECK(result2 == matrix->sumRegion(1, 1, 2, 2)); - CHECK(result3 == matrix->sumRegion(1, 2, 2, 4)); + Solution solution; + CHECK_THAT(result, Equals(solution.matrixBlockSum(input, k))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1314_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1314_TEST_CPP diff --git a/algorithm/dp/leetcode_139.cpp b/algorithm/dp/leetcode_139.cpp index 1c014b52..6236de67 100644 --- a/algorithm/dp/leetcode_139.cpp +++ b/algorithm/dp/leetcode_139.cpp @@ -1,38 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos -*/ -#include "leetcode_139_test.hpp" +#include +#include +#include +#include #include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_139 { +using std::string; +using std::vector; using trieIter::trie; +#endif -bool leetcode_139::wordBreak(const string &s, const vector &wordDict) { - const auto s_size{s.size()}; - size_t wordMin{0x3f3f3f3f}; - trie Trie{}; - for (const auto &word: wordDict) { - Trie.insert(word.cbegin(), word.cend()); - wordMin = std::min(wordMin, word.size()); - } - if (s_size < wordMin) { - return false; // can not even spell into smallest word - } - vector dp(s_size + 1, false); - //dp[i] => the ith word match or not - dp[0] = true; - for (size_t i{1}; i <= s_size; i++) { - for (size_t j{0}; j < i; j++) { - dp[i] = dp[i] || - (dp[j] && Trie.search(s.cbegin() + j, s.cbegin() + i)); +class Solution { +public: + bool wordBreak(const string &s, const vector &wordDict) { + const auto s_size{s.size()}; + size_t wordMin{0x3f3f3f3f}; + trie Trie{}; + for (const auto &word: wordDict) { + Trie.insert(word.cbegin(), word.cend()); + wordMin = std::min(wordMin, word.size()); + } + if (s_size < wordMin) { + return false; // can not even spell into smallest word } + vector dp(s_size + 1, false); + //dp[i] => the ith word match or not + dp[0] = true; + for (size_t i{1}; i <= s_size; i++) { + for (size_t j{0}; j < i; j++) { + dp[i] = dp[i] || + (dp[j] && Trie.search(s.cbegin() + j, s.cbegin() + i)); + } + } + return dp.back(); } - return dp.back(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_139_test.hpp b/algorithm/dp/leetcode_139_test.cpp similarity index 53% rename from algorithm/dp/leetcode_139_test.hpp rename to algorithm/dp/leetcode_139_test.cpp index aa1d7c9d..8dbb8147 100644 --- a/algorithm/dp/leetcode_139_test.hpp +++ b/algorithm/dp/leetcode_139_test.cpp @@ -1,48 +1,39 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Tag Trie //@Tag 字典树 //@Plan 动态规划入门 Day9 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_139_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_139_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_139_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_139_TEST_CPP #include -#include -#include -#include -#include +#include "leetcode_139.cpp" namespace leetcode_139 { using std::vector; using std::string; -struct leetcode_139 final { - static bool wordBreak(const string &s, const vector &wordDict); -}; - TEST_CASE("1 [test_139]", "[test_139]") { static constexpr const char *const input{"leetcode"}; static constexpr const std::array wordDict{"leet", "code"}; - CHECK(leetcode_139::wordBreak(input, {std::cbegin(wordDict), std::cend(wordDict)})); + Solution solution; + CHECK(solution.wordBreak(input, {std::cbegin(wordDict), std::cend(wordDict)})); } TEST_CASE("2 [test_139]", "[test_139]") { static constexpr const char *const input{"applepenapple"}; static constexpr const std::array wordDict{"apple", "pen"}; - CHECK(leetcode_139::wordBreak(input, {std::cbegin(wordDict), std::cend(wordDict)})); + Solution solution; + CHECK(solution.wordBreak(input, {std::cbegin(wordDict), std::cend(wordDict)})); } TEST_CASE("3 [test_139]", "[test_139]") { static constexpr const char *const input{"catsandog"}; static constexpr const std::array wordDict{"cats", "dog", "sand", "and", "cat"}; - CHECK_FALSE(leetcode_139::wordBreak(input, {std::cbegin(wordDict), std::cend(wordDict)})); + Solution solution; + CHECK_FALSE(solution.wordBreak(input, {std::cbegin(wordDict), std::cend(wordDict)})); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_139_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_139_TEST_CPP diff --git a/algorithm/dp/leetcode_152.cpp b/algorithm/dp/leetcode_152.cpp index 4674899b..2c766123 100644 --- a/algorithm/dp/leetcode_152.cpp +++ b/algorithm/dp/leetcode_152.cpp @@ -1,66 +1,74 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_152_test.hpp" +#include +#include +#include +#include namespace leetcode_152 { +using std::vector; +#endif -int32_t leetcode_152::maxProduct(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size == 0) { - return 0; - } else if (nums_size == 1) { - return nums[0]; - } - vector dpMax(nums_size + 1, 0), dpMin(nums_size + 1, 0); - dpMax[0] = 0; // 以第0个结尾的一定是0 - dpMin[0] = 0; // 以第0个结尾的一定是0 - dpMax[1] = nums[0]; // 以第一个结尾的一定是nums[0] - dpMin[1] = nums[0]; // 以第一个结尾的一定是nums[0] - int32_t maxV{nums[0]}; - for (size_t i{2}; i <= nums_size; i++) { - if (nums[i - 1] > 0) { - dpMax[i] = std::max(dpMax[i - 1] * nums[i - 1], nums[i - 1]); - dpMin[i] = std::min(dpMin[i - 1] * nums[i - 1], nums[i - 1]); - } else if (nums[i - 1] == 0) { - dpMax[i] = 0; - dpMin[i] = 0; - } else { - dpMax[i] = std::max(dpMin[i - 1] * nums[i - 1], nums[i - 1]); - dpMin[i] = std::min(dpMax[i - 1] * nums[i - 1], nums[i - 1]); - // 这里其实考虑到了对称性, 先确认了dpMax,再确认的dpMin +class Solution { +public: + int32_t maxProduct(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size == 0) { + return 0; + } else if (nums_size == 1) { + return nums[0]; } - maxV = std::max(maxV, dpMax[i]); + vector dpMax(nums_size + 1, 0), dpMin(nums_size + 1, 0); + dpMax[0] = 0; // 以第0个结尾的一定是0 + dpMin[0] = 0; // 以第0个结尾的一定是0 + dpMax[1] = nums[0]; // 以第一个结尾的一定是nums[0] + dpMin[1] = nums[0]; // 以第一个结尾的一定是nums[0] + int32_t maxV{nums[0]}; + for (size_t i{2}; i <= nums_size; i++) { + if (nums[i - 1] > 0) { + dpMax[i] = std::max(dpMax[i - 1] * nums[i - 1], nums[i - 1]); + dpMin[i] = std::min(dpMin[i - 1] * nums[i - 1], nums[i - 1]); + } else if (nums[i - 1] == 0) { + dpMax[i] = 0; + dpMin[i] = 0; + } else { + dpMax[i] = std::max(dpMin[i - 1] * nums[i - 1], nums[i - 1]); + dpMin[i] = std::min(dpMax[i - 1] * nums[i - 1], nums[i - 1]); + // 这里其实考虑到了对称性, 先确认了dpMax,再确认的dpMin + } + maxV = std::max(maxV, dpMax[i]); + } + return maxV; } - return maxV; -} -int32_t leetcode_152::maxProduct2(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size == 0) { - return 0; - } else if (nums_size == 1) { - return nums[0]; - } - int32_t aMax{nums[0]}, bMax, maxV{nums[0]}; - int32_t aMin{nums[0]}, bMin; - // 滚 动 数 组 - for (size_t i{2}; i <= nums_size; maxV = std::max(maxV, bMax), i++, aMax = bMax, aMin = bMin) { - if (nums[i - 1] > 0) { - bMax = std::max(aMax * nums[i - 1], nums[i - 1]); - bMin = std::min(aMin * nums[i - 1], nums[i - 1]); - } else if (nums[i - 1] == 0) { - bMax = 0; - bMin = 0; - } else { - bMax = std::max(aMin * nums[i - 1], nums[i - 1]); - bMin = std::min(aMax * nums[i - 1], nums[i - 1]); + int32_t maxProduct2(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size == 0) { + return 0; + } else if (nums_size == 1) { + return nums[0]; + } + int32_t aMax{nums[0]}, bMax, maxV{nums[0]}; + int32_t aMin{nums[0]}, bMin; + // 滚 动 数 组 + for (size_t i{2}; i <= nums_size; maxV = std::max(maxV, bMax), i++, aMax = bMax, aMin = bMin) { + if (nums[i - 1] > 0) { + bMax = std::max(aMax * nums[i - 1], nums[i - 1]); + bMin = std::min(aMin * nums[i - 1], nums[i - 1]); + } else if (nums[i - 1] == 0) { + bMax = 0; + bMin = 0; + } else { + bMax = std::max(aMin * nums[i - 1], nums[i - 1]); + bMin = std::min(aMax * nums[i - 1], nums[i - 1]); + } } + return maxV; } - return maxV; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_152_test.cpp b/algorithm/dp/leetcode_152_test.cpp new file mode 100644 index 00000000..49ef074d --- /dev/null +++ b/algorithm/dp/leetcode_152_test.cpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day6 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_152_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_152_TEST_CPP + +#include +#include "leetcode_152.cpp" + +namespace leetcode_152 { +using std::vector; + +TEST_CASE("1 [test_152]", "[test_152]") { + const vector input{1, 5, 11, 5}; + static constexpr const auto result{275}; + Solution solution; + CHECK(result == solution.maxProduct(input)); + CHECK(result == solution.maxProduct2(input)); +} + +TEST_CASE("2 [test_152]", "[test_152]") { + const vector input{-2, 0, -1}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.maxProduct(input)); + CHECK(result == solution.maxProduct2(input)); +} + +TEST_CASE("3 [test_152]", "[test_152]") { + const vector input{2, 3, -2, 4}; + static constexpr const auto result{6}; + Solution solution; + CHECK(result == solution.maxProduct(input)); + CHECK(result == solution.maxProduct2(input)); +} + +TEST_CASE("4 [test_152]", "[test_152]") { + const vector input{-2, 4, -3}; + static constexpr const auto result{24}; + Solution solution; + CHECK(result == solution.maxProduct(input)); + CHECK(result == solution.maxProduct2(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_152_TEST_CPP diff --git a/algorithm/dp/leetcode_152_test.hpp b/algorithm/dp/leetcode_152_test.hpp deleted file mode 100644 index c69cbe27..00000000 --- a/algorithm/dp/leetcode_152_test.hpp +++ /dev/null @@ -1,57 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day6 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_152_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_152_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_152 { -using std::vector; - -struct leetcode_152 final { - static int32_t maxProduct(const vector &nums); - - static int32_t maxProduct2(const vector &nums); -}; - - -TEST_CASE("1 [test_152]", "[test_152]") { - const vector input{1, 5, 11, 5}; - static constexpr const auto result{275}; - CHECK(result == leetcode_152::maxProduct(input)); - CHECK(result == leetcode_152::maxProduct2(input)); -} - -TEST_CASE("2 [test_152]", "[test_152]") { - const vector input{-2, 0, -1}; - static constexpr const auto result{0}; - CHECK(result == leetcode_152::maxProduct(input)); - CHECK(result == leetcode_152::maxProduct2(input)); -} - -TEST_CASE("3 [test_152]", "[test_152]") { - const vector input{2, 3, -2, 4}; - static constexpr const auto result{6}; - CHECK(result == leetcode_152::maxProduct(input)); - CHECK(result == leetcode_152::maxProduct2(input)); -} - -TEST_CASE("4 [test_152]", "[test_152]") { - const vector input{-2, 4, -3}; - static constexpr const auto result{24}; - CHECK(result == leetcode_152::maxProduct(input)); - CHECK(result == leetcode_152::maxProduct2(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_152_TEST_CPP diff --git a/algorithm/dp/leetcode_1567.cpp b/algorithm/dp/leetcode_1567.cpp index ae06c44d..42fcd7f9 100644 --- a/algorithm/dp/leetcode_1567.cpp +++ b/algorithm/dp/leetcode_1567.cpp @@ -1,44 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2021-2022 nanos - -*/ -#include "leetcode_1567_test.hpp" +// SPDX-FileCopyrightText: 2021-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1567 { +using std::vector; +#endif -int32_t leetcode_1567::getMaxLen(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size == 0) { - return 0; - } else if (nums_size == 1) { - return nums[0] > 0 ? 1 : 0; - } - vector dpPos(nums_size + 1, 0), dpNeg(nums_size + 1, 0); - dpPos[0] = 0, dpNeg[0] = 0;// 以第0个结尾一定是0 - dpPos[1] = nums[0] > 0 ? 1 : 0; // 第一个结尾的话,正则1,否则0 - dpNeg[1] = nums[0] < 0 ? 1 : 0; // 第一个结尾的话,正则1,否则0 - for (size_t i{2}; i <= nums_size; i++) { - if (nums[i - 1] == 0) { - dpPos[i] = 0; - dpNeg[i] = 0; - } else if (nums[i - 1] > 0) { - // 这个是正数,则取决于上一个结尾的最大正乘积长度 - dpPos[i] = dpPos[i - 1] + 1; - // 这种情况下,上一个结尾的最大负乘积长度得先存在才能+1 - if (dpNeg[i - 1] > 0) { - dpNeg[i] = dpNeg[i - 1] + 1; - } - } else if (nums[i - 1] < 0) { - if (dpNeg[i - 1] > 0) { - dpPos[i] = dpNeg[i - 1] + 1; +class Solution { +public: + int32_t getMaxLen(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size == 0) { + return 0; + } else if (nums_size == 1) { + return nums[0] > 0 ? 1 : 0; + } + vector dpPos(nums_size + 1, 0), dpNeg(nums_size + 1, 0); + dpPos[0] = 0, dpNeg[0] = 0;// 以第0个结尾一定是0 + dpPos[1] = nums[0] > 0 ? 1 : 0; // 第一个结尾的话,正则1,否则0 + dpNeg[1] = nums[0] < 0 ? 1 : 0; // 第一个结尾的话,正则1,否则0 + for (size_t i{2}; i <= nums_size; i++) { + if (nums[i - 1] == 0) { + dpPos[i] = 0; + dpNeg[i] = 0; + } else if (nums[i - 1] > 0) { + // 这个是正数,则取决于上一个结尾的最大正乘积长度 + dpPos[i] = dpPos[i - 1] + 1; + // 这种情况下,上一个结尾的最大负乘积长度得先存在才能+1 + if (dpNeg[i - 1] > 0) { + dpNeg[i] = dpNeg[i - 1] + 1; + } + } else if (nums[i - 1] < 0) { + if (dpNeg[i - 1] > 0) { + dpPos[i] = dpNeg[i - 1] + 1; + } + dpNeg[i] = dpPos[i - 1] + 1; } - dpNeg[i] = dpPos[i - 1] + 1; } + return *std::max_element(dpPos.cbegin(), dpPos.cend()); } - return *std::max_element(dpPos.cbegin(), dpPos.cend()); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_1567_test.hpp b/algorithm/dp/leetcode_1567_test.cpp similarity index 57% rename from algorithm/dp/leetcode_1567_test.hpp rename to algorithm/dp/leetcode_1567_test.cpp index 5e3ca1de..9bc1463a 100644 --- a/algorithm/dp/leetcode_1567_test.hpp +++ b/algorithm/dp/leetcode_1567_test.cpp @@ -1,58 +1,52 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day6 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1567_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1567_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1567_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1567_TEST_CPP #include -#include -#include -#include +#include "leetcode_1567.cpp" namespace leetcode_1567 { using std::vector; -struct leetcode_1567 { - static int32_t getMaxLen(const vector &nums); -}; - TEST_CASE("1 [test_1567]", "[test_1567]") { const vector input{1, -2, -3, 4}; static constexpr const auto result{4}; - CHECK(result == leetcode_1567::getMaxLen(input)); + Solution solution; + CHECK(result == solution.getMaxLen(input)); } TEST_CASE("2 [test_1567]", "[test_1567]") { const vector input{0, 1, -2, -3, -4}; static constexpr const auto result{3}; - CHECK(result == leetcode_1567::getMaxLen(input)); + Solution solution; + CHECK(result == solution.getMaxLen(input)); } TEST_CASE("3 [test_1567]", "[test_1567]") { const vector input{-1, -2, -3, 0, 1}; static constexpr const auto result{2}; - CHECK(result == leetcode_1567::getMaxLen(input)); + Solution solution; + CHECK(result == solution.getMaxLen(input)); } TEST_CASE("4 [test_1567]", "[test_1567]") { const vector input{-1, 2}; static constexpr const auto result{1}; - CHECK(result == leetcode_1567::getMaxLen(input)); + Solution solution; + CHECK(result == solution.getMaxLen(input)); } TEST_CASE("5 [test_1567]", "[test_1567]") { const vector input{1, 2, 3, 5, -6, 4, 0, 10}; static constexpr const auto result{4}; - CHECK(result == leetcode_1567::getMaxLen(input)); + Solution solution; + CHECK(result == solution.getMaxLen(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_1567_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_1567_TEST_CPP diff --git a/algorithm/dp/leetcode_174.cpp b/algorithm/dp/leetcode_174.cpp index c8ab2808..5a1f2d88 100644 --- a/algorithm/dp/leetcode_174.cpp +++ b/algorithm/dp/leetcode_174.cpp @@ -1,38 +1,45 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_174_test.hpp" +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_174 { +using std::vector; +#endif -int32_t leetcode_174::calculateMinimumHP(const vector> &dungeon) { - if (dungeon.empty() || dungeon.front().empty()) { - return 0; - } - const auto m{dungeon.size()}, n{dungeon.front().size()}; - vector> dp(m + 1, vector(n + 1, 0)); - for (size_t i{m}; i > 0; i--) { - for (size_t j{n}; j > 0; j--) { - dp[i][j] = dungeon[i - 1][j - 1]; +class Solution { +public: + int32_t calculateMinimumHP(const vector> &dungeon) { + if (dungeon.empty() || dungeon.front().empty()) { + return 0; } - } - // i,j -> 到i,j点时,可以到达终点的最低血量. - dp[m][n] = std::max(1 - dp[m][n], 1); - for (size_t i{m - 1}; i > 0; i--) { - dp[i].back() = std::max(dp[i + 1].back() - dp[i].back(), 1); - } - for (size_t i{n - 1}; i > 0; i--) { - dp.back()[i] = std::max(dp.back()[i + 1] - dp.back()[i], 1); - } - for (size_t i{m - 1}; i > 0; i--) { - for (size_t j{n - 1}; j > 0; j--) { - dp[i][j] = std::max(std::min(dp[i + 1][j], dp[i][j + 1]) - dp[i][j], 1); + const auto m{dungeon.size()}, n{dungeon.front().size()}; + vector> dp(m + 1, vector(n + 1, 0)); + for (size_t i{m}; i > 0; i--) { + for (size_t j{n}; j > 0; j--) { + dp[i][j] = dungeon[i - 1][j - 1]; + } } + // i,j -> 到i,j点时,可以到达终点的最低血量. + dp[m][n] = std::max(1 - dp[m][n], 1); + for (size_t i{m - 1}; i > 0; i--) { + dp[i].back() = std::max(dp[i + 1].back() - dp[i].back(), 1); + } + for (size_t i{n - 1}; i > 0; i--) { + dp.back()[i] = std::max(dp.back()[i + 1] - dp.back()[i], 1); + } + for (size_t i{m - 1}; i > 0; i--) { + for (size_t j{n - 1}; j > 0; j--) { + dp[i][j] = std::max(std::min(dp[i + 1][j], dp[i][j + 1]) - dp[i][j], 1); + } + } + return dp[1][1]; } - return dp[1][1]; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_174_test.hpp b/algorithm/dp/leetcode_174_test.cpp similarity index 52% rename from algorithm/dp/leetcode_174_test.hpp rename to algorithm/dp/leetcode_174_test.cpp index d6d84364..3b9e7d27 100644 --- a/algorithm/dp/leetcode_174_test.hpp +++ b/algorithm/dp/leetcode_174_test.cpp @@ -1,46 +1,38 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_174_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_174_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_174_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_174_TEST_CPP #include -#include -#include -#include +#include "leetcode_174.cpp" namespace leetcode_174 { using std::vector; -struct leetcode_174 final { - static int32_t calculateMinimumHP(const vector> &dungeon); -}; - TEST_CASE("1 [test_174]", "[test_174]") { const vector> inputs{{-2, -3, 3}, {-5, -10, 1}, {10, 30, -5}}; static constexpr const auto result{7}; - CHECK(result == leetcode_174::calculateMinimumHP(inputs)); + Solution solution; + CHECK(result == solution.calculateMinimumHP(inputs)); } TEST_CASE("2 [test_174]", "[test_174]") { const vector> inputs{{0, -3}}; static constexpr const auto result{4}; - CHECK(result == leetcode_174::calculateMinimumHP(inputs)); + Solution solution; + CHECK(result == solution.calculateMinimumHP(inputs)); } TEST_CASE("3 [test_174]", "[test_174]") { const vector> inputs{{0}}; static constexpr const auto result{1}; - CHECK(result == leetcode_174::calculateMinimumHP(inputs)); + Solution solution; + CHECK(result == solution.calculateMinimumHP(inputs)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_174_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_174_TEST_CPP diff --git a/algorithm/dp/leetcode_198.cpp b/algorithm/dp/leetcode_198.cpp new file mode 100644 index 00000000..c0fee6f2 --- /dev/null +++ b/algorithm/dp/leetcode_198.cpp @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + +#ifdef ALGORITHM_TEST_MACRO +namespace leetcode_198 { +using std::vector; +#endif + +class Solution { +public: + int64_t rob(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size <= 1) { + return nums[0]; + } + vector dp(nums_size + 1, 0); // 取得0个 只能得0 + dp[1] = nums[0];// then nums_size >= 2 + for (size_t i{2}; i <= nums_size; i++) { + dp[i] = std::max(dp[i - 2] + nums[i - 1], dp[i - 1]); + } + return dp.back(); + } + + int64_t rob2(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size <= 1) { + return nums[0]; + } + std::array dp{0, nums[0], 0}; + // 滚 动 数 组 + for (size_t i{2}; i <= nums_size; i++, dp[1] = dp[2]) { + dp[2] = std::max(dp[0] + nums[i - 1], dp[1]); + dp[0] = dp[1]; // 不确保执行顺序,所以不能都放过去 + } + return dp[2]; + } +}; + +#ifdef ALGORITHM_TEST_MACRO +} +#endif \ No newline at end of file diff --git a/algorithm/dp/leetcode_198_213.cpp b/algorithm/dp/leetcode_198_213.cpp deleted file mode 100644 index 47d0cdfa..00000000 --- a/algorithm/dp/leetcode_198_213.cpp +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_198_213_test.hpp" - -namespace leetcode_198 { - -int64_t leetcode_198::rob(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size <= 1) { - return nums[0]; - } - vector dp(nums_size + 1, 0); // 取得0个 只能得0 - dp[1] = nums[0];// then nums_size >= 2 - for (size_t i{2}; i <= nums_size; i++) { - dp[i] = std::max(dp[i - 2] + nums[i - 1], dp[i - 1]); - } - return dp.back(); -} - -int64_t leetcode_198::rob2(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size <= 1) { - return nums[0]; - } - std::array dp{0, nums[0], 0}; - // 滚 动 数 组 - for (size_t i{2}; i <= nums_size; i++, dp[1] = dp[2]) { - dp[2] = std::max(dp[0] + nums[i - 1], dp[1]); - dp[0] = dp[1]; // 不确保执行顺序,所以不能都放过去 - } - return dp[2]; -} -} -namespace leetcode_213 { - -int64_t leetcode_213::rob(const vector &nums) { - const auto nums_size{nums.size()}; - vector values(nums); - if (nums_size <= 1) { - return values[0]; - } - vector dp(nums_size + 1, 0); // 取得0个 只能得0 - dp[1] = 0;// then nums_size >= 2 - values[0] = 0; - for (size_t i{2}; i <= nums_size; i++) { - dp[i] = std::max(dp[i - 2] + values[i - 1], dp[i - 1]); - } - const auto nums1{dp.back()}; // 置首个为0, 弃用的结果 - values[0] = nums[0]; - std::fill(std::begin(dp), std::end(dp), 0); - dp[1] = values[0]; - values[nums_size - 1] = 0; - for (size_t i{2}; i <= nums_size; i++) { - dp[i] = std::max(dp[i - 2] + values[i - 1], dp[i - 1]); - } - const auto nums2{dp.back()};// 置末尾为0, 弃用的结果 - return std::max(nums1, nums2); -} - -int64_t leetcode_213::rob2(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size <= 1) { - return nums[0]; - } - const vector vec1{nums.cbegin(), nums.cend() - 1}; - const vector vec2{nums.cbegin() + 1, nums.cend()}; - return std::max(leetcode_198::leetcode_198::rob2(vec1), leetcode_198::leetcode_198::rob2(vec2)); -} -} diff --git a/algorithm/dp/leetcode_198_213_test.hpp b/algorithm/dp/leetcode_198_213_test.hpp deleted file mode 100644 index 47e37162..00000000 --- a/algorithm/dp/leetcode_198_213_test.hpp +++ /dev/null @@ -1,79 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day3 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_198_213_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_198_213_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_198 { -using std::vector; - -struct leetcode_198 final { - static int64_t rob(const vector &nums); - - static int64_t rob2(const vector &nums); -}; - -TEST_CASE("1 [test_198]", "[test_198]") { - const vector input{1, 2, 3, 1}; - static constexpr const auto output{static_cast(4)}; - CHECK(output == leetcode_198::rob(input)); - CHECK(output == leetcode_198::rob2(input)); -} - -TEST_CASE("2 [test_198]", "[test_198]") { - const vector input{2, 7, 9, 3, 1}; - static constexpr const auto output{static_cast(12)}; - CHECK(output == leetcode_198::rob(input)); - CHECK(output == leetcode_198::rob2(input)); -} - -TEST_CASE("3 [test_198]", "[test_198]") { - const vector input{1, 1}; - static constexpr const auto output{static_cast(1)}; - CHECK(output == leetcode_198::rob(input)); - CHECK(output == leetcode_198::rob2(input)); -} -} -namespace leetcode_213 { -using std::vector; - -struct leetcode_213 final { - static int64_t rob(const vector &nums); - - static int64_t rob2(const vector &nums); -}; - -TEST_CASE("1 [test_213]", "[test_213]") { - const vector input{2, 3, 2}; - static constexpr const auto output{static_cast(3)}; - CHECK(output == leetcode_213::rob(input)); - CHECK(output == leetcode_213::rob2(input)); -} - -TEST_CASE("2 [test_213]", "[test_213]") { - const vector input{1, 2, 3, 1}; - static constexpr const auto output{static_cast(4)}; - CHECK(output == leetcode_213::rob(input)); - CHECK(output == leetcode_213::rob2(input)); -} - -TEST_CASE("3 [test_213]", "[test_213]") { - const vector input{1, 1}; - static constexpr const auto output{static_cast(1)}; - CHECK(output == leetcode_213::rob(input)); - CHECK(output == leetcode_213::rob2(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_198_213_TEST_CPP diff --git a/algorithm/dp/leetcode_198_test.cpp b/algorithm/dp/leetcode_198_test.cpp new file mode 100644 index 00000000..58f1c2d1 --- /dev/null +++ b/algorithm/dp/leetcode_198_test.cpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day3 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_198_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_198_TEST_CPP + +#include +#include "leetcode_198.cpp" + +namespace leetcode_198 { +using std::vector; + +TEST_CASE("1 [test_198]", "[test_198]") { + const vector input{1, 2, 3, 1}; + static constexpr const auto output{static_cast(4)}; + Solution solution; + CHECK(output == solution.rob(input)); + CHECK(output == solution.rob2(input)); +} + +TEST_CASE("2 [test_198]", "[test_198]") { + const vector input{2, 7, 9, 3, 1}; + static constexpr const auto output{static_cast(12)}; + Solution solution; + CHECK(output == solution.rob(input)); + CHECK(output == solution.rob2(input)); +} + +TEST_CASE("3 [test_198]", "[test_198]") { + const vector input{1, 1}; + static constexpr const auto output{static_cast(1)}; + Solution solution; + CHECK(output == solution.rob(input)); + CHECK(output == solution.rob2(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_198_TEST_CPP diff --git a/algorithm/dp/leetcode_213.cpp b/algorithm/dp/leetcode_213.cpp new file mode 100644 index 00000000..95c1287e --- /dev/null +++ b/algorithm/dp/leetcode_213.cpp @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + +#ifdef ALGORITHM_TEST_MACRO + +#include +#include +#include + +namespace leetcode_213 { +using std::vector; +#endif + +class Solution { +public: + int64_t rob(const vector &nums) { + const auto nums_size{nums.size()}; + vector values(nums); + if (nums_size <= 1) { + return values[0]; + } + vector dp(nums_size + 1, 0); // 取得0个 只能得0 + dp[1] = 0;// then nums_size >= 2 + values[0] = 0; + for (size_t i{2}; i <= nums_size; i++) { + dp[i] = std::max(dp[i - 2] + values[i - 1], dp[i - 1]); + } + const auto nums1{dp.back()}; // 置首个为0, 弃用的结果 + values[0] = nums[0]; + std::fill(std::begin(dp), std::end(dp), 0); + dp[1] = values[0]; + values[nums_size - 1] = 0; + for (size_t i{2}; i <= nums_size; i++) { + dp[i] = std::max(dp[i - 2] + values[i - 1], dp[i - 1]); + } + const auto nums2{dp.back()};// 置末尾为0, 弃用的结果 + return std::max(nums1, nums2); + } + +}; + +#ifdef ALGORITHM_TEST_MACRO +} +#endif diff --git a/algorithm/dp/leetcode_213_test.cpp b/algorithm/dp/leetcode_213_test.cpp new file mode 100644 index 00000000..7d9776b7 --- /dev/null +++ b/algorithm/dp/leetcode_213_test.cpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day3 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_213_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_213_TEST_CPP + +#include +#include "leetcode_213.cpp" + +namespace leetcode_213 { +using std::vector; + +TEST_CASE("1 [test_213]", "[test_213]") { + const vector input{2, 3, 2}; + static constexpr const auto output{static_cast(3)}; + Solution solution; + CHECK(output == solution.rob(input)); +} + +TEST_CASE("2 [test_213]", "[test_213]") { + const vector input{1, 2, 3, 1}; + static constexpr const auto output{static_cast(4)}; + Solution solution; + CHECK(output == solution.rob(input)); +} + +TEST_CASE("3 [test_213]", "[test_213]") { + const vector input{1, 1}; + static constexpr const auto output{static_cast(1)}; + Solution solution; + CHECK(output == solution.rob(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_213_TEST_CPP diff --git a/algorithm/dp/leetcode_221.cpp b/algorithm/dp/leetcode_221.cpp index 26812d7e..4b4c2f35 100644 --- a/algorithm/dp/leetcode_221.cpp +++ b/algorithm/dp/leetcode_221.cpp @@ -1,66 +1,74 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_221_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_221 { -static constexpr const auto base{'0'}; +using std::vector; +#endif -int32_t leetcode_221::maximalSquare(const vector> &matrix) { - if (matrix.empty() || matrix.front().empty()) { - return {}; - } - const auto row{matrix.size()}, col{matrix.front().size()}; - vector> range(row + 1, vector(col + 1)); - for (size_t i{0}; i < row; i++) { - for (size_t j{0}; j < col; j++) { - range[i + 1][j + 1] = range[i][j + 1] + range[i + 1][j] - range[i][j] + (matrix[i][j] - base); +class Solution { +private: + static constexpr const auto base{'0'}; + +public: + int32_t maximalSquare(const vector> &matrix) { + if (matrix.empty() || matrix.front().empty()) { + return {}; } - } - size_t maxV{0}; // O(mn*min(m,n)) - for (size_t i{1}; i <= row; i++) { - for (size_t j{1}; j <= col; j++) { - const auto leftUp{range[i - 1][j - 1]}; - size_t x{i + 1}, y{j + 1}; - if (matrix[i - 1][j - 1] != base) { - maxV = std::max(maxV, static_cast(1)); - while (x <= row && y <= col) { - const size_t diff = range[x][y] - range[i - 1][y] - range[x][j - 1] + leftUp; - if (diff != (x - i + 1) * (x - i + 1)) { - break; - } else { - maxV = std::max(maxV, diff); - x++, y++; + const auto row{matrix.size()}, col{matrix.front().size()}; + vector> range(row + 1, vector(col + 1)); + for (size_t i{0}; i < row; i++) { + for (size_t j{0}; j < col; j++) { + range[i + 1][j + 1] = range[i][j + 1] + range[i + 1][j] - range[i][j] + (matrix[i][j] - base); + } + } + size_t maxV{0}; // O(mn*min(m,n)) + for (size_t i{1}; i <= row; i++) { + for (size_t j{1}; j <= col; j++) { + const auto leftUp{range[i - 1][j - 1]}; + size_t x{i + 1}, y{j + 1}; + if (matrix[i - 1][j - 1] != base) { + maxV = std::max(maxV, static_cast(1)); + while (x <= row && y <= col) { + const size_t diff = range[x][y] - range[i - 1][y] - range[x][j - 1] + leftUp; + if (diff != (x - i + 1) * (x - i + 1)) { + break; + } else { + maxV = std::max(maxV, diff); + x++, y++; + } } } } } + return static_cast(maxV); } - return static_cast(maxV); -} -int32_t leetcode_221::maximalSquare2(const vector> &matrix) { - if (matrix.empty() || matrix.front().empty()) { - return {}; - } - const auto row{matrix.size()}, col{matrix.front().size()}; - vector> dp(row + 1, vector(col + 1)); - int32_t maxV{0}; - for (size_t i{0}; i < row; i++) { - for (size_t j{0}; j < col; j++) { - dp[i + 1][j + 1] = ( - matrix[i][j] == base ? - 0 - : - std::min({dp[i][j], dp[i + 1][j], dp[i][j + 1]}) + 1 - ); - maxV = std::max(maxV, dp[i + 1][j + 1]); + int32_t maximalSquare2(const vector> &matrix) { + if (matrix.empty() || matrix.front().empty()) { + return {}; + } + const auto row{matrix.size()}, col{matrix.front().size()}; + vector> dp(row + 1, vector(col + 1)); + int32_t maxV{0}; + for (size_t i{0}; i < row; i++) { + for (size_t j{0}; j < col; j++) { + dp[i + 1][j + 1] = ( + matrix[i][j] == base ? + 0 + : + std::min({dp[i][j], dp[i + 1][j], dp[i][j + 1]}) + 1 + ); + maxV = std::max(maxV, dp[i + 1][j + 1]); + } } + return maxV * maxV; } - return maxV * maxV; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_221_test.hpp b/algorithm/dp/leetcode_221_test.cpp similarity index 50% rename from algorithm/dp/leetcode_221_test.hpp rename to algorithm/dp/leetcode_221_test.cpp index 71ab5c8e..cbd4b991 100644 --- a/algorithm/dp/leetcode_221_test.hpp +++ b/algorithm/dp/leetcode_221_test.cpp @@ -1,38 +1,26 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day16 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_221_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_221_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_221_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_221_TEST_CPP #include -#include -#include -#include +#include "leetcode_221.cpp" namespace leetcode_221 { using std::vector; -struct leetcode_221 final { - static int32_t maximalSquare(const vector> &matrix); - - static int32_t maximalSquare2(const vector> &matrix); -}; - TEST_CASE("4 [test_221]", "[test_221]") { const vector> input{ {'1', '1'}, {'1', '1'}, }; static constexpr const auto result{4}; - CHECK(result == leetcode_221::maximalSquare(input)); - CHECK(result == leetcode_221::maximalSquare2(input)); + Solution solution; + CHECK(result == solution.maximalSquare(input)); + CHECK(result == solution.maximalSquare2(input)); } TEST_CASE("1 [test_221]", "[test_221]") { @@ -43,8 +31,9 @@ TEST_CASE("1 [test_221]", "[test_221]") { {'1', '0', '0', '1', '0'} }; static constexpr const auto result{4}; - CHECK(result == leetcode_221::maximalSquare(input)); - CHECK(result == leetcode_221::maximalSquare2(input)); + Solution solution; + CHECK(result == solution.maximalSquare(input)); + CHECK(result == solution.maximalSquare2(input)); } TEST_CASE("2 [test_221]", "[test_221]") { @@ -53,15 +42,17 @@ TEST_CASE("2 [test_221]", "[test_221]") { {'1', '0'}, }; static constexpr const auto result{1}; - CHECK(result == leetcode_221::maximalSquare(input)); - CHECK(result == leetcode_221::maximalSquare2(input)); + Solution solution; + CHECK(result == solution.maximalSquare(input)); + CHECK(result == solution.maximalSquare2(input)); } TEST_CASE("3 [test_221]", "[test_221]") { const vector> input{{'0'},}; static constexpr const auto result{0}; - CHECK(result == leetcode_221::maximalSquare(input)); - CHECK(result == leetcode_221::maximalSquare2(input)); + Solution solution; + CHECK(result == solution.maximalSquare(input)); + CHECK(result == solution.maximalSquare2(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_221_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_221_TEST_CPP diff --git a/algorithm/dp/leetcode_264.cpp b/algorithm/dp/leetcode_264.cpp index f51f943d..382c11a3 100644 --- a/algorithm/dp/leetcode_264.cpp +++ b/algorithm/dp/leetcode_264.cpp @@ -1,42 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_264_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_264 { +using std::vector; +#endif -int32_t leetcode_264::nthUglyNumber(int32_t n) { - vector dp(n + 1, 0); - dp[0] = 1; - const auto search = [&dp](int32_t range, double v) { - int32_t begin{0}, middle{0}, end{range}; - while (begin < end) { - middle = (end - begin) / 2 + begin; - const double dpV = dp[middle]; - if (dpV <= v) { - begin = middle + 1; - } else if (dpV > v) { - end = middle; +class Solution { +public: + int32_t nthUglyNumber(int32_t n) { + vector dp(n + 1, 0); + dp[0] = 1; + const auto search = [&dp](int32_t range, double v) { + int32_t begin{0}, middle{0}, end{range}; + while (begin < end) { + middle = (end - begin) / 2 + begin; + const double dpV = dp[middle]; + if (dpV <= v) { + begin = middle + 1; + } else if (dpV > v) { + end = middle; + } } + return begin; + }; + for (int32_t i{1}; i < n; i++) { + const double last = dp[i - 1]; + const auto div2{static_cast(last / 2)}, div3{ + static_cast(last / 3)}, div5{static_cast(last / 5)}; + int32_t maxDiv2{dp[search(i, div2)] * 2}, maxDiv3{dp[search(i, div3)] * 3}, maxDiv5{dp[search(i, div5)] * 5}; + maxDiv2 = maxDiv2 > dp[i - 1] ? maxDiv2 : 0x3f3f3f3f; + maxDiv3 = maxDiv3 > dp[i - 1] ? maxDiv3 : 0x3f3f3f3f; + maxDiv5 = maxDiv5 > dp[i - 1] ? maxDiv5 : 0x3f3f3f3f; + dp[i] = std::min({maxDiv2, maxDiv3, maxDiv5}); } - return begin; - }; - for (int32_t i{1}; i < n; i++) { - const double last = dp[i - 1]; - const auto div2{static_cast(last / 2)}, div3{ - static_cast(last / 3)}, div5{static_cast(last / 5)}; - int32_t maxDiv2{dp[search(i, div2)] * 2}, maxDiv3{dp[search(i, div3)] * 3}, maxDiv5{dp[search(i, div5)] * 5}; - maxDiv2 = maxDiv2 > dp[i - 1] ? maxDiv2 : 0x3f3f3f3f; - maxDiv3 = maxDiv3 > dp[i - 1] ? maxDiv3 : 0x3f3f3f3f; - maxDiv5 = maxDiv5 > dp[i - 1] ? maxDiv5 : 0x3f3f3f3f; - dp[i] = std::min({maxDiv2, maxDiv3, maxDiv5}); + // 不想用O(n)的方式,log_2^(2000)也不过20左右 + return dp[n - 1]; } - // 不想用O(n)的方式,log_2^(2000)也不过20左右 - return dp[n - 1]; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_264_test.cpp b/algorithm/dp/leetcode_264_test.cpp new file mode 100644 index 00000000..960bb66a --- /dev/null +++ b/algorithm/dp/leetcode_264_test.cpp @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day11 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_264_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_264_TEST_CPP + +#include + +#include "leetcode_264.cpp" + +namespace leetcode_264 { +using std::vector; + +TEST_CASE("1 [test_264]", "[test_264]") { + static constexpr const auto input{10}; + static constexpr const auto result{12}; + Solution solution; + CHECK(result == solution.nthUglyNumber(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_264_TEST_CPP diff --git a/algorithm/dp/leetcode_264_test.hpp b/algorithm/dp/leetcode_264_test.hpp deleted file mode 100644 index 12fb4d93..00000000 --- a/algorithm/dp/leetcode_264_test.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day11 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_264_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_264_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_264 { -using std::vector; - -struct leetcode_264 final { - static int32_t nthUglyNumber(int32_t n); -}; - - -TEST_CASE("1 [test_264]", "[test_264]") { - static constexpr const auto input{10}; - static constexpr const auto result{12}; - CHECK(result == leetcode_264::nthUglyNumber(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_264_TEST_CPP diff --git a/algorithm/dp/leetcode_279.cpp b/algorithm/dp/leetcode_279.cpp index 9042da33..4cca51c4 100644 --- a/algorithm/dp/leetcode_279.cpp +++ b/algorithm/dp/leetcode_279.cpp @@ -1,39 +1,44 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2022-2023 nanos +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_279_test.hpp" #include namespace leetcode_279 { +using std::vector; +#endif -vector getSquList(int32_t x) { - vector will_return{}; - for (int32_t i{1}; i * i <= x; i++) { - will_return.push_back(i * i); +class Solution { +private: + vector getSquList(int32_t x) { + vector will_return{}; + for (int32_t i{1}; i * i <= x; i++) { + will_return.push_back(i * i); + } + return will_return; } - return will_return; -} -static constexpr const auto maxNum{10000}; + static constexpr const auto maxNum{10000}; -int32_t leetcode_279::numSquares(int32_t n) { - const auto squList{getSquList(maxNum)}; - const auto squ_list_size{squList.size()}; - vector dp(n + 1); - std::iota(std::begin(dp), std::end(dp), 0); // 只有1组成 - for (size_t j{0}; j < squ_list_size && squList[j] <= n; j++) { - dp[squList[j]] = 1; // 本身就是平方数 - } - for (int32_t i{1}; i <= n; i++) { - for (size_t j{0}; j < squ_list_size && squList[j] <= i; j++) { - dp[i] = std::min(dp[i], dp[i - squList[j]] + 1); // 寻找子问题 +public: + int32_t numSquares(int32_t n) { + const auto squList{getSquList(maxNum)}; + const auto squ_list_size{squList.size()}; + vector dp(n + 1); + std::iota(std::begin(dp), std::end(dp), 0); // 只有1组成 + for (size_t j{0}; j < squ_list_size && squList[j] <= n; j++) { + dp[squList[j]] = 1; // 本身就是平方数 } + for (int32_t i{1}; i <= n; i++) { + for (size_t j{0}; j < squ_list_size && squList[j] <= i; j++) { + dp[i] = std::min(dp[i], dp[i - squList[j]] + 1); // 寻找子问题 + } + } + return dp.back(); } - return dp.back(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_279_test.cpp b/algorithm/dp/leetcode_279_test.cpp new file mode 100644 index 00000000..850eb885 --- /dev/null +++ b/algorithm/dp/leetcode_279_test.cpp @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day21 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_279_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_279_TEST_CPP + +#include +#include "leetcode_279.cpp" + +namespace leetcode_279 { +using std::vector; + +TEST_CASE("1 [test_279]", "[test_279]") { + static constexpr const auto input{12}; + static constexpr const auto result{3}; + Solution solution; + CHECK(result == solution.numSquares(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_279_TEST_CPP diff --git a/algorithm/dp/leetcode_279_test.hpp b/algorithm/dp/leetcode_279_test.hpp deleted file mode 100644 index 3c027b35..00000000 --- a/algorithm/dp/leetcode_279_test.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day21 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_279_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_279_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_279 { -using std::vector; - -struct leetcode_279 final { - static int32_t numSquares(int32_t n); -}; - - -TEST_CASE("1 [test_279]", "[test_279]") { - static constexpr const auto input{12}; - static constexpr const auto result{3}; - CHECK(result == leetcode_279::numSquares(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_279_TEST_CPP diff --git a/algorithm/dp/leetcode_300.cpp b/algorithm/dp/leetcode_300.cpp index 5a733f9e..c757c479 100644 --- a/algorithm/dp/leetcode_300.cpp +++ b/algorithm/dp/leetcode_300.cpp @@ -1,32 +1,34 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_300_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_300 { +using std::vector; +#endif -int32_t leetcode_300::lengthOfLIS(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size <= 1) { - return static_cast(nums_size); - } - vector dp(nums_size, 1); - // 难点在DP定义上, 如何定义子问题,让问题能够连接起来 - // [j] 以j为结尾的最长严格递增子序列 - int32_t will_return{1}; - for (size_t i{1}; i < nums_size; i++) { - for (size_t j{0}; j < i; j++) { - if (nums[i] > nums[j]) { - dp[i] = std::max(dp[i], dp[j] + 1); +class Solution { +public: + int32_t lengthOfLIS(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size <= 1) { + return static_cast(nums_size); + } + vector dp(nums_size, 1); + // 难点在DP定义上, 如何定义子问题,让问题能够连接起来 + // [j] 以j为结尾的最长严格递增子序列 + int32_t will_return{1}; + for (size_t i{1}; i < nums_size; i++) { + for (size_t j{0}; j < i; j++) { + if (nums[i] > nums[j]) { + dp[i] = std::max(dp[i], dp[j] + 1); + } + will_return = std::max(will_return, dp[i]); } - will_return = std::max(will_return, dp[i]); } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_300_test.hpp b/algorithm/dp/leetcode_300_test.cpp similarity index 56% rename from algorithm/dp/leetcode_300_test.hpp rename to algorithm/dp/leetcode_300_test.cpp index e341a264..6d48438f 100644 --- a/algorithm/dp/leetcode_300_test.hpp +++ b/algorithm/dp/leetcode_300_test.cpp @@ -1,54 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Tag stack //@Tag 单调栈 //@Linked 121 122 //@Plan 动态规划入门 Day18 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_300_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_300_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_300_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_300_TEST_CPP #include -#include -#include -#include +#include "leetcode_300.cpp" namespace leetcode_300 { using std::vector; -struct leetcode_300 final { - static int32_t lengthOfLIS(const vector &nums); -}; - - TEST_CASE("0 [test_300]", "[test_300]") { const vector input{10, 9, 2, 5, 3, 7, 101, 18}; static constexpr const auto result{4}; - CHECK(result == leetcode_300::lengthOfLIS(input)); + Solution solution; + CHECK(result == solution.lengthOfLIS(input)); } TEST_CASE("1 [test_300]", "[test_300]") { const vector input{4, 10, 4, 3, 8, 9}; static constexpr const auto result{3}; - CHECK(result == leetcode_300::lengthOfLIS(input)); + Solution solution; + CHECK(result == solution.lengthOfLIS(input)); } TEST_CASE("2 [test_300]", "[test_300]") { const vector input{0, 1, 0, 3, 2, 3}; static constexpr const auto result{4}; - CHECK(result == leetcode_300::lengthOfLIS(input)); + Solution solution; + CHECK(result == solution.lengthOfLIS(input)); } TEST_CASE("3 [test_300]", "[test_300]") { const vector input{7, 7, 7, 7, 7, 7, 7}; static constexpr const auto result{1}; - CHECK(result == leetcode_300::lengthOfLIS(input)); + Solution solution; + CHECK(result == solution.lengthOfLIS(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_300_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_300_TEST_CPP diff --git a/algorithm/dp/leetcode_304.cpp b/algorithm/dp/leetcode_304.cpp new file mode 100644 index 00000000..080c4216 --- /dev/null +++ b/algorithm/dp/leetcode_304.cpp @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + +#ifdef ALGORITHM_TEST_MACRO + +#include +#include +#include + +namespace leetcode_304 { +using std::vector; +#endif + +class NumMatrix { +private: + vector> sumRange; + + vector> init(const vector> &matrix) { + if (matrix.empty() || matrix.front().empty()) { + return {}; + } + const auto row{matrix.size()}, col{matrix.front().size()}; + vector> range(row + 1, vector(col + 1)); + for (size_t i{0}; i < row; i++) { + for (size_t j{0}; j < col; j++) { + range[i + 1][j + 1] = range[i][j + 1] + range[i + 1][j] - range[i][j] + matrix[i][j]; + } + } + return range; + } + +public: + NumMatrix(const vector> &matrix) : sumRange(init(matrix)) { + } + + int sumRegion(int32_t row1, int32_t col1, int32_t row2, int32_t col2) const { + return this->sumRange[row2 + 1][col2 + 1] - this->sumRange[row1][col2 + 1] - + this->sumRange[row2 + 1][col1] + this->sumRange[row1][col1]; + } +}; + +class Solution { +private: + vector> init(const vector> &matrix) { + if (matrix.empty() || matrix.front().empty()) { + return {}; + } + const auto row{matrix.size()}, col{matrix.front().size()}; + vector> range(row + 1, vector(col + 1)); + for (size_t i{0}; i < row; i++) { + for (size_t j{0}; j < col; j++) { + range[i + 1][j + 1] = range[i][j + 1] + range[i + 1][j] - range[i][j] + matrix[i][j]; + } + } + return range; + } + +public: + vector> matrixBlockSum(const vector> &mat, int32_t K) { + if (mat.empty() || mat.front().empty()) { + return {}; + } + const auto k = static_cast(K); + const auto row{mat.size()}, col{mat.front().size()}; + const vector> dp{init(mat)}; + vector> will_return(row, vector(col)); + for (size_t i{0}; i < row; ++i) { + const size_t left{i > k ? i - k : 0}; + const size_t right{std::min(i + k, row - 1)}; + for (size_t j{0}; j < col; ++j) { + const size_t head{j > k ? j - k : 0}; + const size_t loot{std::min(j + k, col - 1)}; + will_return[i][j] = dp[right + 1][loot + 1] - dp[left][loot + 1] - dp[right + 1][head] + + dp[left][head]; + } + } + return will_return; + } +}; + +#ifdef ALGORITHM_TEST_MACRO +} +#endif diff --git a/algorithm/dp/leetcode_304_1314.cpp b/algorithm/dp/leetcode_304_1314.cpp deleted file mode 100644 index 6df714ac..00000000 --- a/algorithm/dp/leetcode_304_1314.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_304_1314_test.hpp" - -namespace leetcode_304 { -vector> init(const vector> &matrix) { - if (matrix.empty() || matrix.front().empty()) { - return {}; - } - const auto row{matrix.size()}, col{matrix.front().size()}; - vector> range(row + 1, vector(col + 1)); - for (size_t i{0}; i < row; i++) { - for (size_t j{0}; j < col; j++) { - range[i + 1][j + 1] = range[i][j + 1] + range[i + 1][j] - range[i][j] + matrix[i][j]; - } - } - return range; -} - -NumMatrix::NumMatrix(const vector> &matrix) : sumRange(init(matrix)) { -} - -int NumMatrix::sumRegion(int32_t row1, int32_t col1, int32_t row2, int32_t col2) const { - return this->sumRange[row2 + 1][col2 + 1] - this->sumRange[row1][col2 + 1] - - this->sumRange[row2 + 1][col1] + this->sumRange[row1][col1]; -} -} - -namespace leetcode_1314 { - -vector> leetcode_1314::matrixBlockSum(const vector> &mat, int32_t K) { - if (mat.empty() || mat.front().empty()) { - return {}; - } - const auto k = static_cast(K); - const auto row{mat.size()}, col{mat.front().size()}; - const vector> dp{leetcode_304::init(mat)}; - vector> will_return(row, vector(col)); - for (size_t i{0}; i < row; ++i) { - const size_t left{i > k ? i - k : 0}; - const size_t right{std::min(i + k, row - 1)}; - for (size_t j{0}; j < col; ++j) { - const size_t head{j > k ? j - k : 0}; - const size_t loot{std::min(j + k, col - 1)}; - will_return[i][j] = dp[right + 1][loot + 1] - dp[left][loot + 1] - dp[right + 1][head] + - dp[left][head]; - } - } - return will_return; -} -} - diff --git a/algorithm/dp/leetcode_304_test.cpp b/algorithm/dp/leetcode_304_test.cpp new file mode 100644 index 00000000..e5c9b5e4 --- /dev/null +++ b/algorithm/dp/leetcode_304_test.cpp @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Description 经典小学数学题,交叉部分算面积 +//@Plan 动态规划入门 Day14 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_304_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_304_TEST_CPP + +#include +#include "leetcode_304.cpp" +#include + +namespace leetcode_304 { +using std::vector; + +using Catch::Matchers::Equals; + +TEST_CASE("1 [test_304]", "[test_304]") { + const vector> input{ + {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}}; + const auto matrix{std::make_unique(input)}; + static constexpr const auto result1{8}, result2{11}, result3{12}; + CHECK(result1 == matrix->sumRegion(2, 1, 4, 3)); + CHECK(result2 == matrix->sumRegion(1, 1, 2, 2)); + CHECK(result3 == matrix->sumRegion(1, 2, 2, 4)); +} + +} + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_304_TEST_CPP diff --git a/algorithm/dp/leetcode_309.cpp b/algorithm/dp/leetcode_309.cpp index c25d0622..a7a59587 100644 --- a/algorithm/dp/leetcode_309.cpp +++ b/algorithm/dp/leetcode_309.cpp @@ -1,45 +1,48 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_309_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_309 { +using std::vector; +#endif -int32_t leetcode_309::maxProfit(const vector &prices) { - const auto p_size{prices.size()}; - if (p_size <= 1) { - return 0; +class Solution { +public: + int32_t maxProfit(const vector &prices) { + const auto p_size{prices.size()}; + if (p_size <= 1) { + return 0; + } + vector dpBuy(p_size + 1, 0), dpSell(p_size + 1, 0); + dpBuy[0] = 0; // 0 day之前无法有任何操作 + dpSell[0] = 0; // 0 day之前无法有任何操作 + dpBuy[1] = -prices[0]; // 1 day 购入 + dpSell[1] = 0; // 无法sell,没东西 + for (size_t i{2}; i <= p_size; i++) { + const auto price{prices[i - 1]}; + dpBuy[i] = std::max(dpBuy[i - 1], dpSell[i - 2] - price); // 只有卖出后有冷冻期,买入时没有 + dpSell[i] = std::max(dpSell[i - 1], dpBuy[i - 1] + price); + } + return dpSell.back(); } - vector dpBuy(p_size + 1, 0), dpSell(p_size + 1, 0); - dpBuy[0] = 0; // 0 day之前无法有任何操作 - dpSell[0] = 0; // 0 day之前无法有任何操作 - dpBuy[1] = -prices[0]; // 1 day 购入 - dpSell[1] = 0; // 无法sell,没东西 - for (size_t i{2}; i <= p_size; i++) { - const auto price{prices[i - 1]}; - dpBuy[i] = std::max(dpBuy[i - 1], dpSell[i - 2] - price); // 只有卖出后有冷冻期,买入时没有 - dpSell[i] = std::max(dpSell[i - 1], dpBuy[i - 1] + price); - } - return dpSell.back(); -} -int32_t leetcode_309::maxProfit2(const vector &prices) { - const auto p_size{prices.size()}; - if (p_size <= 1) { - return 0; + int32_t maxProfit2(const vector &prices) { + const auto p_size{prices.size()}; + if (p_size <= 1) { + return 0; + } + int32_t buy1{-prices[0]}, buy2{0}; + int32_t sell0{0}, sell1{0}, sell2{0}; + for (size_t i{1}; i < p_size; i++, buy1 = buy2, sell1 = sell2) { + const auto price{prices[i]}; + buy2 = std::max(buy1, sell0 - price); // + sell2 = std::max(sell1, buy1 + price); + sell0 = sell1; + } + return sell2; } - int32_t buy1{-prices[0]}, buy2{0}; - int32_t sell0{0}, sell1{0}, sell2{0}; - for (size_t i{1}; i < p_size; i++, buy1 = buy2, sell1 = sell2) { - const auto price{prices[i]}; - buy2 = std::max(buy1, sell0 - price); // - sell2 = std::max(sell1, buy1 + price); - sell0 = sell1; - } - return sell2; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_309_test.cpp b/algorithm/dp/leetcode_309_test.cpp new file mode 100644 index 00000000..703e12c5 --- /dev/null +++ b/algorithm/dp/leetcode_309_test.cpp @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Tag stack +//@Tag 单调栈 +//@Linked 121 122 +//@Plan 动态规划入门 Day8 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_309_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_309_TEST_CPP + +#include +#include "leetcode_309.cpp" + +namespace leetcode_309 { +using std::vector; + +TEST_CASE("0 [test_309]", "[test_309]") { + const vector input{1, 2, 3, 0, 2}; + static constexpr const auto result{3}; + Solution solution; + CHECK(result == solution.maxProfit(input)); + CHECK(result == solution.maxProfit2(input)); +} + +TEST_CASE("1 [test_309]", "[test_309]") { + const vector input{7, 1, 5, 3, 6, 4}; + static constexpr const auto result{5}; + Solution solution; + CHECK(result == solution.maxProfit(input)); + CHECK(result == solution.maxProfit2(input)); +} + +TEST_CASE("2 [test_309]", "[test_309]") { + const vector input{7, 6, 4, 3, 1}; + static constexpr const auto result{0}; + Solution solution; + CHECK(result == solution.maxProfit(input)); + CHECK(result == solution.maxProfit2(input)); +} + +TEST_CASE("3 [test_309]", "[test_309]") { + const vector input{1, 2, 3, 4, 5}; + static constexpr const auto result{4}; + Solution solution; + CHECK(result == solution.maxProfit(input)); + CHECK(result == solution.maxProfit2(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_309_TEST_CPP diff --git a/algorithm/dp/leetcode_309_test.hpp b/algorithm/dp/leetcode_309_test.hpp deleted file mode 100644 index d51de362..00000000 --- a/algorithm/dp/leetcode_309_test.hpp +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Tag stack -//@Tag 单调栈 -//@Linked 121 122 -//@Plan 动态规划入门 Day8 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_309_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_309_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_309 { -using std::vector; - -struct leetcode_309 final { - static int32_t maxProfit(const vector &prices); - - static int32_t maxProfit2(const vector &prices); -}; - - -TEST_CASE("0 [test_309]", "[test_309]") { - const vector input{1, 2, 3, 0, 2}; - static constexpr const auto result{3}; - CHECK(result == leetcode_309::maxProfit(input)); - CHECK(result == leetcode_309::maxProfit2(input)); -} - -TEST_CASE("1 [test_309]", "[test_309]") { - const vector input{7, 1, 5, 3, 6, 4}; - static constexpr const auto result{5}; - CHECK(result == leetcode_309::maxProfit(input)); - CHECK(result == leetcode_309::maxProfit2(input)); -} - -TEST_CASE("2 [test_309]", "[test_309]") { - const vector input{7, 6, 4, 3, 1}; - static constexpr const auto result{0}; - CHECK(result == leetcode_309::maxProfit(input)); - CHECK(result == leetcode_309::maxProfit2(input)); -} - -TEST_CASE("3 [test_309]", "[test_309]") { - const vector input{1, 2, 3, 4, 5}; - static constexpr const auto result{4}; - CHECK(result == leetcode_309::maxProfit(input)); - CHECK(result == leetcode_309::maxProfit2(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_309_TEST_CPP diff --git a/algorithm/dp/leetcode_322.cpp b/algorithm/dp/leetcode_322.cpp index b3f36ebe..3e540b74 100644 --- a/algorithm/dp/leetcode_322.cpp +++ b/algorithm/dp/leetcode_322.cpp @@ -1,48 +1,50 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_322_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_322 { +using std::vector; +#endif -int32_t leetcode_322::coinChange(const vector &coins, int32_t amount) { - vector input{}; - for (const auto coinNum: coins) { - if (coinNum <= amount) { - input.push_back(coinNum); +class Solution { +public: + int32_t coinChange(const vector &coins, int32_t amount) { + vector input{}; + for (const auto coinNum: coins) { + if (coinNum <= amount) { + input.push_back(coinNum); + } } - } - std::sort(input.begin(), input.end()); - // dp[i][j]代表 使用前i种硬币,组合出j面值需要的最小数量 - vector> dp(input.size() + 1, vector(amount + 1, 0x3f3f3f3f)); - dp[0][0] = 0; - for (int32_t i{1}; i <= amount; i++) { - dp[0][i] = 0x3f3f3f3f; // 无论怎样, 前0种无法搭配出任何面值 - } - for (size_t i{1}; i <= input.size(); i++) { - dp[i][0] = 0; // 无论怎样,0面值可以被0个组合出来 - } - for (size_t i{1}; i <= input.size(); i++) { - const auto coin{input[i - 1]}; - for (int32_t j{1}; j <= amount; j++) { - dp[i][j] = std::min(dp[i][j], dp[i - 1][j]); - if (j >= coin) { - // 此处因为是完全背包,所以可以用循环取值的方法求,O(n) - // 优化一下 就变成了dp[i][j-coin], 由本行上一个组成 - // 简化重复计算,因为计算[i][j]的[i-1][j-coin],[i-1][j-2coin]的话, - // 实际上[i][j-coin]已经计算了 [i-1][j-2coin],[i-1][j-3coin]...等等,所以只需要对比一次就ok - dp[i][j] = std::min(dp[i][j], dp[i][j - coin] + 1); + std::sort(input.begin(), input.end()); + // dp[i][j]代表 使用前i种硬币,组合出j面值需要的最小数量 + vector> dp(input.size() + 1, vector(amount + 1, 0x3f3f3f3f)); + dp[0][0] = 0; + for (int32_t i{1}; i <= amount; i++) { + dp[0][i] = 0x3f3f3f3f; // 无论怎样, 前0种无法搭配出任何面值 + } + for (size_t i{1}; i <= input.size(); i++) { + dp[i][0] = 0; // 无论怎样,0面值可以被0个组合出来 + } + for (size_t i{1}; i <= input.size(); i++) { + const auto coin{input[i - 1]}; + for (int32_t j{1}; j <= amount; j++) { + dp[i][j] = std::min(dp[i][j], dp[i - 1][j]); + if (j >= coin) { + // 此处因为是完全背包,所以可以用循环取值的方法求,O(n) + // 优化一下 就变成了dp[i][j-coin], 由本行上一个组成 + // 简化重复计算,因为计算[i][j]的[i-1][j-coin],[i-1][j-2coin]的话, + // 实际上[i][j-coin]已经计算了 [i-1][j-2coin],[i-1][j-3coin]...等等,所以只需要对比一次就ok + dp[i][j] = std::min(dp[i][j], dp[i][j - coin] + 1); + } + //for (int32_t k{j}, count{0}; k >= 0; k -= coin, count++) { + // dp[i][j] = std::min(dp[i][j], dp[i - 1][k] + count); + //} } - //for (int32_t k{j}, count{0}; k >= 0; k -= coin, count++) { - // dp[i][j] = std::min(dp[i][j], dp[i - 1][k] + count); - //} } + return dp.back().back() >= 0x3f3f3f3f ? -1 : dp.back().back(); } - return dp.back().back() >= 0x3f3f3f3f ? -1 : dp.back().back(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_322_test.hpp b/algorithm/dp/leetcode_322_test.cpp similarity index 61% rename from algorithm/dp/leetcode_322_test.hpp rename to algorithm/dp/leetcode_322_test.cpp index 99feee13..c5154c12 100644 --- a/algorithm/dp/leetcode_322_test.hpp +++ b/algorithm/dp/leetcode_322_test.cpp @@ -1,69 +1,64 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day20 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_322_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_322_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_322_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_322_TEST_CPP #include -#include -#include -#include +#include "leetcode_322.cpp" namespace leetcode_322 { using std::vector; -struct leetcode_322 final { - static int32_t coinChange(const vector &coins, int32_t amount); -}; - TEST_CASE("1 [test_322]", "[test_322]") { const vector input{1, 2, 5}; static constexpr const auto amount{11}; static constexpr const auto result{3}; - CHECK(result == leetcode_322::coinChange(input, amount)); + Solution solution; + CHECK(result == solution.coinChange(input, amount)); } TEST_CASE("2 [test_322]", "[test_322]") { const vector input{2}; static constexpr const auto amount{3}; static constexpr const auto result{-1}; - CHECK(result == leetcode_322::coinChange(input, amount)); + Solution solution; + CHECK(result == solution.coinChange(input, amount)); } TEST_CASE("3 [test_322]", "[test_322]") { const vector input{1}; static constexpr const auto amount{0}; static constexpr const auto result{0}; - CHECK(result == leetcode_322::coinChange(input, amount)); + Solution solution; + CHECK(result == solution.coinChange(input, amount)); } TEST_CASE("4 [test_322]", "[test_322]") { const vector input{1}; static constexpr const auto amount{1}; static constexpr const auto result{1}; - CHECK(result == leetcode_322::coinChange(input, amount)); + Solution solution; + CHECK(result == solution.coinChange(input, amount)); } TEST_CASE("5 [test_322]", "[test_322]") { const vector input{1}; static constexpr const auto amount{2}; static constexpr const auto result{2}; - CHECK(result == leetcode_322::coinChange(input, amount)); + Solution solution; + CHECK(result == solution.coinChange(input, amount)); } TEST_CASE("6 [test_322]", "[test_322]") { const vector input{112, 149, 215, 496, 482, 436, 144, 397, 500, 189}; static constexpr const auto amount{8480}; static constexpr const auto result{17}; - CHECK(result == leetcode_322::coinChange(input, amount)); + Solution solution; + CHECK(result == solution.coinChange(input, amount)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_322_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_322_TEST_CPP diff --git a/algorithm/dp/leetcode_376.cpp b/algorithm/dp/leetcode_376.cpp index 2515c93f..3f1fcd41 100644 --- a/algorithm/dp/leetcode_376.cpp +++ b/algorithm/dp/leetcode_376.cpp @@ -1,34 +1,39 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_376_test.hpp" +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_376 { +using std::vector; +#endif -int32_t leetcode_376::wiggleMaxLength(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size <= 1) { - return static_cast(nums_size); - } - vector dpInc(nums_size, 1), dpDec(nums_size, 1); - for (size_t i{1}; i < nums_size; i++) { - for (size_t j{0}; j < i; j++) { - if (nums[i] > nums[j]) { - dpInc[i] = std::max(dpInc[i], dpDec[j] + 1); - } else if (nums[i] < nums[j]) { - dpDec[i] = std::max(dpDec[i], dpInc[j] + 1); +class Solution { +public: + int32_t wiggleMaxLength(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size <= 1) { + return static_cast(nums_size); + } + vector dpInc(nums_size, 1), dpDec(nums_size, 1); + for (size_t i{1}; i < nums_size; i++) { + for (size_t j{0}; j < i; j++) { + if (nums[i] > nums[j]) { + dpInc[i] = std::max(dpInc[i], dpDec[j] + 1); + } else if (nums[i] < nums[j]) { + dpDec[i] = std::max(dpDec[i], dpInc[j] + 1); + } } } + return std::max( + *std::max_element(std::cbegin(dpInc), std::cend(dpInc)), + *std::max_element(std::cbegin(dpDec), std::cend(dpDec)) + ); } - return std::max( - *std::max_element(std::cbegin(dpInc), std::cend(dpInc)), - *std::max_element(std::cbegin(dpDec), std::cend(dpDec)) - ); -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_376_test.hpp b/algorithm/dp/leetcode_376_test.cpp similarity index 52% rename from algorithm/dp/leetcode_376_test.hpp rename to algorithm/dp/leetcode_376_test.cpp index 1295c339..1efaaa27 100644 --- a/algorithm/dp/leetcode_376_test.hpp +++ b/algorithm/dp/leetcode_376_test.cpp @@ -1,45 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day18 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_376_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_376_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_376_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_376_TEST_CPP #include -#include -#include -#include +#include "leetcode_376.cpp" namespace leetcode_376 { using std::vector; -struct leetcode_376 final { - static int32_t wiggleMaxLength(const vector &nums); -}; - TEST_CASE("1 [test_376]", "[test_376]") { const vector input{1, 7, 4, 9, 2, 5}; static constexpr const auto result{6}; - CHECK(result == leetcode_376::wiggleMaxLength(input)); + Solution solution; + CHECK(result == solution.wiggleMaxLength(input)); } TEST_CASE("2 [test_376]", "[test_376]") { const vector input{1, 17, 5, 10, 13, 15, 10, 5, 16, 8}; static constexpr const auto result{7}; - CHECK(result == leetcode_376::wiggleMaxLength(input)); + Solution solution; + CHECK(result == solution.wiggleMaxLength(input)); } TEST_CASE("3 [test_376]", "[test_376]") { const vector input{1, 2, 3, 4, 5, 6, 7, 8, 9}; static constexpr const auto result{2}; - CHECK(result == leetcode_376::wiggleMaxLength(input)); + Solution solution; + CHECK(result == solution.wiggleMaxLength(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_376_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_376_TEST_CPP diff --git a/algorithm/dp/leetcode_377.cpp b/algorithm/dp/leetcode_377.cpp index 3e68e70d..f3e9bc13 100644 --- a/algorithm/dp/leetcode_377.cpp +++ b/algorithm/dp/leetcode_377.cpp @@ -1,31 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanos - -*/ -#include "leetcode_377_test.hpp" +#include #include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_377 { +using std::vector; +#endif -int32_t leetcode_377::combinationSum4(const vector &nums, int32_t target) { - const auto nums_size{nums.size()}; - vector numArray{nums}; - std::sort(std::begin(numArray), std::end(numArray)); - // dp[i] 金额为i情况下的组合个数 - vector dp(target + 1, 0); - dp[0] = 1;// {}, 零只有空能够拼凑出 - // 子问题构造: 去掉最后一个的值,则将其规约成子问题 - for (int32_t i{1}; i <= target; i++) { - // 确定某个金额的组成 - for (size_t j{0}; j < nums_size && numArray[j] <= i; j++) { - const auto num{numArray[j]}; // 本次将使用的数字 - dp[i] += dp[i - num]; +class Solution { +public: + int32_t combinationSum4(const vector &nums, int32_t target) { + const auto nums_size{nums.size()}; + vector numArray{nums}; + std::sort(std::begin(numArray), std::end(numArray)); + // dp[i] 金额为i情况下的组合个数 + vector dp(target + 1, 0); + dp[0] = 1;// {}, 零只有空能够拼凑出 + // 子问题构造: 去掉最后一个的值,则将其规约成子问题 + for (int32_t i{1}; i <= target; i++) { + // 确定某个金额的组成 + for (size_t j{0}; j < nums_size && numArray[j] <= i; j++) { + const auto num{numArray[j]}; // 本次将使用的数字 + dp[i] += dp[i - num]; + } } + return dp.back(); } - return dp.back(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_377_test.hpp b/algorithm/dp/leetcode_377_test.cpp similarity index 68% rename from algorithm/dp/leetcode_377_test.hpp rename to algorithm/dp/leetcode_377_test.cpp index d28e93b3..7c10196c 100644 --- a/algorithm/dp/leetcode_377_test.hpp +++ b/algorithm/dp/leetcode_377_test.cpp @@ -1,33 +1,23 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day21 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_377_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_377_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_377_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_377_TEST_CPP #include -#include -#include -#include +#include "leetcode_377.cpp" namespace leetcode_377 { using std::vector; -struct leetcode_377 final { - static int32_t combinationSum4(const vector &nums, int32_t target); -}; - TEST_CASE("1 [test_377]", "[test_377]") { const vector nums{1, 2, 3}; static constexpr const auto target{4}; static constexpr const auto result{7}; - CHECK(result == leetcode_377::combinationSum4(nums, target)); + Solution solution; + CHECK(result == solution.combinationSum4(nums, target)); } TEST_CASE("2 [test_377]", "[test_377]") { @@ -39,7 +29,8 @@ TEST_CASE("2 [test_377]", "[test_377]") { 920, 930, 940, 950, 960, 970, 980, 990, 111}; static constexpr const auto target{999};//9个111 static constexpr const auto result{1}; - CHECK(result == leetcode_377::combinationSum4(nums, target)); + Solution solution; + CHECK(result == solution.combinationSum4(nums, target)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_377_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_377_TEST_CPP diff --git a/algorithm/dp/leetcode_392.cpp b/algorithm/dp/leetcode_392.cpp index 3dd82fa3..5d4cf2ca 100644 --- a/algorithm/dp/leetcode_392.cpp +++ b/algorithm/dp/leetcode_392.cpp @@ -1,25 +1,30 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanos - -*/ -#include "leetcode_392_test.hpp" +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_392 { +using std::string; +#endif -bool leetcode_392::isSubsequence(const string &s, const string &t) { - const auto tSize{t.size()}, sSize{s.size()}; - if (tSize < sSize) { - return false; - } - size_t sNum{0}; - for (size_t i{0}; i < tSize && sNum != sSize; i++) { - if (t[i] == s[sNum]) { - sNum++; +class Solution { +public: + bool isSubsequence(const string &s, const string &t) { + const auto tSize{t.size()}, sSize{s.size()}; + if (tSize < sSize) { + return false; + } + size_t sNum{0}; + for (size_t i{0}; i < tSize && sNum != sSize; i++) { + if (t[i] == s[sNum]) { + sNum++; + } } + return sNum == sSize; } - return sNum == sSize; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_392_test.cpp b/algorithm/dp/leetcode_392_test.cpp new file mode 100644 index 00000000..a3598ff6 --- /dev/null +++ b/algorithm/dp/leetcode_392_test.cpp @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day19 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_392_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_392_TEST_CPP + +#include +#include "leetcode_392.cpp" + +namespace leetcode_392 { +using std::vector; + +TEST_CASE("1 [test_392]", "[test_392]") { + static constexpr const char *const s{"abc"}, *const t{"ahbgdc"}; + Solution solution; + CHECK(solution.isSubsequence(s, t)); +} + +TEST_CASE("2 [test_392]", "[test_392]") { + static constexpr const char *const s{"axc"}, *const t{"ahbgdc"}; + Solution solution; + CHECK_FALSE(solution.isSubsequence(s, t)); +} + +TEST_CASE("3 [test_392]", "[test_392]") { + static constexpr const char *const s{"114514"}, *const t{"1919810"}; + Solution solution; + CHECK_FALSE(solution.isSubsequence(s, t)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_392_TEST_CPP diff --git a/algorithm/dp/leetcode_392_test.hpp b/algorithm/dp/leetcode_392_test.hpp deleted file mode 100644 index 1cd53259..00000000 --- a/algorithm/dp/leetcode_392_test.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day19 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_392_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_392_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_392 { -using std::vector; - -struct leetcode_392 final { - static bool isSubsequence(const string &s, const string &t); -}; - -TEST_CASE("1 [test_392]", "[test_392]") { - static constexpr const char *const s{"abc"}, *const t{"ahbgdc"}; - CHECK(leetcode_392::isSubsequence(s, t)); -} - -TEST_CASE("2 [test_392]", "[test_392]") { - static constexpr const char *const s{"axc"}, *const t{"ahbgdc"}; - CHECK_FALSE(leetcode_392::isSubsequence(s, t)); -} - -TEST_CASE("3 [test_392]", "[test_392]") { - static constexpr const char *const s{"114514"}, *const t{"1919810"}; - CHECK_FALSE(leetcode_392::isSubsequence(s, t)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_392_TEST_CPP diff --git a/algorithm/dp/leetcode_413.cpp b/algorithm/dp/leetcode_413.cpp index 4c28504f..5ed62371 100644 --- a/algorithm/dp/leetcode_413.cpp +++ b/algorithm/dp/leetcode_413.cpp @@ -1,35 +1,40 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_413_test.hpp" +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_413 { +using std::vector; +#endif -int32_t leetcode_413::numberOfArithmeticSlices(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums.size() <= 2) { - return 0; - } - static constexpr const auto func = [](int32_t x) { - return (x - 1) * (x - 2) / 2; - };// 完全不必要嗯算, 有连续段落的总长度即可 - int32_t sums{0}, lastDiff{nums[1] - nums[0]}, len{1}; - for (size_t i{2}; i < nums_size; i++) { - const int32_t nowDiff{nums[i] - nums[i - 1]}; - if (nowDiff != lastDiff) { - sums += func(len + 1); - len = 1; - lastDiff = nowDiff; - } else { - len++; +class Solution { +public: + int32_t numberOfArithmeticSlices(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums.size() <= 2) { + return 0; } + static constexpr const auto func = [](int32_t x) { + return (x - 1) * (x - 2) / 2; + };// 完全不必要嗯算, 有连续段落的总长度即可 + int32_t sums{0}, lastDiff{nums[1] - nums[0]}, len{1}; + for (size_t i{2}; i < nums_size; i++) { + const int32_t nowDiff{nums[i] - nums[i - 1]}; + if (nowDiff != lastDiff) { + sums += func(len + 1); + len = 1; + lastDiff = nowDiff; + } else { + len++; + } + } + sums += func(len + 1); + return sums; } - sums += func(len + 1); - return sums; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_413_test.hpp b/algorithm/dp/leetcode_413_test.cpp similarity index 51% rename from algorithm/dp/leetcode_413_test.hpp rename to algorithm/dp/leetcode_413_test.cpp index ffa0933d..17e0dbe1 100644 --- a/algorithm/dp/leetcode_413_test.hpp +++ b/algorithm/dp/leetcode_413_test.cpp @@ -1,52 +1,44 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day10 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_413_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_413_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_413_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_413_TEST_CPP #include -#include -#include -#include +#include "leetcode_413.cpp" namespace leetcode_413 { using std::vector; -struct leetcode_413 final { - static int32_t numberOfArithmeticSlices(const vector &nums); -}; - - TEST_CASE("1 [test_413]", "[test_413]") { const vector input{1, 2, 3, 4}; static constexpr const auto output{3}; - CHECK(output == leetcode_413::numberOfArithmeticSlices(input)); + Solution solution; + CHECK(output == solution.numberOfArithmeticSlices(input)); } TEST_CASE("2 [test_413]", "[test_413]") { const vector input{1}; static constexpr const auto output{0}; - CHECK(output == leetcode_413::numberOfArithmeticSlices(input)); + Solution solution; + CHECK(output == solution.numberOfArithmeticSlices(input)); } TEST_CASE("3 [test_413]", "[test_413]") { const vector input{1, 2, 3, 8, 9, 10}; static constexpr const auto output{2}; - CHECK(output == leetcode_413::numberOfArithmeticSlices(input)); + Solution solution; + CHECK(output == solution.numberOfArithmeticSlices(input)); } TEST_CASE("4 [test_413]", "[test_413]") { const vector input{2, 1, 3, 4, 2, 3}; static constexpr const auto output{0}; - CHECK(output == leetcode_413::numberOfArithmeticSlices(input)); + Solution solution; + CHECK(output == solution.numberOfArithmeticSlices(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_413_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_413_TEST_CPP diff --git a/algorithm/dp/leetcode_416.cpp b/algorithm/dp/leetcode_416.cpp index 3aa6c4ab..ebf7b86d 100644 --- a/algorithm/dp/leetcode_416.cpp +++ b/algorithm/dp/leetcode_416.cpp @@ -1,66 +1,71 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_416_test.hpp" #include namespace leetcode_416 { +using std::vector; +#endif -bool leetcode_416::canPartition(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size <= 1) { - return false; - } - const int32_t sum = std::accumulate(nums.cbegin(), nums.cend(), 0); - if (sum % 2 == 1) { - return false; - } - const auto target = sum / 2; - vector> dp(nums_size + 1, vector(target + 1, false)); - dp[0][0] = true; - for (int32_t i{1}; i <= target; i++) { - dp[0][i] = false; // 无论怎样, 前0种无法装满任何有量的背包 - } - for (size_t i{1}; i <= nums_size; i++) { - dp[i][0] = true; // 无论怎样,0量的背包可以被0个物体组合装满 - } - for (size_t i{1}; i <= nums_size; i++) { - for (int32_t j{1}; j <= target; j++) { - dp[i][j] = dp[i][j] || dp[i - 1][j]; - if (j >= nums[i - 1]) { - dp[i][j] = dp[i][j] || dp[i - 1][j - nums[i - 1]]; +class Solution { +public: + bool canPartition(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size <= 1) { + return false; + } + const int32_t sum = std::accumulate(nums.cbegin(), nums.cend(), 0); + if (sum % 2 == 1) { + return false; + } + const auto target = sum / 2; + vector> dp(nums_size + 1, vector(target + 1, false)); + dp[0][0] = true; + for (int32_t i{1}; i <= target; i++) { + dp[0][i] = false; // 无论怎样, 前0种无法装满任何有量的背包 + } + for (size_t i{1}; i <= nums_size; i++) { + dp[i][0] = true; // 无论怎样,0量的背包可以被0个物体组合装满 + } + for (size_t i{1}; i <= nums_size; i++) { + for (int32_t j{1}; j <= target; j++) { + dp[i][j] = dp[i][j] || dp[i - 1][j]; + if (j >= nums[i - 1]) { + dp[i][j] = dp[i][j] || dp[i - 1][j - nums[i - 1]]; + } } } + return dp.back().back(); } - return dp.back().back(); -} -bool leetcode_416::canPartition2(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size <= 1) { - return false; - } - const int32_t sum = std::accumulate(nums.cbegin(), nums.cend(), 0); - if (sum % 2 == 1) { - return false; - } - const auto target = sum / 2; - vector last(target + 1, false), now(target + 1, false); - last[0] = true; - for (size_t i{1}; i <= nums_size; i++) { - now[0] = true; - for (int32_t j{1}; j <= target; j++) { - now[j] = now[j] || last[j]; - if (j >= nums[i - 1]) { - now[j] = now[j] || last[j - nums[i - 1]]; + bool canPartition2(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size <= 1) { + return false; + } + const int32_t sum = std::accumulate(nums.cbegin(), nums.cend(), 0); + if (sum % 2 == 1) { + return false; + } + const auto target = sum / 2; + vector last(target + 1, false), now(target + 1, false); + last[0] = true; + for (size_t i{1}; i <= nums_size; i++) { + now[0] = true; + for (int32_t j{1}; j <= target; j++) { + now[j] = now[j] || last[j]; + if (j >= nums[i - 1]) { + now[j] = now[j] || last[j - nums[i - 1]]; + } } + std::swap(last, now); } - std::swap(last, now); + return last.back(); } - return last.back(); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_416_test.cpp b/algorithm/dp/leetcode_416_test.cpp new file mode 100644 index 00000000..fbf34f47 --- /dev/null +++ b/algorithm/dp/leetcode_416_test.cpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_416_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_416_TEST_CPP + +#include +#include "leetcode_416.cpp" + +namespace leetcode_416 { +using std::vector; + +TEST_CASE("1 [test_416]", "[test_416]") { + const vector input{1, 5, 11, 5}; + Solution solution; + CHECK(solution.canPartition(input)); + CHECK(solution.canPartition2(input)); +} + +TEST_CASE("2 [test_416]", "[test_416]") { + const vector input{1, 2, 3, 5}; + Solution solution; + CHECK_FALSE(solution.canPartition(input)); + CHECK_FALSE(solution.canPartition2(input)); +} + +TEST_CASE("3 [test_416]", "[test_416]") { + const vector input{114514}; + Solution solution; + CHECK_FALSE(solution.canPartition(input)); + CHECK_FALSE(solution.canPartition2(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_416_TEST_CPP diff --git a/algorithm/dp/leetcode_416_test.hpp b/algorithm/dp/leetcode_416_test.hpp deleted file mode 100644 index 05115773..00000000 --- a/algorithm/dp/leetcode_416_test.hpp +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_416_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_416_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_416 { -using std::vector; - -struct leetcode_416 final { - static bool canPartition(const vector &nums); - - static bool canPartition2(const vector &nums); -}; - - -TEST_CASE("1 [test_416]", "[test_416]") { - const vector input{1, 5, 11, 5}; - CHECK(leetcode_416::canPartition(input)); - CHECK(leetcode_416::canPartition2(input)); -} - -TEST_CASE("2 [test_416]", "[test_416]") { - const vector input{1, 2, 3, 5}; - CHECK_FALSE(leetcode_416::canPartition(input)); - CHECK_FALSE(leetcode_416::canPartition2(input)); -} - -TEST_CASE("3 [test_416]", "[test_416]") { - const vector input{114514}; - CHECK_FALSE(leetcode_416::canPartition(input)); - CHECK_FALSE(leetcode_416::canPartition2(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_416_TEST_CPP diff --git a/algorithm/dp/leetcode_435.cpp b/algorithm/dp/leetcode_435.cpp index 9bd5c83e..1ea2569b 100644 --- a/algorithm/dp/leetcode_435.cpp +++ b/algorithm/dp/leetcode_435.cpp @@ -1,27 +1,30 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_435_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_435 { +using std::vector; +#endif -// 逆向思维来看, 这个问题就相当于排课问题中应该排出多少门课程的结果之反: 应该排除多少门课程 -// 因此, 采用经典贪心解法,一直选取最早结束的课程,即可获取答案. -int32_t leetcode_435::eraseOverlapIntervals(const vector> &intervals) { - vector> times{intervals}; - auto will_return = static_cast(times.size()); - std::sort(std::begin(times), std::end(times), [](const auto& p1, const auto& p2) { return p1[1] < p2[1]; }); - int32_t end{std::numeric_limits::min()}; - for (const auto &p: times) { - if (p[0] >= end) { - end = p[1]; - --will_return; +class Solution { +public: + // 逆向思维来看, 这个问题就相当于排课问题中应该排出多少门课程的结果之反: 应该排除多少门课程 + // 因此, 采用经典贪心解法,一直选取最早结束的课程,即可获取答案. + int32_t eraseOverlapIntervals(const vector> &intervals) { + vector> times{intervals}; + auto will_return = static_cast(times.size()); + std::sort(std::begin(times), std::end(times), [](const auto &p1, const auto &p2) { return p1[1] < p2[1]; }); + int32_t end{std::numeric_limits::min()}; + for (const auto &p: times) { + if (p[0] >= end) { + end = p[1]; + --will_return; + } } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_435_test.hpp b/algorithm/dp/leetcode_435_test.cpp similarity index 55% rename from algorithm/dp/leetcode_435_test.hpp rename to algorithm/dp/leetcode_435_test.cpp index 7d1382e2..8e483f54 100644 --- a/algorithm/dp/leetcode_435_test.hpp +++ b/algorithm/dp/leetcode_435_test.cpp @@ -1,29 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 数据结构基础 Day3 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_435_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_435_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_435_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_435_TEST_CPP #include -#include -#include -#include +#include "leetcode_435.cpp" namespace leetcode_435 { using std::vector; -struct leetcode_435 final { - static int32_t eraseOverlapIntervals(const vector> &intervals); -}; - - TEST_CASE("1 [test_435]", "[test_435]") { const vector> input{ {1, 2}, @@ -32,7 +20,8 @@ TEST_CASE("1 [test_435]", "[test_435]") { {1, 3}, }; static constexpr const auto result{1}; - CHECK(result == leetcode_435::eraseOverlapIntervals(input)); + Solution solution; + CHECK(result == solution.eraseOverlapIntervals(input)); } TEST_CASE("2 [test_435]", "[test_435]") { @@ -42,7 +31,8 @@ TEST_CASE("2 [test_435]", "[test_435]") { {1, 2}, }; static constexpr const auto result{2}; - CHECK(result == leetcode_435::eraseOverlapIntervals(input)); + Solution solution; + CHECK(result == solution.eraseOverlapIntervals(input)); } TEST_CASE("3 [test_435]", "[test_435]") { @@ -51,7 +41,8 @@ TEST_CASE("3 [test_435]", "[test_435]") { {2, 3}, }; static constexpr const auto result{0}; - CHECK(result == leetcode_435::eraseOverlapIntervals(input)); + Solution solution; + CHECK(result == solution.eraseOverlapIntervals(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_435_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_435_TEST_CPP diff --git a/algorithm/dp/leetcode_44.cpp b/algorithm/dp/leetcode_44.cpp index e02078f4..5d2541a1 100644 --- a/algorithm/dp/leetcode_44.cpp +++ b/algorithm/dp/leetcode_44.cpp @@ -1,41 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_44_test.hpp" #include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_44 { using std::vector; +using std::string; +#endif -bool leetcode_44::isMatch(const string &s, const string &p) { - const auto s_size{s.size()}, p_size{p.size()}; - vector> DP(s_size + 1, vector(p_size + 1, false)); - DP[0][0] = true; - for (size_t i{1}; i <= p_size; i++) { - DP[0][i] = (p[i - 1] == '*') && DP[0][i - 1]; - } - for (size_t i{1}; i <= s_size; i++) { - for (size_t j{1}; j <= p_size; j++) { - switch (p[j - 1]) { - case '?': { - DP[i][j] = DP[i - 1][j - 1]; - break; - } - case '*': { - DP[i][j] = DP[i][j - 1] || DP[i - 1][j]; - break; - } - default: { - DP[i][j] = DP[i - 1][j - 1] && (s[i - 1] == p[j - 1]); - break; +class Solution { +public: + bool isMatch(const string &s, const string &p) { + const auto s_size{s.size()}, p_size{p.size()}; + vector> DP(s_size + 1, vector(p_size + 1, false)); + DP[0][0] = true; + for (size_t i{1}; i <= p_size; i++) { + DP[0][i] = (p[i - 1] == '*') && DP[0][i - 1]; + } + for (size_t i{1}; i <= s_size; i++) { + for (size_t j{1}; j <= p_size; j++) { + switch (p[j - 1]) { + case '?': { + DP[i][j] = DP[i - 1][j - 1]; + break; + } + case '*': { + DP[i][j] = DP[i][j - 1] || DP[i - 1][j]; + break; + } + default: { + DP[i][j] = DP[i - 1][j - 1] && (s[i - 1] == p[j - 1]); + break; + } } } } + return DP.back().back(); } - return DP.back().back(); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_44_test.cpp b/algorithm/dp/leetcode_44_test.cpp new file mode 100644 index 00000000..a369ee56 --- /dev/null +++ b/algorithm/dp/leetcode_44_test.cpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_44_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_44_TEST_CPP + +#include +#include "leetcode_44.cpp" + +namespace leetcode_44 { +using std::string; + + +TEST_CASE("double empty [test_44]", "[test_44]") { + Solution solution; + CHECK(solution.isMatch("", "*")); +} + +TEST_CASE("test 1 [test_44]", "[test_44]") { + Solution solution; + CHECK_FALSE(solution.isMatch("aa", "a")); +} + + +TEST_CASE("test 2 [test_44]", "[test_44]") { + Solution solution; + CHECK(solution.isMatch("aa", "*")); +} + +TEST_CASE("? [test_44]", "[test_44]") { + Solution solution; + CHECK_FALSE(solution.isMatch("cb", "*a")); +} + + +TEST_CASE("* can match '' or any string [test_44]", "[test_44]") { + Solution solution; + CHECK(solution.isMatch("adceb", "a*b")); +} + +TEST_CASE("both * and ? [test_44]", "[test_44]") { + Solution solution; + CHECK_FALSE(solution.isMatch("acdcb", "a*c?b")); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_44_TEST_CPP diff --git a/algorithm/dp/leetcode_44_test.hpp b/algorithm/dp/leetcode_44_test.hpp deleted file mode 100644 index 68431d6e..00000000 --- a/algorithm/dp/leetcode_44_test.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_44_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_44_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_44 { -using std::string; - -struct leetcode_44 { - static bool isMatch(const string &s, const string &p); -}; - - -TEST_CASE("double empty [test_44]", "[test_44]") { - CHECK(leetcode_44::isMatch("", "*")); -} - -TEST_CASE("test 1 [test_44]", "[test_44]") { - CHECK_FALSE(leetcode_44::isMatch("aa", "a")); -} - - -TEST_CASE("test 2 [test_44]", "[test_44]") { - CHECK(leetcode_44::isMatch("aa", "*")); -} - -TEST_CASE("? [test_44]", "[test_44]") { - CHECK_FALSE(leetcode_44::isMatch("cb", "*a")); -} - - -TEST_CASE("* can match '' or any string [test_44]", "[test_44]") { - CHECK(leetcode_44::isMatch("adceb", "a*b")); -} - -TEST_CASE("both * and ? [test_44]", "[test_44]") { - CHECK_FALSE(leetcode_44::isMatch("acdcb", "a*c?b")); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_44_TEST_CPP diff --git a/algorithm/dp/leetcode_45.cpp b/algorithm/dp/leetcode_45.cpp index 1506022f..5a18311a 100644 --- a/algorithm/dp/leetcode_45.cpp +++ b/algorithm/dp/leetcode_45.cpp @@ -1,49 +1,57 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_45_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_45 { +using std::vector; +using std::max; +using std::min; +#endif -int32_t leetcode_45::jump(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size == 1) { - return 0; - } - int32_t times{0}; - // 每次移动一个"范围" - // 范围内从左到右依次更新右边界 - // 一旦右边界移动出界,则返回 - for (size_t start{0}, end{1}; end < nums_size; times++) { - size_t max{end + 1}; - for (size_t begin{start}; begin < end; begin++) { - max = std::max(max, begin + nums[begin] + 1); +class Solution { +public: + int32_t jump(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size == 1) { + return 0; + } + int32_t times{0}; + // 每次移动一个"范围" + // 范围内从左到右依次更新右边界 + // 一旦右边界移动出界,则返回 + for (size_t start{0}, end{1}; end < nums_size; times++) { + size_t max{end + 1}; + for (size_t begin{start}; begin < end; begin++) { + max = std::max(max, begin + nums[begin] + 1); + } + start = end; + end = max; } - start = end; - end = max; + return times; } - return times; -} -int32_t leetcode_45::jump2(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size == 1) { - return 0; - } - vector steps(nums_size, 0x3f3f3f3f); - steps[0] = 0; - for (size_t i{0}; i < nums_size; i++) { - for (int32_t step{1}; step <= nums[i] && (i + step) < nums_size; step++) { - steps[i + step] = std::min(steps[i + step], steps[i] + 1); - if (i + step + 1 == nums_size) { - return steps.back(); + int32_t jump2(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size == 1) { + return 0; + } + vector steps(nums_size, 0x3f3f3f3f); + steps[0] = 0; + for (size_t i{0}; i < nums_size; i++) { + for (int32_t step{1}; step <= nums[i] && (i + step) < nums_size; step++) { + steps[i + step] = std::min(steps[i + step], steps[i] + 1); + if (i + step + 1 == nums_size) { + return steps.back(); + } } } + return steps.back(); } - return steps.back(); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_45_test.cpp b/algorithm/dp/leetcode_45_test.cpp new file mode 100644 index 00000000..05eb2e47 --- /dev/null +++ b/algorithm/dp/leetcode_45_test.cpp @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day4 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_45_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_45_TEST_CPP + +#include +#include "leetcode_45.cpp" + +namespace leetcode_45 { +using std::vector; + +TEST_CASE("1 [test_45]", "[test_45]") { + const vector inputs{2, 3, 1, 1, 4}; + static constexpr const auto result{2}; + Solution solution; + CHECK(result == solution.jump(inputs)); + CHECK(result == solution.jump2(inputs)); +} + +TEST_CASE("2 [test_45]", "[test_45]") { + const vector inputs{2, 3, 0, 1, 4}; + static constexpr const auto result{2}; + Solution solution; + CHECK(result == solution.jump(inputs)); + CHECK(result == solution.jump2(inputs)); +} + +TEST_CASE("4 [test_45]", "[test_45]") { + const vector inputs{3, 2, 1}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.jump(inputs)); + CHECK(result == solution.jump2(inputs)); +} + +TEST_CASE("3 [test_45]", "[test_45]") { + const vector inputs{1, 2, 3}; + static constexpr const auto result{2}; + Solution solution; + CHECK(result == solution.jump(inputs)); + CHECK(result == solution.jump2(inputs)); +} + +TEST_CASE("5 [test_45]", "[test_45]") { + const vector inputs{2, 1, 1, 1, 1}; + static constexpr const auto result{3}; + Solution solution; + CHECK(result == solution.jump(inputs)); + CHECK(result == solution.jump2(inputs)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_45_TEST_CPP diff --git a/algorithm/dp/leetcode_45_test.hpp b/algorithm/dp/leetcode_45_test.hpp deleted file mode 100644 index 0882034e..00000000 --- a/algorithm/dp/leetcode_45_test.hpp +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day4 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_45_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_45_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_45 { -using std::vector; - -struct leetcode_45 { - static int32_t jump(const vector &nums); - - static int32_t jump2(const vector &nums); -}; - -TEST_CASE("1 [test_45]", "[test_45]") { - const vector inputs{2, 3, 1, 1, 4}; - static constexpr const auto result{2}; - CHECK(result == leetcode_45::jump(inputs)); - CHECK(result == leetcode_45::jump2(inputs)); -} - -TEST_CASE("2 [test_45]", "[test_45]") { - const vector inputs{2, 3, 0, 1, 4}; - static constexpr const auto result{2}; - CHECK(result == leetcode_45::jump(inputs)); - CHECK(result == leetcode_45::jump2(inputs)); -} - -TEST_CASE("4 [test_45]", "[test_45]") { - const vector inputs{3, 2, 1}; - static constexpr const auto result{1}; - CHECK(result == leetcode_45::jump(inputs)); - CHECK(result == leetcode_45::jump2(inputs)); -} - -TEST_CASE("3 [test_45]", "[test_45]") { - const vector inputs{1, 2, 3}; - static constexpr const auto result{2}; - CHECK(result == leetcode_45::jump(inputs)); - CHECK(result == leetcode_45::jump2(inputs)); -} - -TEST_CASE("5 [test_45]", "[test_45]") { - const vector inputs{2, 1, 1, 1, 1}; - static constexpr const auto result{3}; - CHECK(result == leetcode_45::jump(inputs)); - CHECK(result == leetcode_45::jump2(inputs)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_45_TEST_CPP diff --git a/algorithm/dp/leetcode_5.cpp b/algorithm/dp/leetcode_5.cpp index 72ba4651..712a8e29 100644 --- a/algorithm/dp/leetcode_5.cpp +++ b/algorithm/dp/leetcode_5.cpp @@ -1,50 +1,55 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_5_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_5 { -namespace lcs_5 { +using std::vector; +using std::string; +using std::pair; +#endif -string leetcode_5::longestPalindrome(const string &s) { - const size_t s_size = s.size(); - if (s_size <= 1) { - return s; - } else if (s_size == 2) { - if (s[0] == s[1]) { +class Solution { +public: + string longestPalindrome(const string &s) { + const size_t s_size = s.size(); + if (s_size <= 1) { return s; - } else { - return s.substr(0, 1); + } else if (s_size == 2) { + if (s[0] == s[1]) { + return s; + } else { + return s.substr(0, 1); + } } - } - vector> dp(s_size, vector(s_size, false)); - std::pair begin_end{0, 1}; - size_t max_size = 1; - for (size_t i{0}; i < s_size; i++) { - dp[i][i] = true; - } - for (size_t i{0}; i < s_size - 1; i++) { - dp[i][i + 1] = (s[i] == s[i + 1]); - if (dp[i][i + 1]) { - max_size = 2; - begin_end = {i, max_size}; + vector> dp(s_size, vector(s_size, false)); + pair begin_end{0, 1}; + size_t max_size = 1; + for (size_t i{0}; i < s_size; i++) { + dp[i][i] = true; } - } - for (size_t i{s_size}; i > 0; i--) { - for (size_t j{i + 1}; j < s_size; j++) { - dp[i - 1][j] = ((s[i - 1] == s[j]) && dp[i][j - 1]); - if (j - i + 2 > max_size && dp[i - 1][j]) { - max_size = j - i + 2; - begin_end = {i - 1, max_size}; + for (size_t i{0}; i < s_size - 1; i++) { + dp[i][i + 1] = (s[i] == s[i + 1]); + if (dp[i][i + 1]) { + max_size = 2; + begin_end = {i, max_size}; + } + } + for (size_t i{s_size}; i > 0; i--) { + for (size_t j{i + 1}; j < s_size; j++) { + dp[i - 1][j] = ((s[i - 1] == s[j]) && dp[i][j - 1]); + if (j - i + 2 > max_size && dp[i - 1][j]) { + max_size = j - i + 2; + begin_end = {i - 1, max_size}; + } } } + return s.substr(begin_end.first, begin_end.second); } - return s.substr(begin_end.first, begin_end.second); -} +}; +#ifdef ALGORITHM_TEST_MACRO } -} +#endif diff --git a/algorithm/dp/leetcode_509.cpp b/algorithm/dp/leetcode_509.cpp new file mode 100644 index 00000000..d85ff2fc --- /dev/null +++ b/algorithm/dp/leetcode_509.cpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + +#ifdef ALGORITHM_TEST_MACRO + +#include +#include +#include + +namespace leetcode_509 { +using std::array; +#endif + +class Solution { +private: + static constexpr const size_t max{31}; + + static constexpr auto func() { + std::array fib{0}; + fib[1] = 1; + for (size_t i{2}; i < max; i++) { + fib[i] = fib[i - 1] + fib[i - 2]; + } + return fib; + } + +public: + int32_t fib(int32_t n) { + static constexpr const std::array arr = func(); + return arr[n]; + } +}; + +#ifdef ALGORITHM_TEST_MACRO +} +#endif diff --git a/algorithm/dp/leetcode_509_1137.cpp b/algorithm/dp/leetcode_509_1137.cpp deleted file mode 100644 index 4cedaffe..00000000 --- a/algorithm/dp/leetcode_509_1137.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_509_1137_test.hpp" -#include - -namespace leetcode_509 { -using std::array; -static constexpr const size_t max{31}; - -constexpr auto func() { - std::array fib{0}; - fib[1] = 1; - for (size_t i{2}; i < max; i++) { - fib[i] = fib[i - 1] + fib[i - 2]; - } - return fib; -} - -int32_t leetcode_509::fib(int32_t n) { - static constexpr const std::array arr = func(); - return arr[n]; -} - -} -namespace leetcode_1137 { -using std::array; -static constexpr const size_t maxV{38}; - -constexpr auto func() { - std::array fib{0}; - fib[1] = 1; - fib[2] = 1; - for (size_t i{3}; i < maxV; i++) { - fib[i] = fib[i - 1] + fib[i - 2] + fib[i - 3]; - } - return fib; -} - -int32_t leetcode_1137::tribonacci(int32_t n) { - static constexpr const std::array arr = func(); - return arr[n]; -} - -} diff --git a/algorithm/dp/leetcode_509_1137_test.hpp b/algorithm/dp/leetcode_509_1137_test.hpp deleted file mode 100644 index b7251f23..00000000 --- a/algorithm/dp/leetcode_509_1137_test.hpp +++ /dev/null @@ -1,73 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day1 -//@Plan 剑指OfferII-I Day08 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_509_1137_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_509_1137_TEST_CPP - -#include -#include -#include - -namespace leetcode_509 { - -struct leetcode_509 final { - static int32_t fib(int32_t n); -}; - - -TEST_CASE("1 [test_509]", "[test_509]") { - static constexpr const auto input{2}; - static constexpr const auto result{1}; - CHECK(result == leetcode_509::fib(input)); -} - -TEST_CASE("2 [test_509]", "[test_509]") { - static constexpr const auto input{3}; - static constexpr const auto result{2}; - CHECK(result == leetcode_509::fib(input)); -} - -TEST_CASE("3 [test_509]", "[test_509]") { - static constexpr const auto input{4}; - static constexpr const auto result{3}; - - CHECK(result == leetcode_509::fib(input)); -} - -} - -namespace leetcode_1137 { -using std::array; - -struct leetcode_1137 final { - static int32_t tribonacci(int32_t n); -}; - -TEST_CASE("1 [test_1137]", "[test_1137]") { - static constexpr const auto input{4}; - static constexpr const auto result{4}; - CHECK(result == leetcode_1137::tribonacci(input)); -} - -TEST_CASE("2 [test_1137]", "[test_1137]") { - static constexpr const auto input{0}; - static constexpr const auto result{0}; - CHECK(result == leetcode_1137::tribonacci(input)); -} - -TEST_CASE("3 [test_1137]", "[test_1137]") { - static constexpr const auto input{1}; - static constexpr const auto result{1}; - CHECK(result == leetcode_1137::tribonacci(input)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_509_1137_TEST_CPP diff --git a/algorithm/dp/leetcode_509_test.cpp b/algorithm/dp/leetcode_509_test.cpp new file mode 100644 index 00000000..9935645c --- /dev/null +++ b/algorithm/dp/leetcode_509_test.cpp @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day1 +//@Plan 剑指OfferII-I Day08 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_509_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_509_TEST_CPP + +#include +#include "leetcode_509.cpp" + +namespace leetcode_509 { + +TEST_CASE("1 [test_509]", "[test_509]") { + static constexpr const auto input{2}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.fib(input)); +} + +TEST_CASE("2 [test_509]", "[test_509]") { + static constexpr const auto input{3}; + static constexpr const auto result{2}; + Solution solution; + CHECK(result == solution.fib(input)); +} + +TEST_CASE("3 [test_509]", "[test_509]") { + static constexpr const auto input{4}; + static constexpr const auto result{3}; + Solution solution; + CHECK(result == solution.fib(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_509_TEST_CPP diff --git a/algorithm/dp/leetcode_516.cpp b/algorithm/dp/leetcode_516.cpp index 0fbc3700..b67cd0f8 100644 --- a/algorithm/dp/leetcode_516.cpp +++ b/algorithm/dp/leetcode_516.cpp @@ -1,40 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_516_test.hpp" #include +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_516 { using std::vector; +using std::string; +#endif -int32_t leetcode_516::longestPalindromeSubseq(const string &s) { - const auto s_size{s.size()}; - if (s.size() <= 1) { - return static_cast(s_size); - } - vector> dp(s_size, vector(s_size, 0)); - int32_t will_return{0}; - for (size_t i{s_size}; i > 0; --i) { - const auto now{i - 1}; // 不需要+1,-1来回切换,好看多了 - dp[now][now] = 1; - const auto ch1{s[now]}; - for (size_t j{now + 1}; j < s_size; ++j) { - const auto ch2{s[j]}; - if (ch1 == ch2) { - dp[now][j] = dp[now + 1][j - 1] + 2; - } else { - dp[now][j] = std::max(dp[now + 1][j], dp[now][j - 1]); - // dp[i][j] 指的是 (i,j)的子序列的最大长度,因此需要在这里递归的去掉左侧或去掉右侧来匹配 +class Solution { +public: + int32_t longestPalindromeSubseq(const string &s) { + const auto s_size{s.size()}; + if (s.size() <= 1) { + return static_cast(s_size); + } + vector> dp(s_size, vector(s_size, 0)); + int32_t will_return{0}; + for (size_t i{s_size}; i > 0; --i) { + const auto now{i - 1}; // 不需要+1,-1来回切换,好看多了 + dp[now][now] = 1; + const auto ch1{s[now]}; + for (size_t j{now + 1}; j < s_size; ++j) { + const auto ch2{s[j]}; + if (ch1 == ch2) { + dp[now][j] = dp[now + 1][j - 1] + 2; + } else { + dp[now][j] = std::max(dp[now + 1][j], dp[now][j - 1]); + // dp[i][j] 指的是 (i,j)的子序列的最大长度,因此需要在这里递归的去掉左侧或去掉右侧来匹配 + } + will_return = std::max(will_return, dp[now][j]); } - will_return = std::max(will_return, dp[now][j]); } - } - return will_return; -} + return will_return; + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_516_test.hpp b/algorithm/dp/leetcode_516_test.cpp similarity index 64% rename from algorithm/dp/leetcode_516_test.hpp rename to algorithm/dp/leetcode_516_test.cpp index 50913d0c..45bcc6bb 100644 --- a/algorithm/dp/leetcode_516_test.hpp +++ b/algorithm/dp/leetcode_516_test.cpp @@ -1,46 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day17 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_516_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_516_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_516_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_516_TEST_CPP #include -#include -#include -#include +#include "leetcode_516.cpp" namespace leetcode_516 { using std::string; -namespace leetcode_516 { -// 最长回文子序列 -int32_t longestPalindromeSubseq(const string &s); -} - - TEST_CASE("1 [test_516]", "[test_516]") { static constexpr const char *const input{"bbbab"}; static constexpr const auto result{4}; - CHECK(result == leetcode_516::longestPalindromeSubseq(input)); + Solution solution; + CHECK(result == solution.longestPalindromeSubseq(input)); } TEST_CASE("2 [test_516]", "[test_516]") { static constexpr const char *const input{"cddb"}; static constexpr const auto result{2}; - CHECK(result == leetcode_516::longestPalindromeSubseq(input)); + Solution solution; + CHECK(result == solution.longestPalindromeSubseq(input)); } TEST_CASE("4 [test_516]", "[test_516]") { static constexpr const char *const input{"aa"}; static constexpr const auto result{2}; - CHECK(result == leetcode_516::longestPalindromeSubseq(input)); + Solution solution; + CHECK(result == solution.longestPalindromeSubseq(input)); } TEST_CASE("3 [test_516]", "[test_516]") { @@ -48,8 +38,9 @@ TEST_CASE("3 [test_516]", "[test_516]") { "euazbipzncptldueeuechubrcourfpftcebikrxhybkymimgvldiwqvkszfycvqyvtiwfckexmowcxztkfyzqovbtmzpxojfofbvwnncajvrvdbvjhcrameamcfmcoxryjukhpljwszknhiypvyskmsujkuggpztltpgoczafmfelahqwjbhxtjmebnymdyxoeodqmvkxittxjnlltmoobsgzdfhismogqfpfhvqnxeuosjqqalvwhsidgiavcatjjgeztrjuoixxxoznklcxolgpuktirmduxdywwlbikaqkqajzbsjvdgjcnbtfksqhquiwnwflkldgdrqrnwmshdpykicozfowmumzeuznolmgjlltypyufpzjpuvucmesnnrwppheizkapovoloneaxpfinaontwtdqsdvzmqlgkdxlbeguackbdkftzbnynmcejtwudocemcfnuzbttcoew" }; static constexpr const auto result{159}; - CHECK(result == leetcode_516::longestPalindromeSubseq(input)); + Solution solution; + CHECK(result == solution.longestPalindromeSubseq(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_516_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_516_TEST_CPP diff --git a/algorithm/dp/leetcode_518.cpp b/algorithm/dp/leetcode_518.cpp index 6c742a20..c202672b 100644 --- a/algorithm/dp/leetcode_518.cpp +++ b/algorithm/dp/leetcode_518.cpp @@ -1,57 +1,62 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanos - -*/ -#include "leetcode_518_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_518 { +using std::vector; +#endif -int32_t leetcode_518::change(int32_t amount, const vector &coins) { - if (amount == 0) { - return coins.empty() ? 0 : 1; - } - const auto coins_size{coins.size()}, amount_size{static_cast(amount)}; - // dp[i][j]代表使用前i种硬币,在j金额下能够凑出的硬币组合数 - vector> dp(coins_size + 1, vector(amount_size + 1, 0)); - dp[0][0] = 0; // 没有硬币,也没有金额,无法做任何事 - for (size_t i{1}; i <= coins_size; i++) { - dp[i][0] = 0; // 世界上没有空硬币,因此完全无法拼凑出来 - } - for (int32_t i{1}; i <= amount; i++) { - dp[0][i] = 0; // 没有硬币,无法拼出任何金额 - } - for (size_t i{1}; i <= coins_size; i++) { - const auto coin{coins[i - 1]}; - for (int32_t j{1}; j <= amount; j++) { - dp[i][j] = dp[i - 1][j]; // 不使用当前硬币情况下的默认值 +class Solution { +public: + int32_t change(int32_t amount, const vector &coins) { + if (amount == 0) { + return coins.empty() ? 0 : 1; + } + const auto coins_size{coins.size()}, amount_size{static_cast(amount)}; + // dp[i][j]代表使用前i种硬币,在j金额下能够凑出的硬币组合数 + vector> dp(coins_size + 1, vector(amount_size + 1, 0)); + dp[0][0] = 0; // 没有硬币,也没有金额,无法做任何事 + for (size_t i{1}; i <= coins_size; i++) { + dp[i][0] = 0; // 世界上没有空硬币,因此完全无法拼凑出来 } - for (size_t coinNum{1}; coinNum * coin <= amount_size; coinNum++) { - const auto coinSum{coinNum * coin}; - dp[i][coinSum] += 1;// 只使用了当前硬币情况下, 多一种情况 - for (size_t j{coinSum + 1}; j <= amount_size; j++) { - dp[i][j] += dp[i - 1][j - coinSum]; + for (int32_t i{1}; i <= amount; i++) { + dp[0][i] = 0; // 没有硬币,无法拼出任何金额 + } + for (size_t i{1}; i <= coins_size; i++) { + const auto coin{coins[i - 1]}; + for (int32_t j{1}; j <= amount; j++) { + dp[i][j] = dp[i - 1][j]; // 不使用当前硬币情况下的默认值 + } + for (size_t coinNum{1}; coinNum * coin <= amount_size; coinNum++) { + const auto coinSum{coinNum * coin}; + dp[i][coinSum] += 1;// 只使用了当前硬币情况下, 多一种情况 + for (size_t j{coinSum + 1}; j <= amount_size; j++) { + dp[i][j] += dp[i - 1][j - coinSum]; + } } } + return dp.back().back(); } - return dp.back().back(); -} -int32_t leetcode_518::change2(int32_t amount, const vector &coins) { - const auto coins_size{coins.size()}, amount_size{static_cast(amount)}; - // ~dp[i][j]代表使用前i种硬币,在j金额下能够凑出的硬币组合数~ - // dp[j]代表j金额下凑出的硬币组合数 - vector dp(amount_size + 1, 0); - dp[0] = 1; // 只有没有金额才能不用硬币拼凑出 - for (size_t i{1}; i <= coins_size; i++) { - const auto coin{coins[i - 1]}; // i代表使用前i种硬币 - for (int32_t j = coin; j <= amount; j++) { - dp[j] += dp[j - coin]; + int32_t change2(int32_t amount, const vector &coins) { + const auto coins_size{coins.size()}, amount_size{static_cast(amount)}; + // ~dp[i][j]代表使用前i种硬币,在j金额下能够凑出的硬币组合数~ + // dp[j]代表j金额下凑出的硬币组合数 + vector dp(amount_size + 1, 0); + dp[0] = 1; // 只有没有金额才能不用硬币拼凑出 + for (size_t i{1}; i <= coins_size; i++) { + const auto coin{coins[i - 1]}; // i代表使用前i种硬币 + for (int32_t j = coin; j <= amount; j++) { + dp[j] += dp[j - coin]; + } } + return dp.back(); } - return dp.back(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_518_test.hpp b/algorithm/dp/leetcode_518_test.cpp similarity index 53% rename from algorithm/dp/leetcode_518_test.hpp rename to algorithm/dp/leetcode_518_test.cpp index 29dc4bda..462a42a4 100644 --- a/algorithm/dp/leetcode_518_test.hpp +++ b/algorithm/dp/leetcode_518_test.cpp @@ -1,38 +1,27 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day20 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_518_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_518_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_518_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_518_TEST_CPP #include -#include -#include -#include + +#include "leetcode_518.cpp" namespace leetcode_518 { using std::vector; -struct leetcode_518 final { - static int32_t change(int32_t amount, const vector &coins); - - static int32_t change2(int32_t amount, const vector &coins); -}; - TEST_CASE("1 [test_518]", "[test_518]") { static constexpr const auto amount{std::array{1, 2, 3, 4, 5, 6}}; const vector coins{1, 2, 5}; static constexpr const auto result{std::array{1, 2, 2, 3, 4, 5}}; + Solution solution; for (size_t i{0}; i < amount.size(); i++) { - CHECK(result[i] == leetcode_518::change(amount[i], coins)); - CHECK(result[i] == leetcode_518::change2(amount[i], coins)); + CHECK(result[i] == solution.change(amount[i], coins)); + CHECK(result[i] == solution.change2(amount[i], coins)); } } @@ -40,25 +29,28 @@ TEST_CASE("3 [test_518]", "[test_518]") { static constexpr const auto amount{10}; const vector coins{10}; static constexpr const auto result{1}; - CHECK(result == leetcode_518::change(amount, coins)); - CHECK(result == leetcode_518::change2(amount, coins)); + Solution solution; + CHECK(result == solution.change(amount, coins)); + CHECK(result == solution.change2(amount, coins)); } TEST_CASE("2 [test_518]", "[test_518]") { static constexpr const auto amount{3}; const vector coins{2}; static constexpr const auto result{0}; - CHECK(result == leetcode_518::change(amount, coins)); - CHECK(result == leetcode_518::change2(amount, coins)); + Solution solution; + CHECK(result == solution.change(amount, coins)); + CHECK(result == solution.change2(amount, coins)); } TEST_CASE("1s [test_518]", "[test_518]") { static constexpr const auto amount{std::array{1, 2, 3, 4, 5, 6}}; const vector coins{1}; static constexpr const auto result{1}; + Solution solution; for (size_t i{0}; i < amount.size(); i++) { - CHECK(result == leetcode_518::change(amount[i], coins)); - CHECK(result == leetcode_518::change2(amount[i], coins)); + CHECK(result == solution.change(amount[i], coins)); + CHECK(result == solution.change2(amount[i], coins)); } } @@ -66,10 +58,11 @@ TEST_CASE("5 [test_518]", "[test_518]") { static constexpr const auto amount{4}; const vector coins{1, 2, 3}; static constexpr const auto result{4}; - CHECK(result == leetcode_518::change(amount, coins)); - CHECK(result == leetcode_518::change2(amount, coins)); + Solution solution; + CHECK(result == solution.change(amount, coins)); + CHECK(result == solution.change2(amount, coins)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_518_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_518_TEST_CPP diff --git a/algorithm/dp/leetcode_55.cpp b/algorithm/dp/leetcode_55.cpp index fbf65eb5..e6a370f9 100644 --- a/algorithm/dp/leetcode_55.cpp +++ b/algorithm/dp/leetcode_55.cpp @@ -1,31 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_55_test.hpp" +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_55 { +using std::vector; +#endif -bool leetcode_55::canJump(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size <= 1) { - return true; - } - size_t fst{0}, end = nums[0]; - while (fst < end) { - const size_t next = end; - for (size_t now{fst}; now <= next; now++) { - end = std::max(now + nums[now], end); - if (end + 1 >= nums_size) { - return true; +class Solution { +public: + bool canJump(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size <= 1) { + return true; + } + size_t fst{0}, end = nums[0]; + while (fst < end) { + const size_t next = end; + for (size_t now{fst}; now <= next; now++) { + end = std::max(now + nums[now], end); + if (end + 1 >= nums_size) { + return true; + } } + fst = next; } - fst = next; + return end + 1 >= nums_size; } - return end + 1 >= nums_size; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_55_test.cpp b/algorithm/dp/leetcode_55_test.cpp new file mode 100644 index 00000000..906649eb --- /dev/null +++ b/algorithm/dp/leetcode_55_test.cpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day4 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_55_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_55_TEST_CPP + +#include +#include "leetcode_55.cpp" + +namespace leetcode_55 { +using std::vector; + +TEST_CASE("1 [test_55]", "[test_55]") { + const vector inputs{2, 3, 1, 1, 4}; + Solution solution; + CHECK(solution.canJump(inputs)); +} + +TEST_CASE("2 [test_55]", "[test_55]") { + const vector inputs{3, 2, 1, 0, 4}; + Solution solution; + CHECK_FALSE(solution.canJump(inputs)); +} + +TEST_CASE("3 [test_55]", "[test_55]") { + const vector inputs{0}; + Solution solution; + CHECK(solution.canJump(inputs)); +} + +TEST_CASE("4 [test_55]", "[test_55]") { + const vector inputs{2, 0, 0}; + Solution solution; + CHECK(solution.canJump(inputs)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_55_TEST_CPP diff --git a/algorithm/dp/leetcode_55_test.hpp b/algorithm/dp/leetcode_55_test.hpp deleted file mode 100644 index 635761c6..00000000 --- a/algorithm/dp/leetcode_55_test.hpp +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day4 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_55_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_55_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_55 { -using std::vector; - -struct leetcode_55 { - static bool canJump(const vector &nums); -}; - -TEST_CASE("1 [test_55]", "[test_55]") { - const vector inputs{2, 3, 1, 1, 4}; - CHECK(leetcode_55::canJump(inputs)); -} - -TEST_CASE("2 [test_55]", "[test_55]") { - const vector inputs{3, 2, 1, 0, 4}; - CHECK_FALSE(leetcode_55::canJump(inputs)); -} - -TEST_CASE("3 [test_55]", "[test_55]") { - const vector inputs{0}; - CHECK(leetcode_55::canJump(inputs)); -} - -TEST_CASE("4 [test_55]", "[test_55]") { - const vector inputs{2, 0, 0}; - CHECK(leetcode_55::canJump(inputs)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_55_TEST_CPP diff --git a/algorithm/dp/leetcode_5_test.hpp b/algorithm/dp/leetcode_5_test.cpp similarity index 68% rename from algorithm/dp/leetcode_5_test.hpp rename to algorithm/dp/leetcode_5_test.cpp index 704de177..c2d1e423 100644 --- a/algorithm/dp/leetcode_5_test.hpp +++ b/algorithm/dp/leetcode_5_test.cpp @@ -1,32 +1,19 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day17 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_5_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_5_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_5_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_5_TEST_CPP #include -#include -#include -#include -#include +#include "leetcode_5.cpp" namespace leetcode_5 { -namespace lcs_5 { using std::string; using std::vector; -namespace leetcode_5 { -string longestPalindrome(const string &s); -} - template constexpr size_t arr_length(const Type (&)[length]) { return length; @@ -40,56 +27,64 @@ constexpr size_t arr_length(const char (&)[length]) { TEST_CASE("1 [test_5]", "[test_5]") { static constexpr const auto *const input{"babad"}; static constexpr const char result[]{"bab"}; - CHECK(arr_length(result) == leetcode_5::longestPalindrome(input).size()); + Solution solution; + CHECK(arr_length(result) == solution.longestPalindrome(input).size()); } TEST_CASE("2 [test_5]", "[test_5]") { static constexpr const auto *const input{"cbbc"}; static constexpr const char result[]{"cbbc"}; - CHECK(arr_length(result) == leetcode_5::longestPalindrome(input).size()); - CHECK(result == leetcode_5::longestPalindrome(input)); + Solution solution; + CHECK(arr_length(result) == solution.longestPalindrome(input).size()); + CHECK(result == solution.longestPalindrome(input)); } TEST_CASE("2_ [test_5]", "[test_5]") { static constexpr const auto *const input{"cbbd"}; static constexpr const char result[]{"bb"}; - CHECK(arr_length(result) == leetcode_5::longestPalindrome(input).size()); - CHECK(result == leetcode_5::longestPalindrome(input)); + Solution solution; + CHECK(arr_length(result) == solution.longestPalindrome(input).size()); + CHECK(result == solution.longestPalindrome(input)); } TEST_CASE("3 [test_5]", "[test_5]") { static constexpr const auto *const input{"cb"}; static constexpr const char result[]{"c"}; - CHECK(arr_length(result) == leetcode_5::longestPalindrome(input).size()); + Solution solution; + CHECK(arr_length(result) == solution.longestPalindrome(input).size()); } TEST_CASE("4 [test_5]", "[test_5]") { static constexpr const auto *const input{"c"}; static constexpr const char result[]{"c"}; - CHECK(arr_length(result) == leetcode_5::longestPalindrome(input).size()); - CHECK(result == leetcode_5::longestPalindrome(input)); + Solution solution; + CHECK(arr_length(result) == solution.longestPalindrome(input).size()); + CHECK(result == solution.longestPalindrome(input)); } TEST_CASE("5 [test_5]", "[test_5]") { static constexpr const auto *const input{""}; static constexpr const char result[]{""}; - CHECK(arr_length(result) == leetcode_5::longestPalindrome(input).size()); - CHECK(result == leetcode_5::longestPalindrome(input)); + Solution solution; + CHECK(arr_length(result) == solution.longestPalindrome(input).size()); + CHECK(result == solution.longestPalindrome(input)); } TEST_CASE("6 [test_5]", "[test_5]") { static constexpr const auto *const input{"ac"}; static constexpr const char result[]{"a"}; - CHECK(arr_length(result) == leetcode_5::longestPalindrome(input).size()); - CHECK(result == leetcode_5::longestPalindrome(input)); + Solution solution; + CHECK(arr_length(result) == solution.longestPalindrome(input).size()); + CHECK(result == solution.longestPalindrome(input)); } TEST_CASE("7 [test_5]", "[test_5]") { static constexpr const auto *const input{"aaaaa"}; static constexpr const char result[]{"aaaaa"}; - CHECK(arr_length(result) == leetcode_5::longestPalindrome(input).size()); - CHECK(result == leetcode_5::longestPalindrome(input)); + Solution solution; + CHECK(arr_length(result) == solution.longestPalindrome(input).size()); + CHECK(result == solution.longestPalindrome(input)); } TEST_CASE("8 [test_5]", "[test_5]") { @@ -97,10 +92,10 @@ TEST_CASE("8 [test_5]", "[test_5]") { "mozblnzrszxtdjmwvgeovtxoftpcsbnjryogrnibiiqfexljlfikfcxvrzrpfvugtdjrlkgvkmrqgeltifdehsewpdhpjpnuobmuozopmglnocqcozvratjpzrklexqdeuvvzfjkuknkkoynxptrgtzadmpfdkphfjhdulhzncoofmmrwqjxeyhodfavcgpjmohohuztezdxegqzbaaobzrqptuqsvwnfdneyccbkgkjafztytwuppvleukdqqzyeiltsvoqbxupbasiityganofxijucwzqgtdyxljociwwjdrnfnfbwyymmvbuvbrdnvcubzkohknbsneutrcukfiqqhfviqdsbtrldipenqifdcrenpuyaqvkparycksurhbtjppwhezbcgocamurdawimkzzkmiwadrumacogcbzehwppjtbhruskcyrapkvqayupnercdfiqnepidlrtbsdqivfhqqifkucrtuensbnkhokzbucvndrbvubvmmyywbfnfnrdjwwicojlxydtgqzwcujixfonagytiisabpuxbqovstlieyzqqdkuelvppuwtytzfajkgkbccyendfnwvsqutpqrzboaabzqgexdzetzuhohomjpgcvafdohyexjqwrmmfoocnzhludhjfhpkdfpmdaztgrtpxnyokknkukjfzvvuedqxelkrzpjtarvzocqconlgmpozoumbounpjphdpweshedfitlegqrmkvgklrjdtguvfprzrvxcfkifljlxefqiibinrgoyrjnbscptfoxtvoegvwmjdtxzsrznlbzom"}; static constexpr const char result[]{ "mozblnzrszxtdjmwvgeovtxoftpcsbnjryogrnibiiqfexljlfikfcxvrzrpfvugtdjrlkgvkmrqgeltifdehsewpdhpjpnuobmuozopmglnocqcozvratjpzrklexqdeuvvzfjkuknkkoynxptrgtzadmpfdkphfjhdulhzncoofmmrwqjxeyhodfavcgpjmohohuztezdxegqzbaaobzrqptuqsvwnfdneyccbkgkjafztytwuppvleukdqqzyeiltsvoqbxupbasiityganofxijucwzqgtdyxljociwwjdrnfnfbwyymmvbuvbrdnvcubzkohknbsneutrcukfiqqhfviqdsbtrldipenqifdcrenpuyaqvkparycksurhbtjppwhezbcgocamurdawimkzzkmiwadrumacogcbzehwppjtbhruskcyrapkvqayupnercdfiqnepidlrtbsdqivfhqqifkucrtuensbnkhokzbucvndrbvubvmmyywbfnfnrdjwwicojlxydtgqzwcujixfonagytiisabpuxbqovstlieyzqqdkuelvppuwtytzfajkgkbccyendfnwvsqutpqrzboaabzqgexdzetzuhohomjpgcvafdohyexjqwrmmfoocnzhludhjfhpkdfpmdaztgrtpxnyokknkukjfzvvuedqxelkrzpjtarvzocqconlgmpozoumbounpjphdpweshedfitlegqrmkvgklrjdtguvfprzrvxcfkifljlxefqiibinrgoyrjnbscptfoxtvoegvwmjdtxzsrznlbzom"}; - CHECK(arr_length(result) == leetcode_5::longestPalindrome(input).size()); - CHECK(result == leetcode_5::longestPalindrome(input)); + Solution solution; + CHECK(arr_length(result) == solution.longestPalindrome(input).size()); + CHECK(result == solution.longestPalindrome(input)); } } -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_5_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_5_TEST_CPP diff --git a/algorithm/dp/leetcode_62.cpp b/algorithm/dp/leetcode_62.cpp index 959219be..58370cb7 100644 --- a/algorithm/dp/leetcode_62.cpp +++ b/algorithm/dp/leetcode_62.cpp @@ -1,22 +1,26 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_62_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include namespace leetcode_62 { +using std::vector; +#endif -int leetcode_62::uniquePaths(size_t m, size_t n) { - vector> DP(m, vector(n, 1)); - for (size_t i{1}; i < m; i++) { - for (size_t j{1}; j < n; j++) { - DP[i][j] = DP[i - 1][j] + DP[i][j - 1]; +class Solution { +public: + int uniquePaths(size_t m, size_t n) { + vector> DP(m, vector(n, 1)); + for (size_t i{1}; i < m; i++) { + for (size_t j{1}; j < n; j++) { + DP[i][j] = DP[i - 1][j] + DP[i][j - 1]; + } } + return DP.back().back(); } - return DP.back().back(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_62_test.hpp b/algorithm/dp/leetcode_62_test.cpp similarity index 52% rename from algorithm/dp/leetcode_62_test.hpp rename to algorithm/dp/leetcode_62_test.cpp index 79d513e4..7ab17b13 100644 --- a/algorithm/dp/leetcode_62_test.hpp +++ b/algorithm/dp/leetcode_62_test.cpp @@ -1,46 +1,38 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Description 不同路径 //@Plan 动态规划入门 Day15 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_62_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_62_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_62_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_62_TEST_CPP #include -#include -#include -#include +#include "leetcode_62.cpp" namespace leetcode_62 { using std::vector; -struct leetcode_62 final { - static int32_t uniquePaths(size_t m, size_t n); -}; - TEST_CASE("1 [test_62]", "[test_62]") { static constexpr const size_t m{3}, n{7}; static constexpr const auto result{28}; - CHECK(result == leetcode_62::uniquePaths(m, n)); + Solution solution; + CHECK(result == solution.uniquePaths(m, n)); } TEST_CASE("2 [test_62]", "[test_62]") { static constexpr const size_t m{7}, n{3}; static constexpr const auto result{28}; - CHECK(result == leetcode_62::uniquePaths(m, n)); + Solution solution; + CHECK(result == solution.uniquePaths(m, n)); } TEST_CASE("3 [test_62]", "[test_62]") { static constexpr const size_t m{3}, n{3}; static constexpr const auto result{6}; - CHECK(result == leetcode_62::uniquePaths(m, n)); + Solution solution; + CHECK(result == solution.uniquePaths(m, n)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_62_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_62_TEST_CPP diff --git a/algorithm/dp/leetcode_63.cpp b/algorithm/dp/leetcode_63.cpp index b67c6c7a..e3054fbe 100644 --- a/algorithm/dp/leetcode_63.cpp +++ b/algorithm/dp/leetcode_63.cpp @@ -1,36 +1,40 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_63_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include namespace leetcode_63 { +using std::vector; +#endif -int32_t leetcode_63::uniquePathsWithObstacles(const vector> &obs) { - const size_t m{obs.size()}; - if (m == 0) { - return 0; - } - const size_t n{obs[0].size()}; - vector> DP(m, vector(n, 0)); - DP[0][0] = (obs[0][0] == 0); - for (size_t i{1}; i < m; i++) { - DP[i][0] = (DP[i - 1][0] != 0) && (obs[i][0] == 0); - } - for (size_t i{1}; i < n; i++) { - DP[0][i] = (DP[0][i - 1] != 0) && (obs[0][i] == 0); - } - for (size_t i{1}; i < m; i++) { - for (size_t j{1}; j < n; j++) { - if (obs[i][j] == 0) { - DP[i][j] = DP[i - 1][j] + DP[i][j - 1]; +class Solution { +public: + int32_t uniquePathsWithObstacles(const vector> &obs) { + const size_t m{obs.size()}; + if (m == 0) { + return 0; + } + const size_t n{obs[0].size()}; + vector> DP(m, vector(n, 0)); + DP[0][0] = (obs[0][0] == 0); + for (size_t i{1}; i < m; i++) { + DP[i][0] = (DP[i - 1][0] != 0) && (obs[i][0] == 0); + } + for (size_t i{1}; i < n; i++) { + DP[0][i] = (DP[0][i - 1] != 0) && (obs[0][i] == 0); + } + for (size_t i{1}; i < m; i++) { + for (size_t j{1}; j < n; j++) { + if (obs[i][j] == 0) { + DP[i][j] = DP[i - 1][j] + DP[i][j - 1]; + } } } + return DP.back().back(); } - return DP.back().back(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_63_test.hpp b/algorithm/dp/leetcode_63_test.cpp similarity index 53% rename from algorithm/dp/leetcode_63_test.hpp rename to algorithm/dp/leetcode_63_test.cpp index 02e6a81f..44066a4c 100644 --- a/algorithm/dp/leetcode_63_test.hpp +++ b/algorithm/dp/leetcode_63_test.cpp @@ -1,42 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Description 不同路径2 //@Plan 动态规划入门 Day15 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_63_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_63_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_63_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_63_TEST_CPP #include -#include -#include -#include +#include "leetcode_63.cpp" namespace leetcode_63 { using std::vector; -struct leetcode_63 final { - static int32_t uniquePathsWithObstacles(const vector> &obstacleGrid); -}; - TEST_CASE("1 [test_63]", "[test_63]") { const vector> input{{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}; static constexpr const auto result{2}; - CHECK(result == leetcode_63::uniquePathsWithObstacles(input)); + Solution solution; + CHECK(result == solution.uniquePathsWithObstacles(input)); } TEST_CASE("2 [test_63]", "[test_63]") { const vector> input{{0, 1}, {0, 0}}; static constexpr const auto result{1}; - CHECK(result == leetcode_63::uniquePathsWithObstacles(input)); + Solution solution; + CHECK(result == solution.uniquePathsWithObstacles(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_63_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_63_TEST_CPP diff --git a/algorithm/dp/leetcode_64.cpp b/algorithm/dp/leetcode_64.cpp index 11c604b7..79121cb6 100644 --- a/algorithm/dp/leetcode_64.cpp +++ b/algorithm/dp/leetcode_64.cpp @@ -1,29 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_64_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_64 { +using std::vector; +using std::min; +#endif -int32_t leetcode_64::minPathSum(const vector> &grid) { - vector> dp{grid}; - const auto m{grid.size()}, n{grid.front().size()}; - for (size_t i{1}; i < m; i++) { - dp[i][0] += dp[i - 1][0]; - } - for (size_t i{1}; i < n; i++) { - dp[0][i] += dp[0][i - 1]; - } - for (size_t i{1}; i < m; i++) { - for (size_t j{1}; j < n; j++) { - dp[i][j] += std::min(dp[i - 1][j], dp[i][j - 1]); +class Solution { +public: + int32_t minPathSum(const vector> &grid) { + vector> dp{grid}; + const auto m{grid.size()}, n{grid.front().size()}; + for (size_t i{1}; i < m; i++) { + dp[i][0] += dp[i - 1][0]; } + for (size_t i{1}; i < n; i++) { + dp[0][i] += dp[0][i - 1]; + } + for (size_t i{1}; i < m; i++) { + for (size_t j{1}; j < n; j++) { + dp[i][j] += std::min(dp[i - 1][j], dp[i][j - 1]); + } + } + return dp.back().back(); } - return dp.back().back(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_643.cpp b/algorithm/dp/leetcode_643.cpp index 50d55fe7..9f0534ee 100644 --- a/algorithm/dp/leetcode_643.cpp +++ b/algorithm/dp/leetcode_643.cpp @@ -1,29 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanos - -*/ -#include "leetcode_643_test.hpp" +#include #include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_643 { +using std::vector; +#endif -double leetcode_643::findMaxAverage(const vector &nums, int32_t k) { - const auto nums_size{nums.size()}; - if (nums_size <= static_cast(k)) { - return double(std::accumulate(nums.begin(), nums.end(), 0)) / - static_cast(nums_size); - } - vector DP(nums_size - k + 1); - DP[0] = std::accumulate(nums.begin(), nums.begin() + k, 0); - int willreturn = DP[0]; - for (size_t i{1}; i + k <= nums_size; i++) { - DP[i] = DP[i - 1] - nums[i - 1] + nums[k + i - 1]; - willreturn = std::max(willreturn, DP[i]); +class Solution { +public: + double findMaxAverage(const vector &nums, int32_t k) { + const auto nums_size{nums.size()}; + if (nums_size <= static_cast(k)) { + return double(std::accumulate(nums.begin(), nums.end(), 0)) / + static_cast(nums_size); + } + vector DP(nums_size - k + 1); + DP[0] = std::accumulate(nums.begin(), nums.begin() + k, 0); + int willreturn = DP[0]; + for (size_t i{1}; i + k <= nums_size; i++) { + DP[i] = DP[i - 1] - nums[i - 1] + nums[k + i - 1]; + willreturn = std::max(willreturn, DP[i]); + } + return willreturn / double(k); } - return willreturn / double(k); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_643_test.hpp b/algorithm/dp/leetcode_643_test.cpp similarity index 55% rename from algorithm/dp/leetcode_643_test.hpp rename to algorithm/dp/leetcode_643_test.cpp index 4e6d74c5..0c0f61d5 100644 --- a/algorithm/dp/leetcode_643_test.hpp +++ b/algorithm/dp/leetcode_643_test.cpp @@ -1,48 +1,39 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag DP //@Tag 动态规划 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_643_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_643_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_643_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_643_TEST_CPP #include -#include -#include -#include +#include "leetcode_643.cpp" namespace leetcode_643 { using std::vector; -struct leetcode_643 final { - static double findMaxAverage(const vector &nums, int32_t k); -}; - - TEST_CASE("1 [test_643]", "[test_643]") { const vector input{1, 12, -5, -6, 50, 3}; static constexpr const auto k{4}; static const auto result{Catch::Approx(12.75).epsilon(0.0001)}; - CHECK(result == leetcode_643::findMaxAverage(input, k)); + Solution solution; + CHECK(result == solution.findMaxAverage(input, k)); } TEST_CASE("2 [test_643]", "[test_643]") { const vector input{5}; static constexpr const auto k{1}; static const auto result{Catch::Approx(5.0).epsilon(0.0001)}; - CHECK(result == leetcode_643::findMaxAverage(input, k)); + Solution solution; + CHECK(result == solution.findMaxAverage(input, k)); } TEST_CASE("3 [test_643]", "[test_643]") { const vector input{1, 1, 4, 5, 1, 4}; static constexpr const auto k{2}; static const auto result{Catch::Approx(4.5).epsilon(0.0001)}; - CHECK(result == leetcode_643::findMaxAverage(input, k)); + Solution solution; + CHECK(result == solution.findMaxAverage(input, k)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_643_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_643_TEST_CPP diff --git a/algorithm/dp/leetcode_64_test.hpp b/algorithm/dp/leetcode_64_test.cpp similarity index 55% rename from algorithm/dp/leetcode_64_test.hpp rename to algorithm/dp/leetcode_64_test.cpp index 4e52a989..608f4397 100644 --- a/algorithm/dp/leetcode_64_test.hpp +++ b/algorithm/dp/leetcode_64_test.cpp @@ -1,42 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Description 最小路径和 //@Plan 动态规划入门 Day16 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_64_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_64_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_64_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_64_TEST_CPP #include -#include -#include -#include +#include "leetcode_64.cpp" namespace leetcode_64 { using std::vector; -struct leetcode_64 final { - static int32_t minPathSum(const vector> &grid); -}; - TEST_CASE("1 [test_64]", "[test_64]") { const vector> input{{1, 3, 1}, {1, 5, 1}, {4, 2, 1}}; static constexpr const auto result{7}; - CHECK(result == leetcode_64::minPathSum(input)); + Solution solution; + CHECK(result == solution.minPathSum(input)); } TEST_CASE("2 [test_64]", "[test_64]") { const vector> input{{1, 2, 3}, {4, 5, 6}}; static constexpr const auto result{12}; - CHECK(result == leetcode_64::minPathSum(input)); + Solution solution; + CHECK(result == solution.minPathSum(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_64_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_64_TEST_CPP diff --git a/algorithm/dp/leetcode_70.cpp b/algorithm/dp/leetcode_70.cpp new file mode 100644 index 00000000..545b61b6 --- /dev/null +++ b/algorithm/dp/leetcode_70.cpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO + +#include +#include +#include +#include + +namespace leetcode_70 { +using std::vector; +#endif + +class Solution { +public: + int32_t climbStairs(int32_t n) { + int32_t b{1}; + for (int32_t a{0}, i{0}, temp{-1}; i < n; i++) { + temp = a; + a = b; + b = temp + a; + } + return b; + } +}; + +#ifdef ALGORITHM_TEST_MACRO +} +#endif \ No newline at end of file diff --git a/algorithm/dp/leetcode_70_746.cpp b/algorithm/dp/leetcode_70_746.cpp deleted file mode 100644 index 658ca04e..00000000 --- a/algorithm/dp/leetcode_70_746.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_70_746_test.hpp" - -namespace leetcode_70 { -int32_t leetcode_70::climbStairs(int32_t n) { - int32_t b{1}; - for (int32_t a{0}, i{0}, temp{-1}; i < n; i++) { - temp = a; - a = b; - b = temp + a; - } - return b; -} -} - -namespace leetcode_746 { -int32_t leetcode_746::minCostClimbingStairs(const vector &cost) { - const auto cost_size{cost.size()}; // always >= 2 - vector dp(cost.size() + 1, 0); - for (size_t i{2}; i <= cost_size; i++) { - dp[i] = std::min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); - } - return dp.back(); -} - -int32_t leetcode_746::minCostClimbingStairs2(const vector &cost) { - const auto cost_size{cost.size()}; // always >= 2 - std::array dp{0, 0, 0}; - // 滚 动 数 组 - for (size_t i{2}; i <= cost_size; i++) { - dp[2] = std::min(dp[1] + cost[i - 1], dp[0] + cost[i - 2]); - dp[0] = dp[1]; - dp[1] = dp[2]; - } - return dp[2]; -} -} diff --git a/algorithm/dp/leetcode_70_746_test.hpp b/algorithm/dp/leetcode_70_746_test.hpp deleted file mode 100644 index de561d96..00000000 --- a/algorithm/dp/leetcode_70_746_test.hpp +++ /dev/null @@ -1,77 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Description 斐波那契? -//@Plan 动态规划入门 Day2 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_70_746_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_70_746_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_70 { -using std::vector; - -struct leetcode_70 final { - static int32_t climbStairs(int32_t n); -}; - -TEST_CASE("1 [test_70]", "[test_70]") { - static constexpr const auto input{2}, result{2}; - CHECK(result == leetcode_70::climbStairs(input)); -} - -TEST_CASE("2 [test_70]", "[test_70]") { - static constexpr const auto input{3}, result{3}; - CHECK(result == leetcode_70::climbStairs(input)); -} - -TEST_CASE("3 [test_70]", "[test_70]") { - static constexpr const auto input{4}, result{5}; - CHECK(result == leetcode_70::climbStairs(input)); -} - -TEST_CASE("4 [test_70]", "[test_70]") { - static constexpr const auto input{5}, result{8}; - CHECK(result == leetcode_70::climbStairs(input)); -} - -TEST_CASE("5 [test_70]", "[test_70]") { - static constexpr const auto input{6}, result{13}; - CHECK(result == leetcode_70::climbStairs(input)); -} -} - -namespace leetcode_746 { -using std::vector; - -struct leetcode_746 final { - static int32_t minCostClimbingStairs(const vector &cost); - - static int32_t minCostClimbingStairs2(const vector &cost); -}; - -TEST_CASE("1 [test_746]", "[test_746]") { - const vector input{10, 15, 20}; - static constexpr const auto output{15}; - CHECK(output == leetcode_746::minCostClimbingStairs(input)); - CHECK(output == leetcode_746::minCostClimbingStairs2(input)); -} - -TEST_CASE("2 [test_746]", "[test_746]") { - const vector input{1, 100, 1, 1, 1, 100, 1, 1, 100, 1}; - static constexpr const auto output{6}; - // 0 -> 2 -> 4 ->6 -> 7 -> 9 -> out六跳,每跳cost 1 - CHECK(output == leetcode_746::minCostClimbingStairs(input)); - CHECK(output == leetcode_746::minCostClimbingStairs2(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_70_746_TEST_CPP diff --git a/algorithm/dp/leetcode_70_test.cpp b/algorithm/dp/leetcode_70_test.cpp new file mode 100644 index 00000000..79c1d3f5 --- /dev/null +++ b/algorithm/dp/leetcode_70_test.cpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Description 斐波那契? +//@Plan 动态规划入门 Day2 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_70_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_70_TEST_CPP + +#include +#include "leetcode_70.cpp" + +namespace leetcode_70 { +using std::vector; + +TEST_CASE("1 [test_70]", "[test_70]") { + static constexpr const auto input{2}, result{2}; + Solution solution; + CHECK(result == solution.climbStairs(input)); +} + +TEST_CASE("2 [test_70]", "[test_70]") { + static constexpr const auto input{3}, result{3}; + Solution solution; + CHECK(result == solution.climbStairs(input)); +} + +TEST_CASE("3 [test_70]", "[test_70]") { + static constexpr const auto input{4}, result{5}; + Solution solution; + CHECK(result == solution.climbStairs(input)); +} + +TEST_CASE("4 [test_70]", "[test_70]") { + static constexpr const auto input{5}, result{8}; + Solution solution; + CHECK(result == solution.climbStairs(input)); +} + +TEST_CASE("5 [test_70]", "[test_70]") { + static constexpr const auto input{6}, result{13}; + Solution solution; + CHECK(result == solution.climbStairs(input)); +} +} + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_70_TEST_CPP diff --git a/algorithm/dp/leetcode_714.cpp b/algorithm/dp/leetcode_714.cpp index b5063104..43f76404 100644 --- a/algorithm/dp/leetcode_714.cpp +++ b/algorithm/dp/leetcode_714.cpp @@ -1,49 +1,54 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_714_test.hpp" -#include +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_714 { -using std::stack; +using std::vector; +#endif -int32_t leetcode_714::maxProfit(const vector &prices, int32_t fee) { - const auto p_size{prices.size()}; - if (p_size <= 1) { - return 0; - } - vector dpBuy(p_size + 1, 0), dpSell(p_size + 1, 0); - dpBuy[0] = 0; // 0 day之前无法有任何操作 - dpSell[0] = 0; // 0 day之前无法有任何操作 - dpBuy[1] = -prices[0]; // 1 day 购入 - dpSell[1] = 0; // 无法sell,没东西 - for (size_t i{2}; i <= p_size; i++) { - const auto price{prices[i - 1]}; - dpBuy[i] = std::max(dpBuy[i - 1], dpSell[i - 1] - price); // 只有卖出后有冷冻期,买入时没有 - dpSell[i] = std::max(dpSell[i - 1], dpBuy[i - 1] + price - fee); +class Solution { +public: + int32_t maxProfit(const vector &prices, int32_t fee) { + const auto p_size{prices.size()}; + if (p_size <= 1) { + return 0; + } + vector dpBuy(p_size + 1, 0), dpSell(p_size + 1, 0); + dpBuy[0] = 0; // 0 day之前无法有任何操作 + dpSell[0] = 0; // 0 day之前无法有任何操作 + dpBuy[1] = -prices[0]; // 1 day 购入 + dpSell[1] = 0; // 无法sell,没东西 + for (size_t i{2}; i <= p_size; i++) { + const auto price{prices[i - 1]}; + dpBuy[i] = std::max(dpBuy[i - 1], dpSell[i - 1] - price); // 只有卖出后有冷冻期,买入时没有 + dpSell[i] = std::max(dpSell[i - 1], dpBuy[i - 1] + price - fee); + } + return dpSell.back(); } - return dpSell.back(); -} -int32_t leetcode_714::maxProfit2(const vector &prices, int32_t fee) { - const auto p_size{prices.size()}; - if (p_size <= 1) { - return 0; + int32_t maxProfit2(const vector &prices, int32_t fee) { + const auto p_size{prices.size()}; + if (p_size <= 1) { + return 0; + } + // 忽略掉了第0天 => 第一天的变动 + int32_t buyLast{-prices[0]}, buyNow{0}; + int32_t sellLast{0}, sellNow{0}; + // dpBuy[i], 第i天之后, 购入股票状态下的最大收益 + // dpSell[i], 第i天之后, 出售股票状态下的最大收益 + for (size_t i{1}; i < p_size; i++, sellLast = sellNow, buyLast = buyNow) { + const auto price{prices[i]}; + buyNow = std::max(buyLast, sellLast - price); // + sellNow = std::max(sellLast, buyLast + price - fee); + } + return sellNow; } - // 忽略掉了第0天 => 第一天的变动 - int32_t buyLast{-prices[0]}, buyNow{0}; - int32_t sellLast{0}, sellNow{0}; - // dpBuy[i], 第i天之后, 购入股票状态下的最大收益 - // dpSell[i], 第i天之后, 出售股票状态下的最大收益 - for (size_t i{1}; i < p_size; i++, sellLast = sellNow, buyLast = buyNow) { - const auto price{prices[i]}; - buyNow = std::max(buyLast, sellLast - price); // - sellNow = std::max(sellLast, buyLast + price - fee); - } - return sellNow; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_714_test.hpp b/algorithm/dp/leetcode_714_test.cpp similarity index 52% rename from algorithm/dp/leetcode_714_test.hpp rename to algorithm/dp/leetcode_714_test.cpp index 06a8e738..f8a6057b 100644 --- a/algorithm/dp/leetcode_714_test.hpp +++ b/algorithm/dp/leetcode_714_test.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Tag stack @@ -12,69 +7,67 @@ Copyright (C) 2020-2023 nanos //@Linked 121 122 309 //@Plan 动态规划入门 Day8 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_714_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_714_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_714_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_714_TEST_CPP #include -#include -#include -#include +#include "leetcode_714.cpp" namespace leetcode_714 { using std::vector; -struct leetcode_714 final { - static int32_t maxProfit(const vector &prices, int32_t fee); - - static int32_t maxProfit2(const vector &prices, int32_t fee); -}; - TEST_CASE("0 [test_714]", "[test_714]") { const vector input{1, 2, 3, 0, 2}; static constexpr const auto fee{0}; static constexpr const auto result{4}; - CHECK(result == leetcode_714::maxProfit(input, fee)); - CHECK(result == leetcode_714::maxProfit2(input, fee)); + Solution solution; + CHECK(result == solution.maxProfit(input, fee)); + CHECK(result == solution.maxProfit2(input, fee)); } TEST_CASE("1 [test_714]", "[test_714]") { const vector input{7, 1, 5, 3, 6, 4}; static constexpr const auto fee{0}; static constexpr const auto result{7}; - CHECK(result == leetcode_714::maxProfit(input, fee)); - CHECK(result == leetcode_714::maxProfit2(input, fee)); + Solution solution; + CHECK(result == solution.maxProfit(input, fee)); + CHECK(result == solution.maxProfit2(input, fee)); } TEST_CASE("2 [test_714]", "[test_714]") { const vector input{7, 6, 4, 3, 1}; static constexpr const auto fee{0}; static constexpr const auto result{0}; - CHECK(result == leetcode_714::maxProfit(input, fee)); - CHECK(result == leetcode_714::maxProfit2(input, fee)); + Solution solution; + CHECK(result == solution.maxProfit(input, fee)); + CHECK(result == solution.maxProfit2(input, fee)); } TEST_CASE("3 [test_714]", "[test_714]") { const vector input{1, 2, 3, 4, 5}; static constexpr const auto fee{0}; static constexpr const auto result{4}; - CHECK(result == leetcode_714::maxProfit(input, fee)); - CHECK(result == leetcode_714::maxProfit2(input, fee)); + Solution solution; + CHECK(result == solution.maxProfit(input, fee)); + CHECK(result == solution.maxProfit2(input, fee)); } TEST_CASE("4 [test_714]", "[test_714]") { const vector input{1, 3, 2, 8, 4, 9}; static constexpr const auto fee{2}; static constexpr const auto result{8}; - CHECK(result == leetcode_714::maxProfit(input, fee)); - CHECK(result == leetcode_714::maxProfit2(input, fee)); + Solution solution; + CHECK(result == solution.maxProfit(input, fee)); + CHECK(result == solution.maxProfit2(input, fee)); } TEST_CASE("5 [test_714]", "[test_714]") { const vector input{1, 3, 7, 5, 10, 3}; static constexpr const auto fee{3}; static constexpr const auto result{6}; - CHECK(result == leetcode_714::maxProfit(input, fee)); - CHECK(result == leetcode_714::maxProfit2(input, fee)); + Solution solution; + CHECK(result == solution.maxProfit(input, fee)); + CHECK(result == solution.maxProfit2(input, fee)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_714_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_714_TEST_CPP diff --git a/algorithm/dp/leetcode_72.cpp b/algorithm/dp/leetcode_72.cpp index e7fe6ebf..692179d1 100644 --- a/algorithm/dp/leetcode_72.cpp +++ b/algorithm/dp/leetcode_72.cpp @@ -1,39 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanos - -*/ -#include "leetcode_72_test.hpp" +#include +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_72 { +using std::vector; +using std::string; +#endif -int32_t leetcode_72::minDistance(const string &word1, const string &word2) { - const size_t fst_size{word1.size()}, snd_size{word2.size()}; - vector> dp(fst_size + 1, vector(snd_size + 1, 0)); - // dp[i][j], word1[0~i],word2[0~j]的编辑距离 - // 将增,删,改 规约成 - // A增,B增,A改, 再规约成 - // A最后增, B最后增, A任意改 - for (size_t i{0}; i <= fst_size; i++) { - dp[i][0] = i; - } - for (size_t i{1}; i <= snd_size; i++) { - dp[0][i] = i; - } - for (size_t i{1}; i <= fst_size; i++) { - for (size_t j{1}; j <= snd_size; j++) { - if (word1[i - 1] == word2[j - 1]) { - dp[i][j] = std::min({dp[i - 1][j - 1], dp[i][j - 1] + 1, dp[i - 1][j] + 1}); - // 分别对应不改,B增,A增 - } else { - // 分别对应改,B增,A增 - dp[i][j] = 1 + std::min({dp[i - 1][j - 1], dp[i][j - 1], dp[i - 1][j]}); +class Solution { +public: + int32_t minDistance(const string &word1, const string &word2) { + const size_t fst_size{word1.size()}, snd_size{word2.size()}; + vector> dp(fst_size + 1, vector(snd_size + 1, 0)); + // dp[i][j], word1[0~i],word2[0~j]的编辑距离 + // 将增,删,改 规约成 + // A增,B增,A改, 再规约成 + // A最后增, B最后增, A任意改 + for (size_t i{0}; i <= fst_size; i++) { + dp[i][0] = i; + } + for (size_t i{1}; i <= snd_size; i++) { + dp[0][i] = i; + } + for (size_t i{1}; i <= fst_size; i++) { + for (size_t j{1}; j <= snd_size; j++) { + if (word1[i - 1] == word2[j - 1]) { + dp[i][j] = std::min({dp[i - 1][j - 1], dp[i][j - 1] + 1, dp[i - 1][j] + 1}); + // 分别对应不改,B增,A增 + } else { + // 分别对应改,B增,A增 + dp[i][j] = 1 + std::min({dp[i - 1][j - 1], dp[i][j - 1], dp[i - 1][j]}); + } } } + return static_cast(dp.back().back()); } - return static_cast(dp.back().back()); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_72_test.hpp b/algorithm/dp/leetcode_72_test.cpp similarity index 79% rename from algorithm/dp/leetcode_72_test.hpp rename to algorithm/dp/leetcode_72_test.cpp index 3e0a2e19..bae7742b 100644 --- a/algorithm/dp/leetcode_72_test.hpp +++ b/algorithm/dp/leetcode_72_test.cpp @@ -1,52 +1,44 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Description 最小路径和 //@Plan 动态规划入门 Day19 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_72_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_72_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_72_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_72_TEST_CPP #include -#include -#include -#include +#include "leetcode_72.cpp" namespace leetcode_72 { using std::string; -struct leetcode_72 final { - static int32_t minDistance(const string &word1, const string &word2); -}; - - TEST_CASE("1 [test_72]", "[test_72]") { static constexpr const char *const input1{"abcde"}, *const input2{"ace"}; static constexpr const auto result{2}; - CHECK(result == leetcode_72::minDistance(input1, input2)); + Solution solution; + CHECK(result == solution.minDistance(input1, input2)); } TEST_CASE("2 [test_72]", "[test_72]") { static constexpr const char *const input1{"abc"}, *const input2{"abc"}; static constexpr const auto result{0}; - CHECK(result == leetcode_72::minDistance(input1, input2)); + Solution solution; + CHECK(result == solution.minDistance(input1, input2)); } TEST_CASE("3 [test_72]", "[test_72]") { static constexpr const char *const input1{"abc"}, *const input2{"degf"}; static constexpr const auto result{4}; - CHECK(result == leetcode_72::minDistance(input1, input2)); + Solution solution; + CHECK(result == solution.minDistance(input1, input2)); } TEST_CASE("4 [test_72]", "[test_72]") { static constexpr const char *const input1{"a"}, *const input2{"aba"}; static constexpr const auto result{2}; - CHECK(result == leetcode_72::minDistance(input1, input2)); + Solution solution; + CHECK(result == solution.minDistance(input1, input2)); } TEST_CASE("5 [test_72]", "[test_72]") { @@ -55,25 +47,29 @@ TEST_CASE("5 [test_72]", "[test_72]") { static constexpr const char *const input2{ "nohgdazargvalupetizezqpklktojqtqdivcpsfgjopaxwbkvujilqbclehulatshehmjqhyfkpcfwxovajkvankjkvevgdovazmbgtqfwvejczsnmbchkdibstklkxarwjqbqxwvixavkhylqvghqpifijohudenozotejoxavkfkzcdqnoxydynavwdylwhatslyrwlejwdwrmpevmtwpahatwlaxmjmdgrebmfyngdcbmbgjcvqpcbadujkxaxujudmbejcrevuvcdobolcbstifedcvmngnqhudixgzktcdqngxmruhcxqxypwhahobudelivgvynefkjqdyvalmvudcdivmhghqrelurodwdsvuzmjixgdexonwjczghalsjopixsrwjixuzmjgxydqnipelgrivkzkxgjchibgnqbknstspujwdydszohqjsfuzstyjgnwhsrebmlwzkzijgnmnczmrehspihspyfedabotwvwxwpspypctizyhcxypqzctwlspszonsrmnyvmhsvqtkbyhmhwjmvazaviruzqxmbczaxmtqjexmdudypovkjklynktahupanujylylgrajozobsbwpwtohkfsxeverqxylwdwtojoxydepybavwhgdehafurqtcxqhuhkdwxkdojipolctcvcrsvczcxedglgrejerqdgrsvsxgjodajatsnixutihwpivihadqdotsvyrkxehodybapwlsjexixgponcxifijchejoxgxebmbclczqvkfuzgxsbshqvgfcraxytaxeviryhexmvqjybizivyjanwxmpojgxgbyhcruvqpafwjslkbohqlknkdqjixsfsdurgbsvclmrcrcnulinqvcdqhcvwdaxgvafwravunurqvizqtozuxinytafopmhchmxsxgfanetmdcjalmrolejidylkjktunqhkxchyjmpkvsfgnybsjedmzkrkhwryzan"}; static constexpr const auto result{856}; - CHECK(result == leetcode_72::minDistance(input1, input2)); + Solution solution; + CHECK(result == solution.minDistance(input1, input2)); } TEST_CASE("6 [test_72]", "[test_72]") { static constexpr const char *const input1{"bsbininm"}, *const input2{"jmjkbkjkv"}; static constexpr const auto result{9}; - CHECK(result == leetcode_72::minDistance(input1, input2)); + Solution solution; + CHECK(result == solution.minDistance(input1, input2)); } TEST_CASE("7 [test_72]", "[test_72]") { static constexpr const char *const input1{"horse"}, *const input2{"ros"}; static constexpr const auto result{3}; - CHECK(result == leetcode_72::minDistance(input1, input2)); + Solution solution; + CHECK(result == solution.minDistance(input1, input2)); } TEST_CASE("8 [test_72]", "[test_72]") { static constexpr const char *const input1{"intention"}, *const input2{"execution"}; static constexpr const auto result{5}; // etion - CHECK(result == leetcode_72::minDistance(input1, input2)); + Solution solution; + CHECK(result == solution.minDistance(input1, input2)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_72_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_72_TEST_CPP diff --git a/algorithm/dp/leetcode_740.cpp b/algorithm/dp/leetcode_740.cpp index 3b774e30..c5e75df8 100644 --- a/algorithm/dp/leetcode_740.cpp +++ b/algorithm/dp/leetcode_740.cpp @@ -1,30 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_740_test.hpp" +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_740 { +using std::vector; +#endif -int leetcode_740::deleteAndEarn(const vector &nums) { - vector values(nums); - std::sort(std::begin(values), std::end(values)); - const auto maxV{values.back()}; - vector arr(maxV + 1, 0); - vector dp(maxV + 2, 0); - for (const auto value: values) { - arr[value]++; - } - dp[0] = 0; // 只选前0个肯定只能得到0的点数 - dp[1] = arr[0]; // 只选第一个 只能得到1的点数 - for (int32_t i{2}; i <= maxV + 1; i++) { - dp[i] = std::max(dp[i - 2] + arr[i - 1] * (i - 1), dp[i - 1]); - // 因为排了序,所以考虑的时候后面那个根本还没有, 所以不需要考虑 - // 只需要考虑是 要 i-2并且去掉i-1 还是要i-1 +class Solution { +public: + int deleteAndEarn(const vector &nums) { + vector values(nums); + std::sort(std::begin(values), std::end(values)); + const auto maxV{values.back()}; + vector arr(maxV + 1, 0); + vector dp(maxV + 2, 0); + for (const auto value: values) { + arr[value]++; + } + dp[0] = 0; // 只选前0个肯定只能得到0的点数 + dp[1] = arr[0]; // 只选第一个 只能得到1的点数 + for (int32_t i{2}; i <= maxV + 1; i++) { + dp[i] = std::max(dp[i - 2] + arr[i - 1] * (i - 1), dp[i - 1]); + // 因为排了序,所以考虑的时候后面那个根本还没有, 所以不需要考虑 + // 只需要考虑是 要 i-2并且去掉i-1 还是要i-1 + } + return dp.back(); } - return dp.back(); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_740_test.cpp b/algorithm/dp/leetcode_740_test.cpp new file mode 100644 index 00000000..dc28106d --- /dev/null +++ b/algorithm/dp/leetcode_740_test.cpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day3 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_740_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_740_TEST_CPP + +#include +#include "leetcode_740.cpp" + +namespace leetcode_740 { +using std::vector; + +TEST_CASE("1 [test_740]", "[test_740]") { + const vector input{3, 4, 2}; + static constexpr const auto result{6}; + Solution solution; + CHECK(result == solution.deleteAndEarn(input)); +} + +TEST_CASE("2 [test_740]", "[test_740]") { + const vector input{2, 2, 3, 3, 3, 4}; + static constexpr const auto result{9}; + Solution solution; + CHECK(result == solution.deleteAndEarn(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_740_TEST_CPP diff --git a/algorithm/dp/leetcode_740_test.hpp b/algorithm/dp/leetcode_740_test.hpp deleted file mode 100644 index 967aea5c..00000000 --- a/algorithm/dp/leetcode_740_test.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day3 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_740_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_740_TEST_CPP - -#include -#include -#include -#include - -namespace leetcode_740 { -using std::vector; - -struct leetcode_740 final { - static int deleteAndEarn(const vector &nums); -}; - - -TEST_CASE("1 [test_740]", "[test_740]") { - const vector input{3, 4, 2}; - static constexpr const auto result{6}; - CHECK(result == leetcode_740::deleteAndEarn(input)); -} - -TEST_CASE("2 [test_740]", "[test_740]") { - const vector input{2, 2, 3, 3, 3, 4}; - static constexpr const auto result{9}; - CHECK(result == leetcode_740::deleteAndEarn(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_740_TEST_CPP diff --git a/algorithm/dp/leetcode_746.cpp b/algorithm/dp/leetcode_746.cpp new file mode 100644 index 00000000..259afd4d --- /dev/null +++ b/algorithm/dp/leetcode_746.cpp @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + +#ifdef ALGORITHM_TEST_MACRO + +#include +#include +#include +#include + +namespace leetcode_746 { +using std::vector; +#endif + +class Solution { +public: + int32_t minCostClimbingStairs(const std::vector &cost) { + const auto cost_size{cost.size()}; // always >= 2 + std::vector dp(cost.size() + 1, 0); + for (size_t i{2}; i <= cost_size; i++) { + dp[i] = std::min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); + } + return dp.back(); + } + + int32_t minCostClimbingStairs2(const std::vector &cost) { + const auto cost_size{cost.size()}; // always >= 2 + std::array dp{0, 0, 0}; + // 滚 动 数 组 + for (size_t i{2}; i <= cost_size; i++) { + dp[2] = std::min(dp[1] + cost[i - 1], dp[0] + cost[i - 2]); + dp[0] = dp[1]; + dp[1] = dp[2]; + } + return dp[2]; + } +}; + +#ifdef ALGORITHM_TEST_MACRO +} +#endif \ No newline at end of file diff --git a/algorithm/dp/leetcode_746_test.cpp b/algorithm/dp/leetcode_746_test.cpp new file mode 100644 index 00000000..009566aa --- /dev/null +++ b/algorithm/dp/leetcode_746_test.cpp @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Description 斐波那契? +//@Plan 动态规划入门 Day2 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_746_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_746_TEST_CPP + +#include +#include "leetcode_746.cpp" + +namespace leetcode_746 { +using std::vector; + +TEST_CASE("1 [test_746]", "[test_746]") { + const vector input{10, 15, 20}; + static constexpr const auto output{15}; + Solution solution; + CHECK(output == solution.minCostClimbingStairs(input)); + CHECK(output == solution.minCostClimbingStairs2(input)); +} + +TEST_CASE("2 [test_746]", "[test_746]") { + const vector input{1, 100, 1, 1, 1, 100, 1, 1, 100, 1}; + static constexpr const auto output{6}; + // 0 -> 2 -> 4 ->6 -> 7 -> 9 -> out六跳,每跳cost 1 + Solution solution; + CHECK(output == solution.minCostClimbingStairs(input)); + CHECK(output == solution.minCostClimbingStairs2(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_746_TEST_CPP diff --git a/algorithm/dp/leetcode_91.cpp b/algorithm/dp/leetcode_91.cpp index f046928d..d9d51ef2 100644 --- a/algorithm/dp/leetcode_91.cpp +++ b/algorithm/dp/leetcode_91.cpp @@ -1,36 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_91_test.hpp" #include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_91 { using std::vector; +using std::string; +#endif -int32_t leetcode_91::numDecodings(const string &str) { - const auto str_size{str.size()}; - if (str_size == 1) { - return '1' <= str[0] && str[0] <= '9'; - } - vector dp(str_size + 1, 0); - dp[0] = 1; // 前0个字符 有且只有一种编码方式 - dp[1] = '1' <= str[0] && str[0] <= '9'; // 第一个字符需要在[1,9] - for (size_t i{2}; i <= str_size; i++) { - const auto nowChar{str[i - 1]}; - const auto lastChar{str[i - 2]}; - if ('1' <= nowChar && nowChar <= '9') { - dp[i] += dp[i - 1]; +class Solution { +public: + int32_t numDecodings(const string &str) { + const auto str_size{str.size()}; + if (str_size == 1) { + return '1' <= str[0] && str[0] <= '9'; } - const auto combine{(lastChar - '0') * 10 + (nowChar - '0')}; - if (10 <= combine && combine <= 26) { - dp[i] += dp[i - 2]; + vector dp(str_size + 1, 0); + dp[0] = 1; // 前0个字符 有且只有一种编码方式 + dp[1] = '1' <= str[0] && str[0] <= '9'; // 第一个字符需要在[1,9] + for (size_t i{2}; i <= str_size; i++) { + const auto nowChar{str[i - 1]}; + const auto lastChar{str[i - 2]}; + if ('1' <= nowChar && nowChar <= '9') { + dp[i] += dp[i - 1]; + } + const auto combine{(lastChar - '0') * 10 + (nowChar - '0')}; + if (10 <= combine && combine <= 26) { + dp[i] += dp[i - 2]; + } } + return dp.back(); } - return dp.back(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_918.cpp b/algorithm/dp/leetcode_918.cpp index ed817a2c..899fa989 100644 --- a/algorithm/dp/leetcode_918.cpp +++ b/algorithm/dp/leetcode_918.cpp @@ -1,104 +1,112 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_918_test.hpp" +#include +#include #include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_918 { -int32_t maxSubArray2(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size == 1) { - return nums[0]; - } - vector dp(nums_size + 1, 0); - // dp[i] 考虑前第i个的最大值 X 带有第i个的最大值 √(不然不能直接用dp[i-1]+nums[i-1]) - // 若带前面的,则为 dp[i-1]+nums[i-1] - // 若不带前面的,则为 nums[i-1] - dp[0] = 0; // 选0个一定为0 - dp[1] = nums[0]; // 只选一个肯定是nums[0] - int32_t maxV{nums[0]}; - for (size_t i{2}; i <= nums_size; i++) { - dp[i] = std::max(nums[i - 1], dp[i - 1] + nums[i - 1]); - maxV = std::max(maxV, dp[i]); - } - return maxV; -} +using std::vector; +#endif -int32_t minSubArray2(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size == 1) { - return nums[0]; - } - vector dp(nums_size + 1, 0); - // dp[i] 考虑前第i个的最大值 X 带有第i个的最大值 √(不然不能直接用dp[i-1]+nums[i-1]) - // 若带前面的,则为 dp[i-1]+nums[i-1] - // 若不带前面的,则为 nums[i-1] - dp[0] = 0; // 选0个一定为0 - dp[1] = nums[0]; // 只选一个肯定是nums[0] - int32_t minV{nums[0]}; - for (size_t i{2}; i <= nums_size; i++) { - dp[i] = std::min(nums[i - 1], dp[i - 1] + nums[i - 1]); - minV = std::min(minV, dp[i]); +class Solution { +private: + int32_t maxSubArray2(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size == 1) { + return nums[0]; + } + vector dp(nums_size + 1, 0); + // dp[i] 考虑前第i个的最大值 X 带有第i个的最大值 √(不然不能直接用dp[i-1]+nums[i-1]) + // 若带前面的,则为 dp[i-1]+nums[i-1] + // 若不带前面的,则为 nums[i-1] + dp[0] = 0; // 选0个一定为0 + dp[1] = nums[0]; // 只选一个肯定是nums[0] + int32_t maxV{nums[0]}; + for (size_t i{2}; i <= nums_size; i++) { + dp[i] = std::max(nums[i - 1], dp[i - 1] + nums[i - 1]); + maxV = std::max(maxV, dp[i]); + } + return maxV; } - return minV; -} -int32_t leetcode_918::maxSubarraySumCircular(const vector &nums) { - const int32_t nums_size = nums.size(); - if (nums_size == 1) { - return nums[0]; - } - bool isAllPositive{true}, isAllNegative{true}; - std::for_each(nums.cbegin(), nums.cend(), [&isAllPositive, &isAllNegative](const auto v) { - isAllPositive = isAllPositive && (v > 0); - isAllNegative = isAllNegative && (v < 0); - }); - if (isAllNegative) { - return *std::max_element(nums.cbegin(), nums.cend()); - } else if (isAllPositive) { - return std::accumulate(nums.cbegin(), nums.cend(), 0); - } - const int32_t normal = maxSubArray2(nums); - const auto lastMax = [](const auto fst, const auto lst) { - vector num(fst, lst); - const auto num_size{num.size()}; - if (num_size == 1) { - return num[0]; + int32_t minSubArray2(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size == 1) { + return nums[0]; } - vector dp(num_size + 1, 0); + vector dp(nums_size + 1, 0); + // dp[i] 考虑前第i个的最大值 X 带有第i个的最大值 √(不然不能直接用dp[i-1]+nums[i-1]) + // 若带前面的,则为 dp[i-1]+nums[i-1] + // 若不带前面的,则为 nums[i-1] dp[0] = 0; // 选0个一定为0 - dp[1] = num[0]; // 只选一个肯定是nums[0] - for (size_t i{2}; i <= num_size; i++) { - dp[i] = std::max(num[i - 1], dp[i - 1] + num[i - 1]); - } - return dp.back(); - }; - const auto fst = lastMax(nums.cbegin(), nums.cend()); // conti last's biggest value - const auto lst = lastMax(nums.crbegin(), nums.crend()); // conti fst's biggest value - int32_t lst_rightest{0}, fst_leftest; - for (int32_t i{0}, sums{0}; i < nums_size; i++) { - sums += nums[i]; - if (sums == lst) { - lst_rightest = i; + dp[1] = nums[0]; // 只选一个肯定是nums[0] + int32_t minV{nums[0]}; + for (size_t i{2}; i <= nums_size; i++) { + dp[i] = std::min(nums[i - 1], dp[i - 1] + nums[i - 1]); + minV = std::min(minV, dp[i]); } + return minV; } - for (int32_t i{nums_size - 1}, sums{0}; i >= 0; i--) { - sums += nums[i]; - if (sums == fst) { - fst_leftest = i; + +public: + int32_t maxSubarraySumCircular(const vector &nums) { + const int32_t nums_size = nums.size(); + if (nums_size == 1) { + return nums[0]; + } + bool isAllPositive{true}, isAllNegative{true}; + std::for_each(nums.cbegin(), nums.cend(), [&isAllPositive, &isAllNegative](const auto v) { + isAllPositive = isAllPositive && (v > 0); + isAllNegative = isAllNegative && (v < 0); + }); + if (isAllNegative) { + return *std::max_element(nums.cbegin(), nums.cend()); + } else if (isAllPositive) { + return std::accumulate(nums.cbegin(), nums.cend(), 0); + } + const int32_t normal = maxSubArray2(nums); + const auto lastMax = [](const auto fst, const auto lst) { + vector num(fst, lst); + const auto num_size{num.size()}; + if (num_size == 1) { + return num[0]; + } + vector dp(num_size + 1, 0); + dp[0] = 0; // 选0个一定为0 + dp[1] = num[0]; // 只选一个肯定是nums[0] + for (size_t i{2}; i <= num_size; i++) { + dp[i] = std::max(num[i - 1], dp[i - 1] + num[i - 1]); + } + return dp.back(); + }; + const auto fst = lastMax(nums.cbegin(), nums.cend()); // conti last's biggest value + const auto lst = lastMax(nums.crbegin(), nums.crend()); // conti fst's biggest value + int32_t lst_rightest{0}, fst_leftest; + for (int32_t i{0}, sums{0}; i < nums_size; i++) { + sums += nums[i]; + if (sums == lst) { + lst_rightest = i; + } + } + for (int32_t i{nums_size - 1}, sums{0}; i >= 0; i--) { + sums += nums[i]; + if (sums == fst) { + fst_leftest = i; + } + } + if (fst_leftest < lst_rightest) { + // 判定是否交叉,交叉了的话, 全部的和 - 中间的一块最小和 + return std::max(normal, std::accumulate(nums.cbegin(), nums.cend(), 0) - minSubArray2(nums)); + } else { + // 没交差,直接判断一下 + return std::max(normal, fst + lst); } } - if (fst_leftest < lst_rightest) { - // 判定是否交叉,交叉了的话, 全部的和 - 中间的一块最小和 - return std::max(normal, std::accumulate(nums.cbegin(), nums.cend(), 0) - minSubArray2(nums)); - } else { - // 没交差,直接判断一下 - return std::max(normal, fst + lst); - } -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_918_test.hpp b/algorithm/dp/leetcode_918_test.cpp similarity index 58% rename from algorithm/dp/leetcode_918_test.hpp rename to algorithm/dp/leetcode_918_test.cpp index 3912dda1..6063c65b 100644 --- a/algorithm/dp/leetcode_918_test.hpp +++ b/algorithm/dp/leetcode_918_test.cpp @@ -1,88 +1,87 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day5 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_918_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_918_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_918_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_918_TEST_CPP #include -#include -#include -#include +#include "leetcode_918.cpp" namespace leetcode_918 { using std::vector; -struct leetcode_918 final { - static int32_t maxSubarraySumCircular(const vector &nums); -}; - TEST_CASE("10 [test_918]", "[test_918]") { const vector input{-2, 4, -5, 4, -5, 9, 4}; static constexpr const auto result{15}; - CHECK(result == leetcode_918::maxSubarraySumCircular(input)); + Solution solution; + CHECK(result == solution.maxSubarraySumCircular(input)); } TEST_CASE("9 [test_918]", "[test_918]") { const vector input{2, -2, 2, 7, 8, 0}; static constexpr const auto result{19}; - CHECK(result == leetcode_918::maxSubarraySumCircular(input)); + Solution solution; + CHECK(result == solution.maxSubarraySumCircular(input)); } TEST_CASE("6 [test_918]", "[test_918]") { const vector input{-2, 3, 5}; static constexpr const auto result{8}; - CHECK(result == leetcode_918::maxSubarraySumCircular(input)); + Solution solution; + CHECK(result == solution.maxSubarraySumCircular(input)); } TEST_CASE("1 [test_918]", "[test_918]") { const vector input{1, -2, 3, -2}; static constexpr const auto result{3}; - CHECK(result == leetcode_918::maxSubarraySumCircular(input)); + Solution solution; + CHECK(result == solution.maxSubarraySumCircular(input)); } TEST_CASE("2 [test_918]", "[test_918]") { const vector input{5, -3, 5}; static constexpr const auto result{10}; - CHECK(result == leetcode_918::maxSubarraySumCircular(input)); + Solution solution; + CHECK(result == solution.maxSubarraySumCircular(input)); } TEST_CASE("3 [test_918]", "[test_918]") { const vector input{3, -1, 2, -1}; static constexpr const auto result{4}; - CHECK(result == leetcode_918::maxSubarraySumCircular(input)); + Solution solution; + CHECK(result == solution.maxSubarraySumCircular(input)); } TEST_CASE("4 [test_918]", "[test_918]") { const vector input{3, -2, 2, -3}; static constexpr const auto result{3}; - CHECK(result == leetcode_918::maxSubarraySumCircular(input)); + Solution solution; + CHECK(result == solution.maxSubarraySumCircular(input)); } TEST_CASE("5 [test_918]", "[test_918]") { const vector input{-2, -3, -1}; static constexpr const auto result{-1}; - CHECK(result == leetcode_918::maxSubarraySumCircular(input)); + Solution solution; + CHECK(result == solution.maxSubarraySumCircular(input)); } TEST_CASE("7 [test_918]", "[test_918]") { const vector input{3, 1, 3, 2, 6}; static constexpr const auto result{15}; - CHECK(result == leetcode_918::maxSubarraySumCircular(input)); + Solution solution; + CHECK(result == solution.maxSubarraySumCircular(input)); } TEST_CASE("8 [test_918]", "[test_918]") { const vector input{-7, 1, 2, 7, -2, -5}; static constexpr const auto result{10}; - CHECK(result == leetcode_918::maxSubarraySumCircular(input)); + Solution solution; + CHECK(result == solution.maxSubarraySumCircular(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_918_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_918_TEST_CPP diff --git a/algorithm/dp/leetcode_91_test.hpp b/algorithm/dp/leetcode_91_test.cpp similarity index 59% rename from algorithm/dp/leetcode_91_test.hpp rename to algorithm/dp/leetcode_91_test.cpp index 38c57645..3c6e556c 100644 --- a/algorithm/dp/leetcode_91_test.hpp +++ b/algorithm/dp/leetcode_91_test.cpp @@ -1,68 +1,64 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day10 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_91_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_91_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_91_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_91_TEST_CPP #include -#include -#include -#include +#include "leetcode_91.cpp" namespace leetcode_91 { using std::vector; -struct leetcode_91 final { - static int32_t numDecodings(const string &s); -}; - TEST_CASE("1 [test_91]", "[test_91]") { static constexpr const char *const str{"12"}; static constexpr const auto result{2}; - CHECK(result == leetcode_91::numDecodings(str)); + Solution solution; + CHECK(result == solution.numDecodings(str)); } TEST_CASE("2 [test_91]", "[test_91]") { static constexpr const char *const str{"226"}; static constexpr const auto result{3}; - CHECK(result == leetcode_91::numDecodings(str)); + Solution solution; + CHECK(result == solution.numDecodings(str)); } TEST_CASE("3 [test_91]", "[test_91]") { static constexpr const char *const str{"0"}; static constexpr const auto result{0}; - CHECK(result == leetcode_91::numDecodings(str)); + Solution solution; + CHECK(result == solution.numDecodings(str)); } TEST_CASE("4 [test_91]", "[test_91]") { static constexpr const char *const str{"06"}; static constexpr const auto result{0}; - CHECK(result == leetcode_91::numDecodings(str)); + Solution solution; + CHECK(result == solution.numDecodings(str)); } TEST_CASE("5 [test_91]", "[test_91]") { static constexpr const char *const str{"10"}; static constexpr const auto result{1}; - CHECK(result == leetcode_91::numDecodings(str)); + Solution solution; + CHECK(result == solution.numDecodings(str)); } TEST_CASE("6 [test_91]", "[test_91]") { static constexpr const char *const str{"10011"}; static constexpr const auto result{0}; - CHECK(result == leetcode_91::numDecodings(str)); + Solution solution; + CHECK(result == solution.numDecodings(str)); } TEST_CASE("7 [test_91]", "[test_91]") { static constexpr const char *const str{"012"}; static constexpr const auto result{0}; - CHECK(result == leetcode_91::numDecodings(str)); + Solution solution; + CHECK(result == solution.numDecodings(str)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_91_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_91_TEST_CPP diff --git a/algorithm/dp/leetcode_931.cpp b/algorithm/dp/leetcode_931.cpp index 7b2c1cfa..9d09d651 100644 --- a/algorithm/dp/leetcode_931.cpp +++ b/algorithm/dp/leetcode_931.cpp @@ -1,34 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_931_test.hpp" +#include +#include +#include #include #include namespace leetcode_931 { +using std::vector; +#endif -int32_t leetcode_931::minFallingPathSum(const vector> &matrix) { - if (matrix.empty() || matrix.front().empty()) { - return 0; - } - const auto row{matrix.size()}, col{matrix.front().size()}; - if (col == 1) { - return std::accumulate(matrix.cbegin(), matrix.cend(), 0, - [](auto &fir, const auto &sec) { return fir + sec[0]; }); - } - vector last(row, 0), now(row, 0); - for (size_t line{0}; line < row; line++) { - now[0] = matrix[line][0] + std::min(last[0], last[1]); - for (size_t j{1}; j < col - 1; j++) { - now[j] = matrix[line][j] + std::min({last[j], last[j - 1], last[j + 1]}); +class Solution { +public: + int32_t minFallingPathSum(const vector> &matrix) { + if (matrix.empty() || matrix.front().empty()) { + return 0; + } + const auto row{matrix.size()}, col{matrix.front().size()}; + if (col == 1) { + return std::accumulate(matrix.cbegin(), matrix.cend(), 0, + [](auto &fir, const auto &sec) { return fir + sec[0]; }); } - now[col - 1] = matrix[line][col - 1] + std::min(last[col - 2], last[col - 1]); - std::swap(now, last); + vector last(row, 0), now(row, 0); + for (size_t line{0}; line < row; line++) { + now[0] = matrix[line][0] + std::min(last[0], last[1]); + for (size_t j{1}; j < col - 1; j++) { + now[j] = matrix[line][j] + std::min({last[j], last[j - 1], last[j + 1]}); + } + now[col - 1] = matrix[line][col - 1] + std::min(last[col - 2], last[col - 1]); + std::swap(now, last); + } + return *std::min_element(last.cbegin(), last.cend()); } - return *std::min_element(last.cbegin(), last.cend()); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_931_test.hpp b/algorithm/dp/leetcode_931_test.cpp similarity index 51% rename from algorithm/dp/leetcode_931_test.hpp rename to algorithm/dp/leetcode_931_test.cpp index 3d960168..ec8e2d20 100644 --- a/algorithm/dp/leetcode_931_test.hpp +++ b/algorithm/dp/leetcode_931_test.cpp @@ -1,28 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 //@Plan 动态规划入门 Day13 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_931_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_931_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_931_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_931_TEST_CPP #include -#include -#include -#include +#include "leetcode_931.cpp" namespace leetcode_931 { using std::vector; -struct leetcode_931 final { - static int32_t minFallingPathSum(const vector> &matrix); -}; - TEST_CASE("1 [test_931]", "[test_931]") { const vector> input{ {2, 1, 3}, @@ -30,7 +19,8 @@ TEST_CASE("1 [test_931]", "[test_931]") { {7, 8, 9} }; static constexpr const auto result{13}; - CHECK(result == leetcode_931::minFallingPathSum(input)); + Solution solution; + CHECK(result == solution.minFallingPathSum(input)); } TEST_CASE("2 [test_931]", "[test_931]") { @@ -39,7 +29,8 @@ TEST_CASE("2 [test_931]", "[test_931]") { {-40, -5}, }; static constexpr const auto result{-59}; - CHECK(result == leetcode_931::minFallingPathSum(input)); + Solution solution; + CHECK(result == solution.minFallingPathSum(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_931_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_931_TEST_CPP diff --git a/algorithm/dp/leetcode_97.cpp b/algorithm/dp/leetcode_97.cpp index 2272c058..2a9f8d8b 100644 --- a/algorithm/dp/leetcode_97.cpp +++ b/algorithm/dp/leetcode_97.cpp @@ -1,44 +1,50 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_97_test.hpp" #include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_97 { using std::vector; +using std::string; +#endif -bool leetcode_97::isInterleave(const string &s1, const string &s2, const string &s3) { - const auto s1_size{s1.size()}, s2_size{s2.size()}, s3_size{s3.size()}; - if (s1_size + s2_size != s3_size) { - return false; - } else if (s1_size == 0) { - return s2 == s3; - } else if (s2_size == 0) { - return s1 == s3; - } - vector> dp(s1_size + 1, vector(s2_size + 1, false)); - dp[0][0] = true; - for (size_t i{1}; i <= s1_size && dp[i - 1][0]; i++) { - dp[i][0] = dp[i - 1][0] && (s1[i - 1] == s3[i - 1]); - } - for (size_t i{1}; i <= s2_size && dp[0][i - 1]; i++) { - dp[0][i] = dp[0][i - 1] && (s2[i - 1] == s3[i - 1]); - } - for (size_t i{1}; i <= s1_size; i++) { - for (size_t j{1}; j <= s2_size; j++) { - const char char1{s1[i - 1]}, char2{s2[j - 1]}, char3{s3[i + j - 1]}; - if (char1 == char3) { - dp[i][j] = dp[i][j] || dp[i - 1][j]; - } - if (char2 == char3) { - dp[i][j] = dp[i][j] || dp[i][j - 1]; +class Solution { +public: + bool isInterleave(const string &s1, const string &s2, const string &s3) { + const auto s1_size{s1.size()}, s2_size{s2.size()}, s3_size{s3.size()}; + if (s1_size + s2_size != s3_size) { + return false; + } else if (s1_size == 0) { + return s2 == s3; + } else if (s2_size == 0) { + return s1 == s3; + } + vector> dp(s1_size + 1, vector(s2_size + 1, false)); + dp[0][0] = true; + for (size_t i{1}; i <= s1_size && dp[i - 1][0]; i++) { + dp[i][0] = dp[i - 1][0] && (s1[i - 1] == s3[i - 1]); + } + for (size_t i{1}; i <= s2_size && dp[0][i - 1]; i++) { + dp[0][i] = dp[0][i - 1] && (s2[i - 1] == s3[i - 1]); + } + for (size_t i{1}; i <= s1_size; i++) { + for (size_t j{1}; j <= s2_size; j++) { + const char char1{s1[i - 1]}, char2{s2[j - 1]}, char3{s3[i + j - 1]}; + if (char1 == char3) { + dp[i][j] = dp[i][j] || dp[i - 1][j]; + } + if (char2 == char3) { + dp[i][j] = dp[i][j] || dp[i][j - 1]; + } } } + return dp.back().back(); } - return dp.back().back(); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_97_test.hpp b/algorithm/dp/leetcode_97_test.cpp similarity index 64% rename from algorithm/dp/leetcode_97_test.hpp rename to algorithm/dp/leetcode_97_test.cpp index d7c86fd9..613186e8 100644 --- a/algorithm/dp/leetcode_97_test.hpp +++ b/algorithm/dp/leetcode_97_test.cpp @@ -1,42 +1,34 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DP //@Tag 动态规划 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_97_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_97_TEST_CPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_97_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_97_TEST_CPP #include -#include -#include -#include +#include "leetcode_97.cpp" namespace leetcode_97 { using std::string; -struct leetcode_97 final { - static bool isInterleave(const string &s1, const string &s2, const string &s3); -}; - TEST_CASE("1 [test_97]", "[test_97]") { static constexpr const char *const s1{"aabcc"}, *const s2{"dbbca"}, *const s3{"aadbbcbcac"}; - CHECK(leetcode_97::isInterleave(s1, s2, s3)); + Solution solution; + CHECK(solution.isInterleave(s1, s2, s3)); } TEST_CASE("2 [test_97]", "[test_97]") { static constexpr const char *const s1{"aabcc"}, *const s2{"dbbca"}, *const s3{"aadbbbaccc"}; - CHECK_FALSE(leetcode_97::isInterleave(s1, s2, s3)); + Solution solution; + CHECK_FALSE(solution.isInterleave(s1, s2, s3)); } TEST_CASE("3 [test_97]", "[test_97]") { static constexpr const char *const s1{""}, *const s2{""}, *const s3{""}; - CHECK(leetcode_97::isInterleave(s1, s2, s3)); + Solution solution; + CHECK(solution.isInterleave(s1, s2, s3)); } TEST_CASE("4 [test_97]", "[test_97]") { @@ -46,9 +38,10 @@ TEST_CASE("4 [test_97]", "[test_97]") { "babababababababababababababababababababababababababababababababababababababababababababababababaaaba"}, *const s3{ "abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababbb"}; - CHECK_FALSE(leetcode_97::isInterleave(s1, s2, s3)); + Solution solution; + CHECK_FALSE(solution.isInterleave(s1, s2, s3)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_97_TEST_CPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_97_TEST_CPP diff --git a/algorithm/dp/leetcode_so_46.cpp b/algorithm/dp/leetcode_so_46.cpp index cf0db6e8..8dc83a54 100644 --- a/algorithm/dp/leetcode_so_46.cpp +++ b/algorithm/dp/leetcode_so_46.cpp @@ -1,38 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ -#include "leetcode_so_46_test.hpp" #include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_so_46 { using std::vector; +#endif -int32_t leetcode_so_46::translateNum(int32_t num) { - if (num < 10) { - return 1; - } - vector nums{}; - while (num > 0) { - nums.push_back(num % 10); - num /= 10; - } - vector numbers{nums.rbegin(), nums.rend()}; - const auto nums_size{numbers.size()}; // 此时至少为2 - vector dp(nums_size + 1); - dp[0] = 1;// 空白只有一种可能 - dp[1] = 1; // 一位只有一种可能 - for (size_t i{2}; i <= nums_size; ++i) { // 滚动数组不进行优化 - const auto two{numbers[i - 2] * 10 + numbers[i - 1]}; - if (10 <= two && two <= 25) { - dp[i] += dp[i - 2]; +class Solution { +public: + int32_t translateNum(int32_t num) { + if (num < 10) { + return 1; } - dp[i] += dp[i - 1]; + vector nums{}; + while (num > 0) { + nums.push_back(num % 10); + num /= 10; + } + vector numbers{nums.rbegin(), nums.rend()}; + const auto nums_size{numbers.size()}; // 此时至少为2 + vector dp(nums_size + 1); + dp[0] = 1;// 空白只有一种可能 + dp[1] = 1; // 一位只有一种可能 + for (size_t i{2}; i <= nums_size; ++i) { // 滚动数组不进行优化 + const auto two{numbers[i - 2] * 10 + numbers[i - 1]}; + if (10 <= two && two <= 25) { + dp[i] += dp[i - 2]; + } + dp[i] += dp[i - 1]; + } + return dp.back(); } - return dp.back(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/dp/leetcode_so_46_test.cpp b/algorithm/dp/leetcode_so_46_test.cpp new file mode 100644 index 00000000..11c47394 --- /dev/null +++ b/algorithm/dp/leetcode_so_46_test.cpp @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag DP +//@Tag 动态规划 +//@Plan 剑指OfferII-I Day10 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_SO_46_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_SO_46_TEST_CPP + +#include +#include "leetcode_so_46.cpp" + +namespace leetcode_so_46 { + +TEST_CASE("1 [test_so_46]", "[test_so_46]") { + static constexpr const auto input{12258}; + static constexpr const auto result{5}; + Solution solution; + CHECK(result == solution.translateNum(input)); +} + + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_LEETCODE_SO_46_TEST_CPP diff --git a/algorithm/dp/leetcode_so_46_test.hpp b/algorithm/dp/leetcode_so_46_test.hpp deleted file mode 100644 index eb82307c..00000000 --- a/algorithm/dp/leetcode_so_46_test.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -//@Tag DP -//@Tag 动态规划 -//@Plan 剑指OfferII-I Day10 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_SO_46_TEST_CPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_SO_46_TEST_CPP - -#include -#include -#include - -namespace leetcode_so_46 { - -struct leetcode_so_46 { - static int32_t translateNum(int32_t num); -}; - - -TEST_CASE("1 [test_so_46]", "[test_so_46]") { - static constexpr const auto input{12258}; - static constexpr const auto result{5}; - CHECK(result == leetcode_so_46::translateNum(input)); -} - - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_LEETCODE_SO_46_TEST_CPP diff --git a/algorithm/dp/matrix_multiply.cpp b/algorithm/dp/matrix_multiply.cpp index 2ac63eb2..2f319775 100644 --- a/algorithm/dp/matrix_multiply.cpp +++ b/algorithm/dp/matrix_multiply.cpp @@ -1,50 +1,50 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ -#include "matrix_multiply_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +#include +#include +#include +#include +#include namespace dp { namespace matrix_multiply { + namespace iter { -int64_t min_multiply(const vector> &mats) { - for (auto iter = mats.cbegin(), next = iter + 1; next != mats.cend(); ++iter, ++next) { - CHECK(std::get<1>(*iter) == std::get<0>(*next)); - } - const auto mats_size{mats.size()}; - vector> times(mats_size, vector(mats_size, 0x3f3f3f3f)); - // i < j, times[i][j] = min of matrix multiply times between i to j - for (auto iter{0ull}; iter < mats_size; ++iter) { - times[iter][iter] = 0; // - } - const auto func = [&mats](size_t i, size_t j, size_t k) { - const auto [fstCol, fstRow] = mats[i]; - const auto [sndCol1, sndRow1] = mats[j]; - const auto [trdCol, trdRow] = mats[k]; - return fstCol * sndRow1 * trdRow; - }; - // k-i>j-1-i , k-i>k-j,所以可以从右上的行到左下角,一行行的获取 - for (size_t i{mats_size - 1}; i != 0; --i) { // 代表左上到右下一行的元素数量 - const auto step = mats_size - i; // 代表一步的步长 - for (size_t j{0}; j + step < mats_size; ++j) { // 确保最后一步不越界 - const auto x = j; - const auto y = j + step; - for (size_t k{x}; k < y; ++k) {// 代表中间点 - const auto sums = times[x][k] + times[k + 1][y] + func(x, k, y); - if (sums < times[x][y]) { - times[x][y] = sums; +class Solution { +public: + int64_t min_multiply(const std::vector> &mats) { + const auto mats_size{mats.size()}; + std::vector> times(mats_size, std::vector(mats_size, 0x3f3f3f3f)); + // i < j, times[i][j] = min of matrix multiply times between i to j + for (auto iter{0ull}; iter < mats_size; ++iter) { + times[iter][iter] = 0; // + } + const auto func = [&mats](size_t i, size_t j, size_t k) { + const auto [fstCol, fstRow] = mats[i]; + const auto [sndCol1, sndRow1] = mats[j]; + const auto [trdCol, trdRow] = mats[k]; + return fstCol * sndRow1 * trdRow; + }; + // k-i>j-1-i , k-i>k-j,所以可以从右上的行到左下角,一行行的获取 + for (size_t i{mats_size - 1}; i != 0; --i) { // 代表左上到右下一行的元素数量 + const auto step = mats_size - i; // 代表一步的步长 + for (size_t j{0}; j + step < mats_size; ++j) { // 确保最后一步不越界 + const auto x = j; + const auto y = j + step; + for (size_t k{x}; k < y; ++k) {// 代表中间点 + const auto sums = times[x][k] + times[k + 1][y] + func(x, k, y); + if (sums < times[x][y]) { + times[x][y] = sums; + } } } } + return times[0].back(); } - return times[0].back(); -} +}; } -namespace rec { const auto higherFunction = [](const auto &mats) { return [&mats](size_t i, size_t j, size_t k) { const auto [fstCol, fstRow] = mats[i]; @@ -53,35 +53,37 @@ const auto higherFunction = [](const auto &mats) { return fstCol * sndRow1 * trdRow; }; }; // lambda表达式我的超人 +namespace rec { +class Solution { +private: + int64_t min_multiply_helper(size_t x, size_t y, std::vector> &dp, + const std::function &func) { + if (dp[x][y] != 0) { + return dp[x][y]; + } + int64_t value{0x3f3f3f3f}; + for (size_t k{x}; k < y; ++k) { + value = std::min(value, + min_multiply_helper(x, k, dp, func) + + min_multiply_helper(k + 1, y, dp, func) + + func(x, y, k) -int64_t -min_multiply(size_t x, size_t y, vector> &dp, - const std::function &func) { - if (dp[x][y] != 0) { - return dp[x][y]; + ); + } // 递归实现,简单易懂 + dp[x][y] = value; + return value; } - int64_t value{0x3f3f3f3f}; - for (size_t k{x}; k < y; ++k) { - value = std::min(value, - min_multiply(x, k, dp, func) + - min_multiply(k + 1, y, dp, func) + - func(x, y, k) - ); - } // 递归实现,简单易懂 - dp[x][y] = value; - return value; - -} - -int64_t min_multiply(const vector> &mats) { - const auto mats_size{mats.size()}; - vector> dp(mats_size, vector(mats_size, 0)); - for (size_t iter{0}; iter < mats_size; ++iter) { - dp[iter][iter] = 1; +public: + int64_t min_multiply(const std::vector> &mats) { + const auto mats_size{mats.size()}; + std::vector> dp(mats_size, std::vector(mats_size, 0)); + for (size_t iter{0}; iter < mats_size; ++iter) { + dp[iter][iter] = 1; + } + return min_multiply_helper(0, mats_size - 1, dp, higherFunction(mats)); } - return min_multiply(0, mats_size - 1, dp, higherFunction(mats)); -} +}; } } diff --git a/algorithm/dp/matrix_multiply_test.hpp b/algorithm/dp/matrix_multiply_test.cpp similarity index 65% rename from algorithm/dp/matrix_multiply_test.hpp rename to algorithm/dp/matrix_multiply_test.cpp index 29d77e4b..f1e52f16 100644 --- a/algorithm/dp/matrix_multiply_test.hpp +++ b/algorithm/dp/matrix_multiply_test.cpp @@ -1,20 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_MATRIX_MULTIPLY_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_MATRIX_MULTIPLY_TEST_HPP - -#include -#include -#include -#include +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_MATRIX_MULTIPLY_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_MATRIX_MULTIPLY_TEST_HPP #include +#include "matrix_multiply.cpp" namespace dp { namespace matrix_multiply {// Introduction to Algorithms Edition3 Chapter15.2 @@ -22,7 +13,6 @@ using std::tuple; using std::vector; namespace iter { -int64_t min_multiply(const vector> &mats); TEST_CASE("1 [iter::test_matrix_multiply]", "[test_matrix_multiply]") { const vector> mats{ @@ -34,11 +24,11 @@ TEST_CASE("1 [iter::test_matrix_multiply]", "[test_matrix_multiply]") { std::make_tuple(20, 25), }; constexpr const auto results{15125}; - const auto output = min_multiply(mats); + Solution solution; + const auto output = solution.min_multiply(mats); } } namespace rec { -int64_t min_multiply(const vector> &mats); TEST_CASE("1 [rec::test_matrix_multiply]", "[test_matrix_multiply]") { const vector> mats{ @@ -50,10 +40,11 @@ TEST_CASE("1 [rec::test_matrix_multiply]", "[test_matrix_multiply]") { std::make_tuple(20, 25), }; constexpr const auto results{15125}; - const auto output = min_multiply(mats); + Solution solution; + const auto output = solution.min_multiply(mats); } } } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_MATRIX_MULTIPLY_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_MATRIX_MULTIPLY_TEST_HPP diff --git a/algorithm/dp/package.cpp b/algorithm/dp/package.cpp index 2b349904..af78abf5 100644 --- a/algorithm/dp/package.cpp +++ b/algorithm/dp/package.cpp @@ -1,13 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include "package.hpp" -#include "package_test.hpp" namespace dp_package { diff --git a/algorithm/dp/package.hpp b/algorithm/dp/package.hpp index 2b2aff87..51db815c 100644 --- a/algorithm/dp/package.hpp +++ b/algorithm/dp/package.hpp @@ -1,13 +1,8 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos - -*/ - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_PACKAGE_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_PACKAGE_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_PACKAGE_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_PACKAGE_HPP #include #include @@ -73,4 +68,4 @@ struct Package final : private nonCopyMoveAble { } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_PACKAGE_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_PACKAGE_HPP diff --git a/algorithm/dp/package_test.hpp b/algorithm/dp/package_test.cpp similarity index 93% rename from algorithm/dp/package_test.hpp rename to algorithm/dp/package_test.cpp index 6e4c6cc1..b44b7036 100644 --- a/algorithm/dp/package_test.hpp +++ b/algorithm/dp/package_test.cpp @@ -1,16 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanos +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_DP_PACKAGE_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_DP_PACKAGE_TEST_HPP -*/ - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_DP_PACKAGE_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_DP_PACKAGE_TEST_HPP - -#include "package.hpp" #include +#include "package.cpp" namespace dp_package { @@ -103,4 +98,4 @@ TEST_CASE("3 [test_complate]", "[test_complate]") { } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_DP_PACKAGE_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_DP_PACKAGE_TEST_HPP diff --git a/algorithm/effective_cpp/CMakeLists.txt b/algorithm/effective_cpp/CMakeLists.txt index 0922a83d..37d82c16 100644 --- a/algorithm/effective_cpp/CMakeLists.txt +++ b/algorithm/effective_cpp/CMakeLists.txt @@ -9,7 +9,7 @@ set(dependencies item03_more_const) LIST(APPEND dependencies item04_init_variables) foreach (elementName IN LISTS dependencies) add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) endforeach () diff --git a/algorithm/effective_cpp/item03_more_const.cpp b/algorithm/effective_cpp/item03_more_const.cpp index 5a06d9c1..63d60fd8 100644 --- a/algorithm/effective_cpp/item03_more_const.cpp +++ b/algorithm/effective_cpp/item03_more_const.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include diff --git a/algorithm/effective_cpp/item04_init_variables.cpp b/algorithm/effective_cpp/item04_init_variables.cpp index 3016bdc2..dba45145 100644 --- a/algorithm/effective_cpp/item04_init_variables.cpp +++ b/algorithm/effective_cpp/item04_init_variables.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include diff --git a/algorithm/fft/CMakeLists.txt b/algorithm/fft/CMakeLists.txt index 2711ca35..81807dc5 100644 --- a/algorithm/fft/CMakeLists.txt +++ b/algorithm/fft/CMakeLists.txt @@ -12,8 +12,8 @@ foreach (elementName IN LISTS dependencies) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_${elementName}_test ${CMAKE_CURRENT_SOURCE_DIR}/fft_test.cpp) - target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE CS203_DSAA_TEST_MACRO) - target_link_libraries(${PROJECT_NAME}_${elementName}_test ${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE ALGORITHM_TEST_MACRO) + target_link_libraries(${PROJECT_NAME}_${elementName}_test ${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/fft/fft.cpp b/algorithm/fft/fft.cpp index 12890753..e69796f5 100644 --- a/algorithm/fft/fft.cpp +++ b/algorithm/fft/fft.cpp @@ -1,16 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanos - * @Date: 2021-05-13 20:29:20 - * @LastEditors: nanos - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2021-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2021-2025 nanoseeds #include "fft.hpp" #ifndef M_PI diff --git a/algorithm/fft/fft.hpp b/algorithm/fft/fft.hpp index bb1dc28e..b8460cdc 100644 --- a/algorithm/fft/fft.hpp +++ b/algorithm/fft/fft.hpp @@ -1,18 +1,7 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanos - * @Date: 2021-05-13 20:29:20 - * @LastEditors: nanos - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2021-2023 nanos - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_FFT_FFT_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_FFT_FFT_HPP +// SPDX-FileCopyrightText: 2021-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_FFT_FFT_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_FFT_FFT_HPP #include @@ -60,4 +49,4 @@ inline vector num_to_vec(uint64_t uint64) { return will_return; } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_FFT_FFT_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_FFT_FFT_HPP diff --git a/algorithm/fft/fft_test.cpp b/algorithm/fft/fft_test.cpp index e39c07ef..f0f31ea3 100644 --- a/algorithm/fft/fft_test.cpp +++ b/algorithm/fft/fft_test.cpp @@ -1,16 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanos - * @Date: 2021-05-13 20:29:20 - * @LastEditors: nanos - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2021-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2021-2025 nanoseeds #include #include "fft.hpp" diff --git a/algorithm/fft/unfft.cpp b/algorithm/fft/unfft.cpp index cda94f69..32731b0f 100644 --- a/algorithm/fft/unfft.cpp +++ b/algorithm/fft/unfft.cpp @@ -1,16 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanos - * @Date: 2021-05-13 20:29:37 - * @LastEditors: nanos - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2021-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2021-2025 nanoseeds #include "fft.hpp" namespace fft { diff --git a/algorithm/graph/CMakeLists.txt b/algorithm/graph/CMakeLists.txt index 1bba000b..2a0de7a9 100644 --- a/algorithm/graph/CMakeLists.txt +++ b/algorithm/graph/CMakeLists.txt @@ -8,7 +8,6 @@ add_library(${PROJECT_NAME}_BUILD_GRAPH ${LIB_WAY} ${CMAKE_CURRENT_SOURCE_DIR}/b enable_testing() set(dependencies dijistra flow bfs dfs toposort) -LIST(TRANSFORM dependencies APPEND _test) set(leetcode_order) list(APPEND leetcode_order 743 so_12 so_13 797 1334) @@ -16,11 +15,13 @@ LIST(TRANSFORM leetcode_order PREPEND leetcode_) set(dependencies ${dependencies} ${leetcode_order}) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName}_test - ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName}_test - ${PROJECT_NAME}_BUILD_GRAPH CS203_DSAA_template_INCLUDE) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName}_test from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") - add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}_test) + add_executable(${PROJECT_NAME}_${elementName} + ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_link_libraries(${PROJECT_NAME}_${elementName} + ${PROJECT_NAME}_BUILD_GRAPH algorithm_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") + add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) endforeach () unset(dependencies) \ No newline at end of file diff --git a/algorithm/graph/bfs.hpp b/algorithm/graph/bfs.hpp index a8fb60cf..53d73dd9 100644 --- a/algorithm/graph/bfs.hpp +++ b/algorithm/graph/bfs.hpp @@ -1,13 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_BFS_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_BFS_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_BFS_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_BFS_HPP #include "build_graph.hpp" #include @@ -84,4 +78,4 @@ class graphlist final { } } -#endif // CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_BFS_HPP +#endif // ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_BFS_HPP diff --git a/algorithm/graph/bfs_test.cpp b/algorithm/graph/bfs_test.cpp index c56acf08..59ee11df 100644 --- a/algorithm/graph/bfs_test.cpp +++ b/algorithm/graph/bfs_test.cpp @@ -1,11 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include "bfs.hpp" diff --git a/algorithm/graph/build_graph.cpp b/algorithm/graph/build_graph.cpp index a856db87..3d2b0eac 100644 --- a/algorithm/graph/build_graph.cpp +++ b/algorithm/graph/build_graph.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include "build_graph.hpp" diff --git a/algorithm/graph/build_graph.hpp b/algorithm/graph/build_graph.hpp index a161c607..e13904b9 100644 --- a/algorithm/graph/build_graph.hpp +++ b/algorithm/graph/build_graph.hpp @@ -1,11 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_BUILD_GRAPH_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_BUILD_GRAPH_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_BUILD_GRAPH_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_BUILD_GRAPH_HPP #include #include @@ -28,4 +24,4 @@ adjlist build_adjlist(const vector> &input, int32_t node_num); bool check_graph_cost_all_positive(const vector> &input); } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_BUILD_GRAPH_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_BUILD_GRAPH_HPP diff --git a/algorithm/graph/dfs.hpp b/algorithm/graph/dfs.hpp index 725569a1..3d3f5f48 100644 --- a/algorithm/graph/dfs.hpp +++ b/algorithm/graph/dfs.hpp @@ -1,13 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_DFS_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_DFS_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_DFS_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_DFS_HPP #include "build_graph.hpp" #include @@ -89,4 +83,4 @@ class graphlist final { } } -#endif // CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_DFS_HPP +#endif // ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_DFS_HPP diff --git a/algorithm/graph/dfs_test.cpp b/algorithm/graph/dfs_test.cpp index cc3ea350..614d6287 100644 --- a/algorithm/graph/dfs_test.cpp +++ b/algorithm/graph/dfs_test.cpp @@ -1,11 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include "dfs.hpp" diff --git a/algorithm/graph/dijistra.hpp b/algorithm/graph/dijistra.hpp index 97f6e073..8457285e 100644 --- a/algorithm/graph/dijistra.hpp +++ b/algorithm/graph/dijistra.hpp @@ -1,13 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_DIJISTRA_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_DIJISTRA_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_DIJISTRA_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_DIJISTRA_HPP #include #include @@ -62,4 +56,4 @@ class graphlist final { } } -#endif // CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_DIJISTRA_HPP +#endif // ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_DIJISTRA_HPP diff --git a/algorithm/graph/dijistra_test.cpp b/algorithm/graph/dijistra_test.cpp index 6c42fc64..82b027cf 100644 --- a/algorithm/graph/dijistra_test.cpp +++ b/algorithm/graph/dijistra_test.cpp @@ -1,11 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include "dijistra.hpp" diff --git a/algorithm/graph/flow.hpp b/algorithm/graph/flow.hpp index a0f77568..2b644a1b 100644 --- a/algorithm/graph/flow.hpp +++ b/algorithm/graph/flow.hpp @@ -1,13 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_FLOW_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_FLOW_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_FLOW_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_FLOW_HPP #include "build_graph.hpp" #include @@ -101,4 +95,4 @@ class flow final { }; } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_FLOW_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_FLOW_HPP diff --git a/algorithm/graph/flow_test.cpp b/algorithm/graph/flow_test.cpp index 8b743f81..0366878b 100644 --- a/algorithm/graph/flow_test.cpp +++ b/algorithm/graph/flow_test.cpp @@ -1,16 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanos - * @Date: 2021-06-08 23:10:45 - * @LastEditors: nanos - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include "flow.hpp" diff --git a/algorithm/graph/leetcode_1334.cpp b/algorithm/graph/leetcode_1334.cpp index 6adf289e..8d0f5ab5 100644 --- a/algorithm/graph/leetcode_1334.cpp +++ b/algorithm/graph/leetcode_1334.cpp @@ -1,64 +1,69 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_1334_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include +#include #include +#include +#include namespace leetcode_1334 { using std::priority_queue; +using std::vector; +#endif -//TODO floyd求多元最短路径 - -//本质上是一个单源最短路径 -vector minimum_path(const vector>> &map, const int n) { - constexpr const auto cmp = []( - const std::pair &p1, const std::pair &p2) -> bool { - return p1.second < p2.second; - }; - priority_queue, vector>, decltype(cmp)> nodes(cmp); - vector d(map.size(), INT32_MAX); - d[n] = 0; - nodes.emplace(n, 0); - while (!nodes.empty()) { - const auto root = nodes.top(); - nodes.pop(); - const int root_v = root.first; - for (size_t i{0}, map_root_v_size{map[root_v].size()}; i < map_root_v_size; ++i) { - const auto [fst, snd] = map[root_v][i]; - if (d[fst] > d[root_v] + snd) { - d[fst] = d[root_v] + snd; - nodes.emplace(fst, d[fst]); +class Solution { +private: + //本质上是一个单源最短路径 + vector minimum_path(const vector>> &map, const int n) { + constexpr const auto cmp = []( + const std::pair &p1, const std::pair &p2) -> bool { + return p1.second > p2.second; + }; + priority_queue, vector>, decltype(cmp)> nodes(cmp); + vector d(map.size(), std::numeric_limits::max()); + d[n] = 0; + nodes.emplace(n, 0); + while (!nodes.empty()) { + const auto root = nodes.top(); + nodes.pop(); + const int root_v = root.first; + for (size_t i{0}, map_root_v_size{map[root_v].size()}; i < map_root_v_size; ++i) { + const auto [fst, snd] = map[root_v][i]; + if (d[fst] > d[root_v] + snd) { + d[fst] = d[root_v] + snd; + nodes.emplace(fst, d[fst]); + } } } + return d; } - return d; -} -// 使用多次单源最短路径, 所以会比较慢 -int32_t leetcode_1334::findTheCity(int32_t n, const vector> &edges, int32_t distanceThreshold) { - vector>> maps(n); - const auto cmp = [distanceThreshold](int32_t i) { return i <= distanceThreshold; }; - for (size_t i{0}, edges_size{edges.size()}; i < edges_size; ++i) { - if (edges[i][2] <= distanceThreshold) { - maps[edges[i][0]].emplace_back(edges[i][1], edges[i][2]); - maps[edges[i][1]].emplace_back(edges[i][0], edges[i][2]); +public: + // 使用多次单源最短路径, 所以会比较慢 + int32_t findTheCity(int32_t n, const vector> &edges, int32_t distanceThreshold) { + vector>> maps(n); + const auto cmp = [distanceThreshold](int32_t i) { return i <= distanceThreshold; }; + for (size_t i{0}, edges_size{edges.size()}; i < edges_size; ++i) { + if (edges[i][2] <= distanceThreshold) { + maps[edges[i][0]].emplace_back(edges[i][1], edges[i][2]); + maps[edges[i][1]].emplace_back(edges[i][0], edges[i][2]); + } } - } - int32_t count = INT16_MAX; - int32_t willreturn = -1; - for (int32_t i{0}; i < n; ++i) { - const vector dis = minimum_path(maps, i); - const int32_t temp = std::count_if(dis.begin(), dis.end(), cmp) - 1; - if (count >= temp) { - count = temp; - willreturn = i; + int32_t count = std::numeric_limits::max(); + int32_t willreturn = -1; + for (int32_t i{0}; i < n; ++i) { + const vector dis = minimum_path(maps, i); + const int32_t temp = std::count_if(dis.begin(), dis.end(), cmp) - 1; + if (count >= temp) { + count = temp; + willreturn = i; + } } + return willreturn; } - return willreturn; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/graph/leetcode_1334_test.hpp b/algorithm/graph/leetcode_1334_test.cpp similarity index 70% rename from algorithm/graph/leetcode_1334_test.hpp rename to algorithm/graph/leetcode_1334_test.cpp index 2602812c..e1a0c05f 100644 --- a/algorithm/graph/leetcode_1334_test.hpp +++ b/algorithm/graph/leetcode_1334_test.cpp @@ -1,28 +1,21 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_1334_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_1334_TEST_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_1334_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_1334_TEST_HPP #include #include #include #include +#include "leetcode_1334.cpp" namespace leetcode_1334 { using std::vector; -namespace leetcode_1334 { -int32_t findTheCity(int32_t n, const vector> &edges, int32_t distanceThreshold); -} - using Catch::Matchers::UnorderedEquals; TEST_CASE("basic tests [test_1334]", "[test_1334]") { + Solution s; const vector> vec{ {0, 1, 3}, {1, 2, 1}, @@ -30,10 +23,11 @@ TEST_CASE("basic tests [test_1334]", "[test_1334]") { {2, 3, 1}, }; constexpr const auto n{4}, distanceThreshold{4}; - CHECK(3 == leetcode_1334::findTheCity(n, vec, distanceThreshold)); + CHECK(3 == s.findTheCity(n, vec, distanceThreshold)); } TEST_CASE("basic tests 2 [test_1334]", "[test_1334]") { + Solution s; const vector> vec{ {0, 1, 2}, {0, 4, 8}, @@ -43,10 +37,11 @@ TEST_CASE("basic tests 2 [test_1334]", "[test_1334]") { {3, 4, 1}, }; constexpr const auto n{5}, distanceThreshold{2}; - CHECK(0 == leetcode_1334::findTheCity(n, vec, distanceThreshold)); + CHECK(0 == s.findTheCity(n, vec, distanceThreshold)); } TEST_CASE("basic tests 3 [test_1334]", "[test_1334]") { + Solution s; const vector> vec{ {0, 2, 3996}, {0, 3, 7495}, @@ -69,8 +64,8 @@ TEST_CASE("basic tests 3 [test_1334]", "[test_1334]") { {6, 7, 2202}, }; constexpr const auto n{8}, distanceThreshold{7937}; - CHECK(7 == leetcode_1334::findTheCity(n, vec, distanceThreshold)); + CHECK(7 == s.findTheCity(n, vec, distanceThreshold)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_1334_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_1334_TEST_HPP diff --git a/algorithm/graph/leetcode_743.cpp b/algorithm/graph/leetcode_743.cpp index 6321eebc..52d69c26 100644 --- a/algorithm/graph/leetcode_743.cpp +++ b/algorithm/graph/leetcode_743.cpp @@ -1,51 +1,57 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_743_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include +#include +#include +#include namespace leetcode_743 { using std::priority_queue; using std::unordered_set; +using std::vector; +#endif -int32_t leetcode_743::networkDelayTime(const vector> ×, int32_t n, int32_t k) { - struct time_ { - int32_t end, cost; +class Solution { +public: + int32_t networkDelayTime(const vector> ×, int32_t n, int32_t k) { + struct time_ { + int32_t end, cost; - time_(int32_t end, int32_t cost) : end(end), cost(cost) {} + time_(int32_t end, int32_t cost) : end(end), cost(cost) {} - bool operator<(const time_ &v2) const { return this->cost > v2.cost; } - }; - k -= 1; - vector> dis(n, vector{}); - vector results(n, 0x3f3f3f3f); - for (const auto &time: times) { - const auto &first = time[0]; - const auto &second = time[1]; - const auto &third = time[2]; - dis[first - 1].emplace_back(second - 1, third); - } - priority_queue priorityQueue{}; - unordered_set uMap{}; - results[k] = 0; - priorityQueue.emplace(k, -1); - while (!priorityQueue.empty()) { - const auto head = priorityQueue.top(); - priorityQueue.pop(); - for (auto &i: dis[head.end]) { - const auto val = results[head.end] + i.cost; - if (val < results[i.end]) { - results[i.end] = val; - priorityQueue.push(i); + bool operator<(const time_ &v2) const { return this->cost > v2.cost; } + }; + k -= 1; + vector> dis(n, vector{}); + vector results(n, 0x3f3f3f3f); + for (const auto &time: times) { + const auto &first = time[0]; + const auto &second = time[1]; + const auto &third = time[2]; + dis[first - 1].emplace_back(second - 1, third); + } + priority_queue priorityQueue{}; + unordered_set uMap{}; + results[k] = 0; + priorityQueue.emplace(k, -1); + while (!priorityQueue.empty()) { + const auto head = priorityQueue.top(); + priorityQueue.pop(); + for (auto &i: dis[head.end]) { + const auto val = results[head.end] + i.cost; + if (val < results[i.end]) { + results[i.end] = val; + priorityQueue.push(i); + } } } + const int32_t will_return = *std::max_element(std::cbegin(results), std::cend(results)); + return will_return == 0x3f3f3f3f ? -1 : will_return; } - const int32_t will_return = *std::max_element(std::cbegin(results), std::cend(results)); - return will_return == 0x3f3f3f3f ? -1 : will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/graph/leetcode_743_test.hpp b/algorithm/graph/leetcode_743_test.cpp similarity index 56% rename from algorithm/graph/leetcode_743_test.hpp rename to algorithm/graph/leetcode_743_test.cpp index 68f6dcb7..fb6b55ea 100644 --- a/algorithm/graph/leetcode_743_test.hpp +++ b/algorithm/graph/leetcode_743_test.cpp @@ -1,26 +1,19 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_743_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_743_TEST_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_743_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_743_TEST_HPP #include #include #include #include +#include "leetcode_743.cpp" namespace leetcode_743 { using std::vector; -struct leetcode_743 { - static int32_t networkDelayTime(const vector> ×, int32_t n, int32_t k); -}; - TEST_CASE("basic tests [test_743]", "[test_743]") { + Solution s; const vector> input{ {2, 1, 1}, {2, 3, 1}, @@ -28,16 +21,17 @@ TEST_CASE("basic tests [test_743]", "[test_743]") { }; static constexpr const auto n{4}, k{2}; static constexpr const auto result{2}; - CHECK(result == leetcode_743::networkDelayTime(input, n, k)); + CHECK(result == s.networkDelayTime(input, n, k)); } TEST_CASE("basic tests 2[test_743]", "[test_743]") { + Solution s; const vector> input{ {1, 2, 1}, }; static constexpr const auto n{2}, k{1}; static constexpr const auto result{1}; - CHECK(result == leetcode_743::networkDelayTime(input, n, k)); + CHECK(result == s.networkDelayTime(input, n, k)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_743_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_743_TEST_HPP diff --git a/algorithm/graph/leetcode_797.cpp b/algorithm/graph/leetcode_797.cpp index e95998d0..b678a8e6 100644 --- a/algorithm/graph/leetcode_797.cpp +++ b/algorithm/graph/leetcode_797.cpp @@ -1,67 +1,73 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_797_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include +#include +#include +#include namespace leetcode_797 { using std::set; +using std::vector; +#endif -vector> leetcode_797::allPathsSourceTarget(const vector> &graph) { - // bfs - vector> will_return; - set> re_org; - vector> temp; - temp.push_back(vector{0}); - const size_t aim = graph.size() - 1; - for (size_t i{0}; i < aim; i++) { - vector> replace; - for (const auto &j: temp) { - vector added(j); - added.push_back(0); - const int32_t where = j.back(); - const auto j_size = j.size(); - for (const auto k: graph[where]) { - added[j_size] = k; - if (static_cast(k) == aim) { - re_org.insert(added); - } else { - replace.push_back(added); +class Solution { +public: + vector> allPathsSourceTarget(const vector> &graph) { + // bfs + vector> will_return; + set> re_org; + vector> temp; + temp.push_back(vector{0}); + const size_t aim = graph.size() - 1; + for (size_t i{0}; i < aim; i++) { + vector> replace; + for (const auto &j: temp) { + vector added(j); + added.push_back(0); + const int32_t where = j.back(); + const auto j_size = j.size(); + for (const auto k: graph[where]) { + added[j_size] = k; + if (static_cast(k) == aim) { + re_org.insert(added); + } else { + replace.push_back(added); + } } } + if (replace.empty()) { + break; + } + temp = replace; } - if (replace.empty()) { - break; + will_return.reserve(re_org.size()); + for (const auto &iter: re_org) { + will_return.push_back(iter); } - temp = replace; + return will_return; } - will_return.reserve(re_org.size()); - for (const auto &iter: re_org) { - will_return.push_back(iter); + + vector> allPathsSourceTarget2(const vector> &graph) { + vector> answer{}; + vector path{0}; + const auto aim = static_cast(graph.size() - 1); + const std::function dfs = [&answer, &path, &graph, &dfs, &aim](int32_t now) { + if (now == aim) { + answer.push_back(path); + return; + } + for (const auto ele: graph[now]) { + path.push_back(ele); + dfs(ele); + path.pop_back(); + } + }; + dfs(0); + return answer; } - return will_return; -} +}; -vector> leetcode_797::allPathsSourceTarget2(const vector> &graph) { - vector> answer{}; - vector path{0}; - const auto aim = static_cast(graph.size() - 1); - const std::function dfs = [&answer, &path, &graph, &dfs, &aim](int32_t now) { - if (now == aim) { - answer.push_back(path); - return; - } - for (const auto ele: graph[now]) { - path.push_back(ele); - dfs(ele); - path.pop_back(); - } - }; - dfs(0); - return answer; -} +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/graph/leetcode_797_test.cpp b/algorithm/graph/leetcode_797_test.cpp new file mode 100644 index 00000000..c782f5ab --- /dev/null +++ b/algorithm/graph/leetcode_797_test.cpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_797_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_797_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_797.cpp" + +namespace leetcode_797 { +using std::vector; + +using Catch::Matchers::UnorderedEquals; + +TEST_CASE("basic tests [test_797]", "[test_797]") { + Solution s; + const vector> input{ + {4, 3, 1}, + {3, 2, 4}, + {3}, + {4}, + {} + }; + const vector> result{ + {0, 4}, + {0, 3, 4}, + {0, 1, 3, 4}, + {0, 1, 2, 3, 4}, + {0, 1, 4} + }; + CHECK_THAT(result, UnorderedEquals(s.allPathsSourceTarget(input))); + CHECK_THAT(result, UnorderedEquals(s.allPathsSourceTarget2(input))); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_797_TEST_HPP diff --git a/algorithm/graph/leetcode_797_test.hpp b/algorithm/graph/leetcode_797_test.hpp deleted file mode 100644 index 76a1c5a1..00000000 --- a/algorithm/graph/leetcode_797_test.hpp +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_797_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_797_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_797 { -using std::vector; - -struct leetcode_797 { - static vector> allPathsSourceTarget(const vector> &graph); - - static vector> allPathsSourceTarget2(const vector> &graph); -}; - -using Catch::Matchers::UnorderedEquals; - -TEST_CASE("basic tests [test_797]", "[test_797]") { - const vector> input{ - {4, 3, 1}, - {3, 2, 4}, - {3}, - {4}, - {} - }; - const vector> result{ - {0, 4}, - {0, 3, 4}, - {0, 1, 3, 4}, - {0, 1, 2, 3, 4}, - {0, 1, 4} - }; - CHECK_THAT(result, UnorderedEquals(leetcode_797::allPathsSourceTarget(input))); - CHECK_THAT(result, UnorderedEquals(leetcode_797::allPathsSourceTarget2(input))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_797_TEST_HPP diff --git a/algorithm/graph/leetcode_so_12.cpp b/algorithm/graph/leetcode_so_12.cpp index c6678226..504410ea 100644 --- a/algorithm/graph/leetcode_so_12.cpp +++ b/algorithm/graph/leetcode_so_12.cpp @@ -1,50 +1,58 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_so_12_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_so_12 { -bool dfs(vector> &board, const string &word, const string &wor, const std::pair loca) { - if (word == wor) { - return true; - } - const auto&[row, line] = loca; - const auto ch = board[row][line]; - const auto this_ch = word[wor.size()]; - board[row][line] = ' '; - bool temp{false}; - temp = temp || (row > 0 && this_ch == board[row - 1][line] && - dfs(board, word, wor + board[row - 1][line], {row - 1, line})) - || (row + 1 < board.size() && this_ch == board[row + 1][line] && - dfs(board, word, wor + board[row + 1][line], {row + 1, line})) - || (line > 0 && this_ch == board[row][line - 1] && - dfs(board, word, wor + board[row][line - 1], {row, line - 1})) - || (line + 1 < board.front().size() && this_ch == board[row][line + 1] && - dfs(board, word, wor + board[row][line + 1], {row, line + 1})); - board[row][line] = ch; - return temp; -} +using std::vector; +using std::string; +#endif -bool leetcode_so_12::exist(const vector> &board, const string &word) { - if (board.empty() || board.front().empty()) { - return word.empty(); - } else if (word.empty()) { - return true; +class Solution { +private: + bool dfs(vector> &board, const string &word, const string &wor, const std::pair loca) { + if (word == wor) { + return true; + } + const auto&[row, line] = loca; + const auto ch = board[row][line]; + const auto this_ch = word[wor.size()]; + board[row][line] = ' '; + bool temp{false}; + temp = temp || (row > 0 && this_ch == board[row - 1][line] && + dfs(board, word, wor + board[row - 1][line], {row - 1, line})) + || (row + 1 < board.size() && this_ch == board[row + 1][line] && + dfs(board, word, wor + board[row + 1][line], {row + 1, line})) + || (line > 0 && this_ch == board[row][line - 1] && + dfs(board, word, wor + board[row][line - 1], {row, line - 1})) + || (line + 1 < board.front().size() && this_ch == board[row][line + 1] && + dfs(board, word, wor + board[row][line + 1], {row, line + 1})); + board[row][line] = ch; + return temp; } - vector> boardMutable{board}; - const auto row{board.size()}, col{board.front().size()}; - for (size_t i{0}; i < row; ++i) { - for (size_t j{0}; j < col; ++j) { - if (board[i][j] == word.front() && dfs(boardMutable, word, string(1, board[i][j]), {i, j})) { - return true; + +public: + bool exist(const vector> &board, const string &word) { + if (board.empty() || board.front().empty()) { + return word.empty(); + } else if (word.empty()) { + return true; + } + vector> boardMutable{board}; + const auto row{board.size()}, col{board.front().size()}; + for (size_t i{0}; i < row; ++i) { + for (size_t j{0}; j < col; ++j) { + if (board[i][j] == word.front() && dfs(boardMutable, word, string(1, board[i][j]), {i, j})) { + return true; + } } } + return false; } - return false; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/graph/leetcode_so_12_test.hpp b/algorithm/graph/leetcode_so_12_test.cpp similarity index 55% rename from algorithm/graph/leetcode_so_12_test.hpp rename to algorithm/graph/leetcode_so_12_test.cpp index 1ac6bb5e..85e016dd 100644 --- a/algorithm/graph/leetcode_so_12_test.hpp +++ b/algorithm/graph/leetcode_so_12_test.cpp @@ -1,37 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DFS //@Tag 深度优先遍历 //@Plan 剑指OfferII-I Day13 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_12_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_12_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_12_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_12_TEST_HPP #include #include #include #include +#include +#include "leetcode_so_12.cpp" namespace leetcode_so_12 { using std::vector; - -struct leetcode_so_12 { - static bool exist(const vector> &board, const string &word); -}; +using std::string; TEST_CASE("basic tests [test_so_12]", "[test_so_12]") { + Solution s; const vector> input{ {'a', 'b', 'c', 'e'}, {'s', 'f', 'c', 's'}, {'a', 'd', 'e', 'e'}, }; static constexpr const char *const word{"abcced"}; - CHECK(leetcode_so_12::exist(input, word)); + CHECK(s.exist(input, word)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_12_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_12_TEST_HPP diff --git a/algorithm/graph/leetcode_so_13.cpp b/algorithm/graph/leetcode_so_13.cpp index 94db56c2..5f9b8b28 100644 --- a/algorithm/graph/leetcode_so_13.cpp +++ b/algorithm/graph/leetcode_so_13.cpp @@ -1,51 +1,55 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_so_13_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include +#include +#include namespace leetcode_so_13 { using std::vector; using std::queue; +#endif -int32_t leetcode_so_13::movingCount(int32_t m, int32_t n, int32_t k) { - vector> visit(m + 2, vector(n + 2, false)); - for (int32_t i{0}; i < n + 2; i++) { - visit[0][i] = true; - visit[m + 1][i] = true; - } - for (int32_t i{0}; i < m + 2; i++) { - visit[i][0] = true; - visit[i][n + 1] = true; - } - visit[1][1] = true; - static constexpr const auto sums = [](auto num) { - int32_t sum{0}; - for (; num != 0; num /= 10) { sum += num % 10; } - return sum; - }; - static constexpr const std::array, 4> path{{{1, 0}, - {-1, 0}, - {0, 1}, - {0, -1}}}; - int32_t nums{0}; - for (queue> que{{{1, 1}}}; !que.empty(); ++nums) { - const auto head = que.front(); - que.pop(); - for (const auto&[row, col]: path) { - const auto x{head.first + row}, y{head.second + col}; - if (!visit[x][y] && - sums(x - 1) + sums(y - 1) <= k) { - que.push({x, y}); - visit[x][y] = true; +class Solution { +public: + int32_t movingCount(int32_t m, int32_t n, int32_t k) { + vector> visit(m + 2, vector(n + 2, false)); + for (int32_t i{0}; i < n + 2; i++) { + visit[0][i] = true; + visit[m + 1][i] = true; + } + for (int32_t i{0}; i < m + 2; i++) { + visit[i][0] = true; + visit[i][n + 1] = true; + } + visit[1][1] = true; + static constexpr const auto sums = [](auto num) { + int32_t sum{0}; + for (; num != 0; num /= 10) { sum += num % 10; } + return sum; + }; + static constexpr const std::array, 4> path{{{1, 0}, + {-1, 0}, + {0, 1}, + {0, -1}}}; + int32_t nums{0}; + for (queue> que{{{1, 1}}}; !que.empty(); ++nums) { + const auto head = que.front(); + que.pop(); + for (const auto&[row, col]: path) { + const auto x{head.first + row}, y{head.second + col}; + if (!visit[x][y] && + sums(x - 1) + sums(y - 1) <= k) { + que.push({x, y}); + visit[x][y] = true; + } } } + return nums; } - return nums; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/graph/leetcode_so_13_test.hpp b/algorithm/graph/leetcode_so_13_test.cpp similarity index 55% rename from algorithm/graph/leetcode_so_13_test.hpp rename to algorithm/graph/leetcode_so_13_test.cpp index 5bf3d6e9..2afa43d9 100644 --- a/algorithm/graph/leetcode_so_13_test.hpp +++ b/algorithm/graph/leetcode_so_13_test.cpp @@ -1,42 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag DFS //@Tag 深度优先遍历 //@Plan 剑指OfferII-I Day13 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_13_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_13_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_13_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_13_TEST_HPP #include #include #include +#include "leetcode_so_13.cpp" namespace leetcode_so_13 { -struct leetcode_so_13 { - static int32_t movingCount(int32_t m, int32_t n, int32_t k); -}; - TEST_CASE("basic tests [test_so_13]", "[test_so_13]") { + Solution s; static constexpr const auto m{2}, n{3}, k{1}; static constexpr const auto result{3}; - CHECK(result == leetcode_so_13::movingCount(m, n, k)); + CHECK(result == s.movingCount(m, n, k)); } TEST_CASE("basic tests 2 [test_so_13]", "[test_so_13]") { + Solution s; static constexpr const auto m{3}, n{1}, k{0}; static constexpr const auto result{1}; - CHECK(result == leetcode_so_13::movingCount(m, n, k)); + CHECK(result == s.movingCount(m, n, k)); } TEST_CASE("basic tests 3 [test_so_13]", "[test_so_13]") { + Solution s; static constexpr const auto m{1}, n{2}, k{1}; static constexpr const auto result{2}; - CHECK(result == leetcode_so_13::movingCount(m, n, k)); + CHECK(result == s.movingCount(m, n, k)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_13_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_LEETCODE_SO_13_TEST_HPP diff --git a/algorithm/graph/toposort.hpp b/algorithm/graph/toposort.hpp index 05de86f1..dce6f39b 100644 --- a/algorithm/graph/toposort.hpp +++ b/algorithm/graph/toposort.hpp @@ -1,13 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_TOPOSORT_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_TOPOSORT_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_TOPOSORT_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_TOPOSORT_HPP #include #include @@ -135,4 +129,4 @@ class graphlist final { } } -#endif // CS203_DSAA_TEMPLATE_ALGORITHM_GRAPH_TOPOSORT_HPP +#endif // ALGORITHM_TEMPLATE_ALGORITHM_GRAPH_TOPOSORT_HPP diff --git a/algorithm/graph/toposort_test.cpp b/algorithm/graph/toposort_test.cpp index 832ff73c..9f218891 100644 --- a/algorithm/graph/toposort_test.cpp +++ b/algorithm/graph/toposort_test.cpp @@ -1,11 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include "toposort.hpp" diff --git a/algorithm/greedy/CMakeLists.txt b/algorithm/greedy/CMakeLists.txt index 60156298..e5a47f66 100644 --- a/algorithm/greedy/CMakeLists.txt +++ b/algorithm/greedy/CMakeLists.txt @@ -9,10 +9,10 @@ set(dependencies 1353) LIST(TRANSFORM dependencies PREPEND leetcode_) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE CS203_DSAA_TEST_MACRO) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) unset(elementName) endforeach () diff --git a/algorithm/greedy/leetcode_1353.cpp b/algorithm/greedy/leetcode_1353.cpp index 9e182608..2819fd55 100644 --- a/algorithm/greedy/leetcode_1353.cpp +++ b/algorithm/greedy/leetcode_1353.cpp @@ -1,43 +1,49 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_1353_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include +#include +#include +#include + +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1353 { using std::priority_queue; +using std::vector; +#endif -int32_t leetcode_1353::maxEvents(const vector> &events) { - int32_t begin{0x3f3f3f3f}, end{0}; - for (const auto &event: events) { - begin = std::min(begin, event[0]); - end = std::max(end, event[1]); - } - vector> dayToEvents{static_cast(end + 1)}; - for (const auto &event: events) { - dayToEvents[event[0]].push_back(event[1]); - } - priority_queue, std::greater<>> priorityQueue{}; - int32_t joined{0}; - for (int32_t order{begin}; order <= end; order++) { - for (const auto lastDay: dayToEvents[order]) { - priorityQueue.push(lastDay); +class Solution { +public: + int32_t maxEvents(const vector> &events) { + int32_t begin{0x3f3f3f3f}, end{0}; + for (const auto &event: events) { + begin = std::min(begin, event[0]); + end = std::max(end, event[1]); + } + vector> dayToEvents{static_cast(end + 1)}; + for (const auto &event: events) { + dayToEvents[event[0]].push_back(event[1]); } - for (; !priorityQueue.empty();) { - const auto head = priorityQueue.top(); - if (head >= order) { + priority_queue, std::greater<>> priorityQueue{}; + int32_t joined{0}; + for (int32_t order{begin}; order <= end; order++) { + for (const auto lastDay: dayToEvents[order]) { + priorityQueue.push(lastDay); + } + for (; !priorityQueue.empty();) { + const auto head = priorityQueue.top(); + if (head >= order) { + priorityQueue.pop(); + joined += 1; + break; + } priorityQueue.pop(); - joined += 1; - break; } - priorityQueue.pop(); } + return joined; } - return joined; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/greedy/leetcode_1353_test.hpp b/algorithm/greedy/leetcode_1353_test.cpp similarity index 71% rename from algorithm/greedy/leetcode_1353_test.hpp rename to algorithm/greedy/leetcode_1353_test.cpp index 8044bfd9..5771f8ee 100644 --- a/algorithm/greedy/leetcode_1353_test.hpp +++ b/algorithm/greedy/leetcode_1353_test.cpp @@ -1,30 +1,23 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag 贪心算法 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1353_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1353_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1353_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1353_TEST_HPP #include #include #include +#include "leetcode_1353.cpp" namespace leetcode_1353 { -namespace leetcode_1353 { -int32_t maxEvents(const vector> &events); -} - TEST_CASE("test case 1 [test_1353]", "[test_1353]") { const vector> input{{1, 2}, {2, 3}, {3, 4}}; constexpr const auto result{3}; - CHECK(result == leetcode_1353::maxEvents(input)); + Solution solution; + CHECK(result == solution.maxEvents(input)); } TEST_CASE("test case 2 [test_1353]", "[test_1353]") { @@ -33,7 +26,8 @@ TEST_CASE("test case 2 [test_1353]", "[test_1353]") { {2, 3}, {3, 4}}; constexpr const auto result{4}; - CHECK(result == leetcode_1353::maxEvents(input)); + Solution solution; + CHECK(result == solution.maxEvents(input)); } TEST_CASE("test case 3 [test_1353]", "[test_1353]") { @@ -43,7 +37,8 @@ TEST_CASE("test case 3 [test_1353]", "[test_1353]") { {1, 5}, {1, 5}}; constexpr const auto result{5}; - CHECK(result == leetcode_1353::maxEvents(input)); + Solution solution; + CHECK(result == solution.maxEvents(input)); } TEST_CASE("test case 4 [test_1353]", "[test_1353]") { @@ -54,7 +49,8 @@ TEST_CASE("test case 4 [test_1353]", "[test_1353]") { {1, 9}, {8, 10}}; constexpr const auto result{6}; - CHECK(result == leetcode_1353::maxEvents(input)); + Solution solution; + CHECK(result == solution.maxEvents(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1353_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1353_TEST_HPP diff --git a/algorithm/list/CMakeLists.txt b/algorithm/list/CMakeLists.txt index d612a118..a6277c69 100644 --- a/algorithm/list/CMakeLists.txt +++ b/algorithm/list/CMakeLists.txt @@ -13,10 +13,10 @@ LIST(APPEND dependencies 160 876 1409) LIST(TRANSFORM dependencies PREPEND leetcode_) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE CS203_DSAA_TEST_MACRO) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) unset(elementName) endforeach () diff --git a/algorithm/list/leetcode_109.cpp b/algorithm/list/leetcode_109.cpp index 0db6c9fd..0affabcb 100644 --- a/algorithm/list/leetcode_109.cpp +++ b/algorithm/list/leetcode_109.cpp @@ -1,36 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_109_test.hpp" +#include +#include +#include namespace leetcode_109 { +using LISTNODE::ListNode; +using TreeNode = TREE_NODE::TreeNode; +#endif - -TreeNode *leetcode_109::sortedListToBST(ListNode *head) { - if (head == nullptr) { - return nullptr; - } else if (head->next == nullptr) { - return new TreeNode(head->val); - } - ListNode *one{head}, *two{head}, *prev{nullptr}; - while (two->next != nullptr) { - prev = one; - one = one->next; - two = two->next; - if (two->next != nullptr) { +class Solution { +public: + TreeNode *sortedListToBST(ListNode *head) { + if (head == nullptr) { + return nullptr; + } else if (head->next == nullptr) { + return new TreeNode(head->val); + } + ListNode *one{head}, *two{head}, *prev{nullptr}; + while (two->next != nullptr) { + prev = one; + one = one->next; two = two->next; + if (two->next != nullptr) { + two = two->next; + } } + auto *const mid = new TreeNode(one->val); + prev->next = nullptr; + mid->left = sortedListToBST(head); + mid->right = sortedListToBST(one->next); + return mid; } - auto *const mid = new TreeNode(one->val); - prev->next = nullptr; - mid->left = sortedListToBST(head); - mid->right = sortedListToBST(one->next); - return mid; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_109_test.hpp b/algorithm/list/leetcode_109_test.cpp similarity index 53% rename from algorithm/list/leetcode_109_test.hpp rename to algorithm/list/leetcode_109_test.cpp index 030e2e44..66d7c4bc 100644 --- a/algorithm/list/leetcode_109_test.hpp +++ b/algorithm/list/leetcode_109_test.cpp @@ -1,30 +1,15 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 //@Tag 二叉树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_109_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_109_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_109_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_109_TEST_HPP #include -#include -#include -#include -#include -#include +#include "leetcode_109.cpp" namespace leetcode_109 { -using LISTNODE::ListNode; -using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_109 { - static TreeNode *sortedListToBST(ListNode *head); -}; using LISTNODE::ListNodeLink; using TreeNodeLink = TREE_NODE::TreeNodeLink; @@ -35,9 +20,11 @@ TEST_CASE("-1 [test _109]", "[test _109]") { -3, 9, -10, TreeNode::No, 5, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No}; - const TreeNode *const result = leetcode_109::sortedListToBST(vec1[0]); + Solution solution; + const TreeNode *const result = solution.sortedListToBST(vec1[0]); const TreeNodeLink link{const_cast(result)}; CHECK(TREE_NODE::judge_equal(const_cast(result), output)); } + } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_109_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_109_TEST_HPP diff --git a/algorithm/list/leetcode_1409.cpp b/algorithm/list/leetcode_1409.cpp index 3e3510c7..e8d70fb6 100644 --- a/algorithm/list/leetcode_1409.cpp +++ b/algorithm/list/leetcode_1409.cpp @@ -1,14 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_1409_test.hpp" +#include +#include +#include +#include namespace leetcode_1409 { +using std::vector; +using std::unordered_map; +#endif struct ListNode1409 final { ListNode1409 *pre{}, *next{}; @@ -18,47 +21,52 @@ struct ListNode1409 final { ListNode1409(int32_t v, ListNode1409 *pre, ListNode1409 *n) : pre(pre), next(n), val(v) {} }; -vector leetcode_1409::processQueries(const vector &queries, int32_t m) { - ListNode1409 head{0, nullptr, nullptr}; - ListNode1409 *head_pointer{&head}; - vector todelete{}; - for (int32_t i{0}; i < m; ++i) { - head_pointer->next = new ListNode1409(i + 1, head_pointer, nullptr); - head_pointer->next->position = i; - head_pointer = head_pointer->next; - todelete.push_back(head_pointer); - } - head_pointer = head.next; - head_pointer->pre = nullptr; - std::unordered_map loca{}; - for (int32_t i{0}; i < m; ++i) { - loca[i + 1] = todelete[i]; - } - vector will_return{}; - for (const auto query: queries) { - const auto node = loca[query]; - will_return.push_back(node->position); - const auto pre = node->pre; - if (pre == nullptr) { // 前无古人, 不需要操作 - continue; +class Solution { +public: + vector processQueries(const vector &queries, int32_t m) { + ListNode1409 head{0, nullptr, nullptr}; + ListNode1409 *head_pointer{&head}; + vector todelete{}; + for (int32_t i{0}; i < m; ++i) { + head_pointer->next = new ListNode1409(i + 1, head_pointer, nullptr); + head_pointer->next->position = i; + head_pointer = head_pointer->next; + todelete.push_back(head_pointer); } - for (auto begin{head_pointer}; begin != node; begin = begin->next) { - begin->position++; + head_pointer = head.next; + head_pointer->pre = nullptr; + std::unordered_map loca{}; + for (int32_t i{0}; i < m; ++i) { + loca[i + 1] = todelete[i]; } - node->position = 0; - pre->next = node->next; - if (pre->next != nullptr) { - pre->next->pre = pre; + vector will_return{}; + for (const auto query: queries) { + const auto node = loca[query]; + will_return.push_back(node->position); + const auto pre = node->pre; + if (pre == nullptr) { // 前无古人, 不需要操作 + continue; + } + for (auto begin{head_pointer}; begin != node; begin = begin->next) { + begin->position++; + } + node->position = 0; + pre->next = node->next; + if (pre->next != nullptr) { + pre->next->pre = pre; + } + node->pre = nullptr; + node->next = head_pointer; + head_pointer->pre = node; + head_pointer = node; } - node->pre = nullptr; - node->next = head_pointer; - head_pointer->pre = node; - head_pointer = node; - } - for (auto &pointer: todelete) { - delete pointer; + for (auto &pointer: todelete) { + delete pointer; + } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_1409_test.hpp b/algorithm/list/leetcode_1409_test.cpp similarity index 55% rename from algorithm/list/leetcode_1409_test.hpp rename to algorithm/list/leetcode_1409_test.cpp index 2f506fae..e4e1d5fb 100644 --- a/algorithm/list/leetcode_1409_test.hpp +++ b/algorithm/list/leetcode_1409_test.cpp @@ -1,32 +1,26 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 //@Description 链表中点,经典双指针 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1409_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1409_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1409_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1409_TEST_HPP #include -namespace leetcode_1409 { +#include "leetcode_1409.cpp" namespace leetcode_1409 { -vector processQueries(const vector &queries, int32_t m); -} using Catch::Matchers::Equals; TEST_CASE("test case 1 [test_1409]", "[test_1409]") { const vector vec1{3, 1, 2, 1}; constexpr const auto m{5}; const vector result{2, 1, 2, 1}; - CHECK_THAT(result, Equals(leetcode_1409::processQueries(vec1, m))); + Solution solution; + CHECK_THAT(result, Equals(solution.processQueries(vec1, m))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1409_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1409_TEST_HPP diff --git a/algorithm/list/leetcode_141.cpp b/algorithm/list/leetcode_141.cpp index a38f2f70..f96dbfe9 100644 --- a/algorithm/list/leetcode_141.cpp +++ b/algorithm/list/leetcode_141.cpp @@ -1,42 +1,50 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_141_test.hpp" +#include +#include #include -// 无需畏惧死循环, while这个肯定能打破 +#include namespace leetcode_141 { using std::unordered_set; +using LISTNODE::ListNode; + +#endif + +// 无需畏惧死循环, while这个肯定能打破 -bool leetcode_141::hasCycle(ListNode *head) { - for (unordered_set nodes{}; head != nullptr;) { - if (nodes.count(head) != 0) { - return true; +class Solution { +public: + bool hasCycle(ListNode *head) { + for (unordered_set nodes{}; head != nullptr;) { + if (nodes.count(head) != 0) { + return true; + } + nodes.insert(head); + head = head->next; } - nodes.insert(head); - head = head->next; + return false; } - return false; -} -bool leetcode_141::hasCycle2(ListNode *head) { - for (ListNode *quick{head}, *slow{head}; quick != nullptr && slow != nullptr;) { - slow = slow->next; - quick = quick->next; - if (quick == nullptr) { - return false; - } - quick = quick->next; - if (slow == quick && slow != nullptr) { - return true; + bool hasCycle2(ListNode *head) { + for (ListNode *quick{head}, *slow{head}; quick != nullptr && slow != nullptr;) { + slow = slow->next; + quick = quick->next; + if (quick == nullptr) { + return false; + } + quick = quick->next; + if (slow == quick && slow != nullptr) { + return true; + } } + return false; } - return false; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_141_test.cpp b/algorithm/list/leetcode_141_test.cpp new file mode 100644 index 00000000..2022ede3 --- /dev/null +++ b/algorithm/list/leetcode_141_test.cpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag list +//@Tag 链表 +//@Tag +//@Description 利用地址不重复 +//@Plan 数据结构入门 Day7 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_141_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_141_TEST_HPP + + +#include +#include +#include +#include "leetcode_141.cpp" + +namespace leetcode_141 { +using LISTNODE::ListNode; +using LISTNODE::ListNodeLink; + +TEST_CASE("fst [test_141]", "[test_141]") { + const ListNodeLink link{3, 2, 0, -4}; + link[3]->next = link[1]; + auto clas = Solution(); + CHECK(clas.hasCycle(link[0])); + CHECK(clas.hasCycle2(link[0])); +} + +TEST_CASE("2nd [test_141]", "[test_141]") { + const ListNodeLink link{1, 2}; + link[1]->next = link[0]; + auto clas = Solution(); + CHECK(clas.hasCycle(link[0])); + CHECK(clas.hasCycle2(link[0])); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_141_TEST_HPP diff --git a/algorithm/list/leetcode_141_test.hpp b/algorithm/list/leetcode_141_test.hpp deleted file mode 100644 index 489c9106..00000000 --- a/algorithm/list/leetcode_141_test.hpp +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 -//@Tag -//@Description 利用地址不重复 -//@Plan 数据结构入门 Day7 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_141_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_141_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_141 { -using LISTNODE::ListNode; - -struct leetcode_141 { - static bool hasCycle(ListNode *head); - - static bool hasCycle2(ListNode *head); -}; - -using LISTNODE::ListNodeLink; - -TEST_CASE("fst [test_141]", "[test_141]") { - const ListNodeLink link{3, 2, 0, -4}; - link[3]->next = link[1]; - CHECK(leetcode_141::hasCycle(link[0])); - CHECK(leetcode_141::hasCycle2(link[0])); -} - -TEST_CASE("2nd [test_141]", "[test_141]") { - const ListNodeLink link{1, 2}; - link[1]->next = link[0]; - CHECK(leetcode_141::hasCycle(link[0])); - CHECK(leetcode_141::hasCycle2(link[0])); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_141_TEST_HPP diff --git a/algorithm/list/leetcode_146.cpp b/algorithm/list/leetcode_146.cpp index 3b41416a..5ae8587a 100644 --- a/algorithm/list/leetcode_146.cpp +++ b/algorithm/list/leetcode_146.cpp @@ -1,14 +1,34 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_146_test.hpp" +#include +#include +#include +#include +#include #include + namespace leetcode_146 { +using std::unordered_map; +using std::unique_ptr; + +#endif + +class LRUCache { +protected: + const size_t size; +public: + explicit LRUCache(int32_t capacity) : size(capacity) {} + + virtual int32_t get(int32_t key) = 0; + + virtual void put(int32_t key, int32_t value) = 0; + + virtual ~LRUCache() = default; +}; + class LRU final : public LRUCache, protected nonCopyMoveAble { private: struct Node final : private nonCopyMoveAble { @@ -79,14 +99,20 @@ class LRU final : public LRUCache, protected nonCopyMoveAble { } ~LRU() override { - for (const auto&[k, v]: umap) { + for (const auto &[k, v]: umap) { delete v; } } }; -std::unique_ptr leetcode_146::get(int32_t cap) { - return std::make_unique(cap); -} +class Solution { +public: + std::unique_ptr get(int32_t cap) { + return std::make_unique(cap); + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_146_test.cpp b/algorithm/list/leetcode_146_test.cpp new file mode 100644 index 00000000..f7c83fd1 --- /dev/null +++ b/algorithm/list/leetcode_146_test.cpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag list +//@Tag 链表 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_146_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_146_TEST_HPP + +#include +#include "leetcode_146.cpp" + +namespace leetcode_146 { + +TEST_CASE("fst [test_146]", "[test_146]") { + Solution solution; + const auto ptr = solution.get(2); + ptr->put(1, 1); + ptr->put(2, 2); + CHECK(1 == ptr->get(1)); + ptr->put(3, 3); + CHECK(-1 == ptr->get(2)); + ptr->put(4, 4); + CHECK(-1 == ptr->get(1)); + CHECK(3 == ptr->get(3)); + CHECK(4 == ptr->get(4)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_146_TEST_HPP diff --git a/algorithm/list/leetcode_146_test.hpp b/algorithm/list/leetcode_146_test.hpp deleted file mode 100644 index 8f6db712..00000000 --- a/algorithm/list/leetcode_146_test.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_146_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_146_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_146 { - -class LRUCache { -protected: - const size_t size; -public: - explicit LRUCache(int32_t capacity) : size(capacity) {} - - virtual int32_t get(int32_t key) = 0; - - virtual void put(int32_t key, int32_t value) = 0; - - virtual ~LRUCache() = default; -}; - - -struct leetcode_146 { - static std::unique_ptr get(int32_t cap); -}; - -TEST_CASE("fst [test_146]", "[test_146]") { - const auto ptr = leetcode_146::get(2); - ptr->put(1, 1); - ptr->put(2, 2); - CHECK(1 == ptr->get(1)); - ptr->put(3, 3); - CHECK(-1 == ptr->get(2)); - ptr->put(4, 4); - CHECK(-1 == ptr->get(1)); - CHECK(3 == ptr->get(3)); - CHECK(4 == ptr->get(4)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_146_TEST_HPP diff --git a/algorithm/list/leetcode_160.cpp b/algorithm/list/leetcode_160.cpp index 338ca882..68b37236 100644 --- a/algorithm/list/leetcode_160.cpp +++ b/algorithm/list/leetcode_160.cpp @@ -1,31 +1,36 @@ -/* -AGPL-3.0-or-later License +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -CS160_DSAA_template +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_160_test.hpp" +#include namespace leetcode_160 { +using LISTNODE::ListNode; -ListNode *leetcode_160::getIntersectionNode(ListNode *headA, ListNode *headB) { - size_t aSize{0}, bSize{0}; - for (ListNode *temp{headA}; temp != nullptr; temp = temp->next, ++aSize) {} - for (ListNode *temp{headB}; temp != nullptr; temp = temp->next, ++bSize) {} - if (aSize > bSize) { - for (size_t i{bSize}; i < aSize; ++i, headA = headA->next) {} - } else if (aSize < bSize) { - for (size_t i{aSize}; i < bSize; ++i, headB = headB->next) {} - } - ListNode aObj{-1, headA}, bObj{-1, headB}; - for (headA = &aObj,headB = &bObj; headA != nullptr; headA = headA->next, headB = headB->next) { - if (headA->next == headB->next) { - return headA->next; +#endif + +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + size_t aSize{0}, bSize{0}; + for (ListNode *temp{headA}; temp != nullptr; temp = temp->next, ++aSize) {} + for (ListNode *temp{headB}; temp != nullptr; temp = temp->next, ++bSize) {} + if (aSize > bSize) { + for (size_t i{bSize}; i < aSize; ++i, headA = headA->next) {} + } else if (aSize < bSize) { + for (size_t i{aSize}; i < bSize; ++i, headB = headB->next) {} } + ListNode aObj{-1, headA}, bObj{-1, headB}; + for (headA = &aObj, headB = &bObj; headA != nullptr; headA = headA->next, headB = headB->next) { + if (headA->next == headB->next) { + return headA->next; + } + } + return nullptr; } - return nullptr; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_160_test.hpp b/algorithm/list/leetcode_160_test.cpp similarity index 62% rename from algorithm/list/leetcode_160_test.hpp rename to algorithm/list/leetcode_160_test.cpp index 2e5af6d0..ac110224 100644 --- a/algorithm/list/leetcode_160_test.hpp +++ b/algorithm/list/leetcode_160_test.cpp @@ -1,11 +1,5 @@ -/* -AGPL-3.0-or-later License - -CS160_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 //@Plan 剑指OfferII-I Day12 @@ -13,16 +7,9 @@ Copyright (C) 2020-2023 nanoseeds #define CS160_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_160_TEST_HPP #include -#include -#include -#include +#include "leetcode_160.cpp" namespace leetcode_160 { -using LISTNODE::ListNode; - -struct leetcode_160 final : private nonCopyMoveAble { - static ListNode *getIntersectionNode(ListNode *headA, ListNode *headB); -}; using LISTNODE::ListNodeLink; @@ -33,13 +20,16 @@ TEST_CASE("test case 1 [test_160]", "[test_160]") { vec1[1]->next = vecCommon[0]; vec2[2]->next = vecCommon[0]; const vector output{8, 4, 5}; - const ListNode *const result = leetcode_160::getIntersectionNode(vec1[0], vec2[0]); + Solution solution; + const ListNode *const result = solution.getIntersectionNode(vec1[0], vec2[0]); CHECK(ListNode::equal(output, result)); } + TEST_CASE("test case 2 [test_160]", "[test_160]") { const ListNodeLink vecCommon{1}; const vector output{1}; - const ListNode *const result = leetcode_160::getIntersectionNode(vecCommon[0], vecCommon[0]); + Solution solution; + const ListNode *const result = solution.getIntersectionNode(vecCommon[0], vecCommon[0]); CHECK(ListNode::equal(output, result)); } } diff --git a/algorithm/list/leetcode_19.cpp b/algorithm/list/leetcode_19.cpp index da68bc5f..99cdfef0 100644 --- a/algorithm/list/leetcode_19.cpp +++ b/algorithm/list/leetcode_19.cpp @@ -1,60 +1,67 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_19_test.hpp" +#include +#include namespace leetcode_19 { -ListNode *leetcode_19::removeNthFromEnd(ListNode *head, int32_t n) { - // auto *will_return = new ListNode(0); - ListNode will_return_o{0, head}; - auto *const will_return = &will_return_o; - ListNode *first = will_return; - ListNode *second = will_return; - if (n == 0) { - second = second->next; - while (second->next != nullptr) { +using LISTNODE::ListNode; + +#endif + +class Solution { +public: + ListNode *removeNthFromEnd(ListNode *head, int32_t n) { + // auto *will_return = new ListNode(0); + ListNode will_return_o{0, head}; + auto *const will_return = &will_return_o; + ListNode *first = will_return; + ListNode *second = will_return; + if (n == 0) { + second = second->next; + while (second->next != nullptr) { + first = first->next; + second = second->next; + } + first->next = nullptr; + return head; + } + for (int32_t i{0}; i <= n; i++) { + second = second->next; + } + while (second != nullptr) { first = first->next; second = second->next; } - first->next = nullptr; - return head; - } - for (int32_t i{0}; i <= n; i++) { - second = second->next; - } - while (second != nullptr) { - first = first->next; - second = second->next; - } - if (first == nullptr || first->next == nullptr) { - return head; + if (first == nullptr || first->next == nullptr) { + return head; + } + first->next = (first->next)->next; + return will_return->next; } - first->next = (first->next)->next; - return will_return->next; -} -ListNode *leetcode_19::removeNthFromEnd2(ListNode *head, int32_t n) { - // auto *will_return = new ListNode(0); - ListNode will_return_o{0, head}; - auto *const will_return = &will_return_o; - ListNode *first = will_return; - ListNode *second = will_return; - for (int32_t i{0}; i <= n; i++) { - second = second->next; - } - while (second != nullptr) { - first = first->next; - second = second->next; - } - if (first == nullptr || first->next == nullptr) { - return head; + ListNode *removeNthFromEnd2(ListNode *head, int32_t n) { + // auto *will_return = new ListNode(0); + ListNode will_return_o{0, head}; + auto *const will_return = &will_return_o; + ListNode *first = will_return; + ListNode *second = will_return; + for (int32_t i{0}; i <= n; i++) { + second = second->next; + } + while (second != nullptr) { + first = first->next; + second = second->next; + } + if (first == nullptr || first->next == nullptr) { + return head; + } + first->next = (first->next)->next; + return will_return->next; } - first->next = (first->next)->next; - return will_return->next; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_19_test.hpp b/algorithm/list/leetcode_19_test.cpp similarity index 54% rename from algorithm/list/leetcode_19_test.hpp rename to algorithm/list/leetcode_19_test.cpp index 57642c98..913f1b94 100644 --- a/algorithm/list/leetcode_19_test.hpp +++ b/algorithm/list/leetcode_19_test.cpp @@ -1,67 +1,60 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_19_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_19_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_19_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_19_TEST_HPP #include -#include #include -#include +#include "leetcode_19.cpp" namespace leetcode_19 { using LISTNODE::ListNode; - -struct leetcode_19 { - static ListNode *removeNthFromEnd(ListNode *head, int32_t n); - - static ListNode *removeNthFromEnd2(ListNode *head, int32_t n); -}; - using LISTNODE::ListNodeLink; TEST_CASE("test case 1 [test_19]", "[test_19]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const auto *const result = leetcode_19::removeNthFromEnd(vec1[0], 2); + auto clas = Solution(); + const auto *const result = clas.removeNthFromEnd(vec1[0], 2); CHECK(ListNode::equal({1, 2, 3, 5}, result)); } TEST_CASE("test case 2 [test_19]", "[test_19]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const auto *const result = leetcode_19::removeNthFromEnd(vec1[0], 1); + auto clas = Solution(); + const auto *const result = clas.removeNthFromEnd(vec1[0], 1); CHECK(ListNode::equal({1, 2, 3, 4}, result)); } TEST_CASE("test case 3 [test_19]", "[test_19]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const auto *const result = leetcode_19::removeNthFromEnd(vec1[0], 5); + auto clas = Solution(); + const auto *const result = clas.removeNthFromEnd(vec1[0], 5); CHECK(ListNode::equal({2, 3, 4, 5}, result)); } TEST_CASE("test case 2-1 [test_19]", "[test_19]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const auto *const result = leetcode_19::removeNthFromEnd2(vec1[0], 2); + auto clas = Solution(); + const auto *const result = clas.removeNthFromEnd2(vec1[0], 2); CHECK(ListNode::equal({1, 2, 3, 5}, result)); } TEST_CASE("test case 2-2 [test_19]", "[test_19]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const auto *const result = leetcode_19::removeNthFromEnd2(vec1[0], 1); + auto clas = Solution(); + const auto *const result = clas.removeNthFromEnd2(vec1[0], 1); CHECK(ListNode::equal({1, 2, 3, 4}, result)); } TEST_CASE("test case 2-3 [test_19]", "[test_19]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const auto *const result = leetcode_19::removeNthFromEnd2(vec1[0], 5); + auto clas = Solution(); + const auto *const result = clas.removeNthFromEnd2(vec1[0], 5); CHECK(ListNode::equal({2, 3, 4, 5}, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_19_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_19_TEST_HPP diff --git a/algorithm/list/leetcode_2.cpp b/algorithm/list/leetcode_2.cpp index 6ecdb475..b2f3ed63 100644 --- a/algorithm/list/leetcode_2.cpp +++ b/algorithm/list/leetcode_2.cpp @@ -1,54 +1,61 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_2_test.hpp" +#include +#include namespace leetcode_2 { -int32_t get_depth(ListNode *node) { - if (node == nullptr) { - return 0; - } - int32_t will_return = 0; - while (node != nullptr) { - will_return++; - node = node->next; - } - return will_return; -} +using LISTNODE::ListNode; -ListNode *leetcode_2::addTwoNumbers(ListNode *l1_in, ListNode *l2_in) { - ListNode *l1 = l1_in; - ListNode *l2 = l2_in; - if (get_depth(l2) > get_depth(l1)) { - std::swap(l1, l2); - } - ListNode will_return{0}; - ListNode *head = &will_return; - int32_t add_in = 0; - while (l1 != nullptr && l2 != nullptr) { - int32_t sum = (l1->val + l2->val + add_in); - head->next = new ListNode(sum % 10); - add_in = sum / 10; - l1 = l1->next; - l2 = l2->next; - head = head->next; - } - while (l1 != nullptr) { - int32_t sum = (l1->val + add_in); - head->next = new ListNode{sum % 10}; - add_in = sum / 10; - l1 = l1->next; - head = head->next; - } - if (add_in != 0) { - head->next = new ListNode{add_in}; +#endif + +class Solution { +private: + int32_t get_depth(ListNode *node) { + if (node == nullptr) { + return 0; + } + int32_t will_return = 0; + while (node != nullptr) { + will_return++; + node = node->next; + } + return will_return; } - return will_return.next; -} +public: + ListNode *addTwoNumbers(ListNode *l1_in, ListNode *l2_in) { + ListNode *l1 = l1_in; + ListNode *l2 = l2_in; + if (get_depth(l2) > get_depth(l1)) { + std::swap(l1, l2); + } + ListNode will_return{0}; + ListNode *head = &will_return; + int32_t add_in = 0; + while (l1 != nullptr && l2 != nullptr) { + int32_t sum = (l1->val + l2->val + add_in); + head->next = new ListNode(sum % 10); + add_in = sum / 10; + l1 = l1->next; + l2 = l2->next; + head = head->next; + } + while (l1 != nullptr) { + int32_t sum = (l1->val + add_in); + head->next = new ListNode{sum % 10}; + add_in = sum / 10; + l1 = l1->next; + head = head->next; + } + if (add_in != 0) { + head->next = new ListNode{add_in}; + } + return will_return.next; + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_203.cpp b/algorithm/list/leetcode_203.cpp index 2b7153a0..a2adc9b7 100644 --- a/algorithm/list/leetcode_203.cpp +++ b/algorithm/list/leetcode_203.cpp @@ -1,34 +1,39 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_203_test.hpp" +#include namespace leetcode_203 { +using LISTNODE::ListNode; + +#endif -ListNode *leetcode_203::removeElements(ListNode *head, int32_t val) { - ListNode fst{0}; - for (ListNode *base{head}; base != nullptr; base = base->next) { - if (base->val != val) { - fst.next = base; - break; +class Solution { +public: + ListNode *removeElements(ListNode *head, int32_t val) { + ListNode fst{0}; + for (ListNode *base{head}; base != nullptr; base = base->next) { + if (base->val != val) { + fst.next = base; + break; + } } - } - if (fst.next == nullptr) { - return nullptr; - } - for (ListNode *base{fst.next}; base->next != nullptr;) { - ListNode *nnext{base->next}; - if (nnext->val == val) { - base->next = nnext->next; - } else { - base = base->next; + if (fst.next == nullptr) { + return nullptr; + } + for (ListNode *base{fst.next}; base->next != nullptr;) { + ListNode *nnext{base->next}; + if (nnext->val == val) { + base->next = nnext->next; + } else { + base = base->next; + } } + return fst.next; // should not reach there } - return fst.next; // should not reach there -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_203_test.hpp b/algorithm/list/leetcode_203_test.cpp similarity index 59% rename from algorithm/list/leetcode_203_test.hpp rename to algorithm/list/leetcode_203_test.cpp index 2a147334..87cefba7 100644 --- a/algorithm/list/leetcode_203_test.hpp +++ b/algorithm/list/leetcode_203_test.cpp @@ -1,34 +1,29 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 //@Plan 数据结构入门 Day7 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_203_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_203_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_203_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_203_TEST_HPP + #include #include #include -#include +#include +#include "leetcode_203.cpp" namespace leetcode_203 { using LISTNODE::ListNode; - -struct leetcode_203 final : private nonCopyMoveAble { - static ListNode *removeElements(ListNode *head, int32_t val); -}; +using std::vector; TEST_CASE("test case 1 [test_203]", "[test_203]") { const LISTNODE::ListNodeLink vec1{1, 2, 6, 3, 4, 5, 6}; static constexpr const auto remove{6}; const vector output{1, 2, 3, 4, 5}; - const ListNode *const result = leetcode_203::removeElements(vec1[0], remove); + auto clas = Solution(); + const ListNode *const result = clas.removeElements(vec1[0], remove); CHECK(ListNode::equal(output, result)); } @@ -36,23 +31,26 @@ TEST_CASE("test case 2 [test_203]", "[test_203]") { const LISTNODE::ListNodeLink vec1{6, 6, 6, 5, 6, 9, 3, 4, 5, 6}; static constexpr const auto remove{6}; const vector output{5, 9, 3, 4, 5}; - const ListNode *const result = leetcode_203::removeElements(vec1[0], remove); + auto clas = Solution(); + const ListNode *const result = clas.removeElements(vec1[0], remove); CHECK(ListNode::equal(output, result)); } TEST_CASE("test case 3 [test_203]", "[test_203]") { const LISTNODE::ListNodeLink vec1{6, 6, 6, 6, 6}; static constexpr const auto remove{6}; - const ListNode *const result = leetcode_203::removeElements(vec1[0], remove); + auto clas = Solution(); + const ListNode *const result = clas.removeElements(vec1[0], remove); CHECK(nullptr == result); } TEST_CASE("test case 4 [test_203]", "[test_203]") { const LISTNODE::ListNodeLink vec1{}; static constexpr const auto remove{114514}; - const ListNode *const result = leetcode_203::removeElements(vec1[0], remove); + auto clas = Solution(); + const ListNode *const result = clas.removeElements(vec1[0], remove); CHECK(nullptr == result); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_203_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_203_TEST_HPP diff --git a/algorithm/list/leetcode_206.cpp b/algorithm/list/leetcode_206.cpp index 7c5f0eb7..b487c669 100644 --- a/algorithm/list/leetcode_206.cpp +++ b/algorithm/list/leetcode_206.cpp @@ -1,53 +1,59 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_206_test.hpp" +#include namespace leetcode_206 { +using LISTNODE::ListNode; -/** - * 第一版 - * */ -ListNode *leetcode_206::reverseList2(ListNode *head) { - if (head == nullptr || head->next == nullptr) { - return head; - } - ListNode *ll = head; - ListNode *rl = head->next; - ListNode *rr = rl->next; - while (rr != nullptr) { - head->next = rr; - rl->next = ll; - ll = rl; - rl = rr; - rr = rr->next; - } - head->next = nullptr; - rl->next = ll; - ll = rl; - return ll; -} +#endif -/** - * 化简版 - * */ -ListNode *leetcode_206::reverseList(ListNode *head) { - if (head == nullptr || head->next == nullptr) { - return head; - } - ListNode *ll = head; - ListNode *rl = head->next; - while (rl != nullptr) { +class Solution { +public: + /** + * 第一版 + * */ + ListNode *reverseList2(ListNode *head) { + if (head == nullptr || head->next == nullptr) { + return head; + } + ListNode *ll = head; + ListNode *rl = head->next; ListNode *rr = rl->next; - head->next = rr; + while (rr != nullptr) { + head->next = rr; + rl->next = ll; + ll = rl; + rl = rr; + rr = rr->next; + } + head->next = nullptr; rl->next = ll; ll = rl; - rl = rr; + return ll; } - return ll; -} + + /** + * 化简版 + * */ + ListNode *reverseList(ListNode *head) { + if (head == nullptr || head->next == nullptr) { + return head; + } + ListNode *ll = head; + ListNode *rl = head->next; + while (rl != nullptr) { + ListNode *rr = rl->next; + head->next = rr; + rl->next = ll; + ll = rl; + rl = rr; + } + return ll; + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_206_test.hpp b/algorithm/list/leetcode_206_test.cpp similarity index 52% rename from algorithm/list/leetcode_206_test.hpp rename to algorithm/list/leetcode_206_test.cpp index 26f29913..90a2268b 100644 --- a/algorithm/list/leetcode_206_test.hpp +++ b/algorithm/list/leetcode_206_test.cpp @@ -1,46 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 //@Description 反转链表 //@Plan 数据结构入门 Day8 //@Plan 剑指OfferII-I Day02 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_206_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_206_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_206_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_206_TEST_HPP #include -#include +#include "leetcode_206.cpp" namespace leetcode_206 { -using LISTNODE::ListNode; - -struct leetcode_206 final : private nonCopyMoveAble { - static ListNode *reverseList(ListNode *head); - - static ListNode *reverseList2(ListNode *head); -}; TEST_CASE("test case 1 [test_206]", "[test_206]") { const LISTNODE::ListNodeLink vec1{1, 2, 3, 4, 5}; - const auto result = leetcode_206::reverseList(vec1[0]); + Solution solution; + const auto result = solution.reverseList(vec1[0]); CHECK(ListNode::equal({5, 4, 3, 2, 1}, result)); } TEST_CASE("test case 2 [test_206]", "[test_206]") { const LISTNODE::ListNodeLink vec1{1, 1, 4, 5, 1, 4}; - const auto result = leetcode_206::reverseList(vec1[0]); + Solution solution; + const auto result = solution.reverseList(vec1[0]); CHECK(ListNode::equal({4, 1, 5, 4, 1, 1}, result)); } TEST_CASE("test case 3 [test_206]", "[test_206]") { const LISTNODE::ListNodeLink vec1{1, 9, 1, 9, 8, 1, 0}; - const auto result = leetcode_206::reverseList(vec1[0]); + Solution solution; + const auto result = solution.reverseList(vec1[0]); CHECK(ListNode::equal({0, 1, 8, 9, 1, 9, 1}, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_206_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_206_TEST_HPP diff --git a/algorithm/list/leetcode_21.cpp b/algorithm/list/leetcode_21.cpp index 9a6af80e..2dd87adf 100644 --- a/algorithm/list/leetcode_21.cpp +++ b/algorithm/list/leetcode_21.cpp @@ -1,26 +1,31 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_21_test.hpp" +#include namespace leetcode_21 { +using LISTNODE::ListNode; + +#endif -ListNode *leetcode_21::mergeTwoLists(ListNode *l1, ListNode *l2) { - if (l1 == nullptr) { - return l2; - } else if (l2 == nullptr) { +class Solution { +public: + ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { + if (l1 == nullptr) { + return l2; + } else if (l2 == nullptr) { + return l1; + } + if (l1->val > l2->val) { + l2->next = mergeTwoLists(l1, l2->next); + return l2; + } + l1->next = mergeTwoLists(l1->next, l2); return l1; } - if (l1->val > l2->val) { - l2->next = mergeTwoLists(l1, l2->next); - return l2; - } - l1->next = mergeTwoLists(l1->next, l2); - return l1; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_21_test.hpp b/algorithm/list/leetcode_21_test.cpp similarity index 53% rename from algorithm/list/leetcode_21_test.hpp rename to algorithm/list/leetcode_21_test.cpp index c7f3f1c8..f2303187 100644 --- a/algorithm/list/leetcode_21_test.hpp +++ b/algorithm/list/leetcode_21_test.cpp @@ -1,48 +1,40 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 //@Plan 数据结构入门 Day7 //@Plan 剑指OfferII-I Day12 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_21_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_21_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_21_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_21_TEST_HPP #include -#include #include -#include +#include "leetcode_21.cpp" namespace leetcode_21 { using LISTNODE::ListNode; - -struct leetcode_21 { - static ListNode *mergeTwoLists(ListNode *l1, ListNode *l2); -}; - using LISTNODE::ListNodeLink; TEST_CASE("1 [test_21]", "[test_21]") { const ListNodeLink vec1{1, 2, 4}; const ListNodeLink vec2{1, 3, 4}; - const ListNode *const node1 = leetcode_21::mergeTwoLists(vec1[0], vec2[0]); + auto clas = Solution(); + const ListNode *const node1 = clas.mergeTwoLists(vec1[0], vec2[0]); CHECK(ListNode::equal({1, 1, 2, 3, 4, 4}, node1)); } TEST_CASE("2 [test_21]", "[test_21]") { const ListNodeLink vec1{1, 1, 1, 4, 4, 5}; const ListNodeLink vec2{0, 1, 1, 1, 8, 9, 9}; - const ListNode *const node1 = leetcode_21::mergeTwoLists(vec1[0], vec2[0]); + auto clas = Solution(); + const ListNode *const node1 = clas.mergeTwoLists(vec1[0], vec2[0]); CHECK(ListNode::equal({0, 1, 1, 1, 1, 1, 1, 4, 4, 5, 8, 9, 9}, node1)); } TEST_CASE("3 [test_21]", "[test_21]") { - const ListNode *const node1 = leetcode_21::mergeTwoLists(nullptr, nullptr); + auto clas = Solution(); + const ListNode *const node1 = clas.mergeTwoLists(nullptr, nullptr); CHECK(ListNode::equal({}, node1)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_21_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_21_TEST_HPP diff --git a/algorithm/list/leetcode_23.cpp b/algorithm/list/leetcode_23.cpp index 551048ad..7bc7c636 100644 --- a/algorithm/list/leetcode_23.cpp +++ b/algorithm/list/leetcode_23.cpp @@ -1,39 +1,45 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_23_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include #include +#include -using std::priority_queue; namespace leetcode_23 { +using std::vector; +using std::priority_queue; +using LISTNODE::ListNode; -ListNode *leetcode_23::mergeKLists(const vector &lists) { - static constexpr auto cmp{ - [](const ListNode *const v1, const ListNode *const v2) { - return v1->val > v2->val; - }}; - priority_queue, decltype(cmp)> pq{cmp}; - for (auto &&ele: lists) { - if (ele != nullptr) { - pq.push(ele); +#endif + +class Solution { +public: + ListNode *mergeKLists(const vector &lists) { + static constexpr auto cmp{ + [](const ListNode *const v1, const ListNode *const v2) { + return v1->val > v2->val; + }}; + priority_queue, decltype(cmp)> pq{cmp}; + for (auto &&ele: lists) { + if (ele != nullptr) { + pq.push(ele); + } } - } - ListNode head(0); - for (ListNode *stable = &head; !pq.empty();) { - stable->next = pq.top(); - pq.pop(); - stable = stable->next; - if (stable->next != nullptr) { - pq.push(stable->next); + ListNode head(0); + for (ListNode *stable = &head; !pq.empty();) { + stable->next = pq.top(); + pq.pop(); + stable = stable->next; + if (stable->next != nullptr) { + pq.push(stable->next); + } } + return head.next; } - return head.next; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_23_test.hpp b/algorithm/list/leetcode_23_test.cpp similarity index 53% rename from algorithm/list/leetcode_23_test.hpp rename to algorithm/list/leetcode_23_test.cpp index 47132a2a..84a91731 100644 --- a/algorithm/list/leetcode_23_test.hpp +++ b/algorithm/list/leetcode_23_test.cpp @@ -1,27 +1,15 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 //@Tag 优先队列 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_23_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_23_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_23_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_23_TEST_HPP #include -#include -#include -#include +#include "leetcode_23.cpp" namespace leetcode_23 { -using LISTNODE::ListNode; - -struct leetcode_23 { - static ListNode *mergeKLists(const std::vector &lists); -}; using LISTNODE::ListNodeLink; @@ -30,20 +18,23 @@ TEST_CASE("1 [test _23]", "[test _23]") { const ListNodeLink vec2{1, 3, 4}; const ListNodeLink vec3{2, 6}; const auto input = vector{vec1[0], vec2[0], vec3[0]}; - const ListNode *const result = leetcode_23::mergeKLists(input); + Solution solution; + const ListNode *const result = solution.mergeKLists(input); CHECK(ListNode::equal({1, 1, 2, 3, 4, 4, 5, 6}, result)); } TEST_CASE("2 [test _23]", "[test _23]") { const auto input = vector{}; - const ListNode *const result = leetcode_23::mergeKLists(input); + Solution solution; + const ListNode *const result = solution.mergeKLists(input); CHECK(ListNode::equal({}, result)); } TEST_CASE("3 [test _23]", "[test _23]") { const auto input = vector{nullptr}; - const ListNode *const result = leetcode_23::mergeKLists(input); + Solution solution; + const ListNode *const result = solution.mergeKLists(input); CHECK(ListNode::equal({}, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_23_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_23_TEST_HPP diff --git a/algorithm/list/leetcode_24.cpp b/algorithm/list/leetcode_24.cpp index 2ac2a5ef..7277e64a 100644 --- a/algorithm/list/leetcode_24.cpp +++ b/algorithm/list/leetcode_24.cpp @@ -1,27 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_24_test.hpp" +#include namespace leetcode_24 { +using LISTNODE::ListNode; + +#endif -ListNode *leetcode_24::swapPairs(ListNode *head) { - if (head == nullptr) { - return nullptr; - } else if (head->next == nullptr) { - return head; +class Solution { +public: + ListNode *swapPairs(ListNode *head) { + if (head == nullptr) { + return nullptr; + } else if (head->next == nullptr) { + return head; + } + ListNode *const fir = head; + ListNode *const sec = fir->next; + ListNode *const third = swapPairs(sec->next); + sec->next = fir; + fir->next = third; + return sec; } - ListNode *const fir = head; - ListNode *const sec = fir->next; - ListNode *const third = swapPairs(sec->next); - sec->next = fir; - fir->next = third; - return sec; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_24_test.cpp b/algorithm/list/leetcode_24_test.cpp new file mode 100644 index 00000000..2691544e --- /dev/null +++ b/algorithm/list/leetcode_24_test.cpp @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 +//@Plan 剑指OfferII-I Day02 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_24_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_24_TEST_HPP + +#include +#include "leetcode_24.cpp" + +namespace leetcode_24 { + +using LISTNODE::ListNodeLink; + +TEST_CASE("1 [test _24]", "[test _24]") { + const ListNodeLink vec1{1, 2, 3, 4}; + Solution solution; + const ListNode *const result = solution.swapPairs(vec1[0]); + CHECK(ListNode::equal({2, 1, 4, 3}, result)); + +} + +TEST_CASE("2 [test _24]", "[test _24]") { + Solution solution; + const ListNode *const result = solution.swapPairs(nullptr); + CHECK(ListNode::equal({}, result)); +} + +TEST_CASE("3 [test _24]", "[test _24]") { + const ListNodeLink vec1{1}; + Solution solution; + const ListNode *const result = solution.swapPairs(vec1[0]); + CHECK(ListNode::equal({1}, result)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_24_TEST_HPP diff --git a/algorithm/list/leetcode_24_test.hpp b/algorithm/list/leetcode_24_test.hpp deleted file mode 100644 index f4d1371f..00000000 --- a/algorithm/list/leetcode_24_test.hpp +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 -//@Plan 剑指OfferII-I Day02 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_24_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_24_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_24 { -using LISTNODE::ListNode; - -struct leetcode_24 { - static ListNode *swapPairs(ListNode *head); -}; - -using LISTNODE::ListNodeLink; - -TEST_CASE("1 [test _24]", "[test _24]") { - const ListNodeLink vec1{1, 2, 3, 4}; - const ListNode *const result = leetcode_24::swapPairs(vec1[0]); - CHECK(ListNode::equal({2, 1, 4, 3}, result)); - -} - -TEST_CASE("2 [test _24]", "[test _24]") { - const ListNode *const result = leetcode_24::swapPairs(nullptr); - CHECK(ListNode::equal({}, result)); -} - -TEST_CASE("3 [test _24]", "[test _24]") { - const ListNodeLink vec1{1}; - const ListNode *const result = leetcode_24::swapPairs(vec1[0]); - CHECK(ListNode::equal({1}, result)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_24_TEST_HPP diff --git a/algorithm/list/leetcode_25.cpp b/algorithm/list/leetcode_25.cpp index 7135e772..b1f19e8b 100644 --- a/algorithm/list/leetcode_25.cpp +++ b/algorithm/list/leetcode_25.cpp @@ -1,34 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_25_test.hpp" +#include +#include +#include +#include namespace leetcode_25 { +using std::vector; +using LISTNODE::ListNode; -ListNode *leetcode_25::reverseKGroup(ListNode *head, int32_t k) { - if (head == nullptr) { - return head; - } - vector nodes; - for (int32_t i{0}; i < k && head != nullptr; ++i) { - nodes.push_back(head); - head = head->next; - } - const auto nodes_size = static_cast(nodes.size()); - if (nodes_size != k) { - return nodes.front(); - } - ListNode *const knext = reverseKGroup(nodes.back()->next, k); - for (int32_t i{0}; i < nodes_size - 1; i++) { - nodes[i + 1]->next = nodes[i]; +#endif + +class Solution { +public: + ListNode *reverseKGroup(ListNode *head, int32_t k) { + if (head == nullptr) { + return head; + } + vector nodes; + for (int32_t i{0}; i < k && head != nullptr; ++i) { + nodes.push_back(head); + head = head->next; + } + const auto nodes_size = static_cast(nodes.size()); + if (nodes_size != k) { + return nodes.front(); + } + ListNode *const knext = reverseKGroup(nodes.back()->next, k); + for (int32_t i{0}; i < nodes_size - 1; i++) { + nodes[i + 1]->next = nodes[i]; + } + nodes[0]->next = knext; + return nodes.back(); } - nodes[0]->next = knext; - return nodes.back(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_25_test.cpp b/algorithm/list/leetcode_25_test.cpp new file mode 100644 index 00000000..f3444a61 --- /dev/null +++ b/algorithm/list/leetcode_25_test.cpp @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_25_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_25_TEST_HPP + +#include +#include "leetcode_25.cpp" + +namespace leetcode_25 { + +using LISTNODE::ListNodeLink; + +TEST_CASE("1 [test _25]", "[test _25]") { + const ListNodeLink vec1{1, 2, 3, 4, 5}; + Solution solution; + const ListNode *const result = solution.reverseKGroup(vec1[0], 2); + CHECK(ListNode::equal({2, 1, 4, 3, 5}, result)); +} + +TEST_CASE("2 [test _25]", "[test _25]") { + Solution solution; + const ListNode *const result = solution.reverseKGroup(nullptr, 2); + CHECK(ListNode::equal({}, result)); +} + +TEST_CASE("3 [test _25]", "[test _25]") { + const ListNodeLink vec1{1}; + Solution solution; + const ListNode *const result = solution.reverseKGroup(vec1[0], 2); + CHECK(ListNode::equal({1}, result)); +} + +TEST_CASE("4 [test _25]", "[test _25]") { + const ListNodeLink vec1{1, 2, 3, 4, 5}; + Solution solution; + const ListNode *const result = solution.reverseKGroup(vec1[0], 3); + CHECK(ListNode::equal({3, 2, 1, 4, 5}, result)); +} + +TEST_CASE("5 [test _25]", "[test _25]") { + const ListNodeLink vec1{1, 2, 3, 4, 5}; + Solution solution; + const ListNode *const result = solution.reverseKGroup(vec1[0], 1); + CHECK(ListNode::equal({1, 2, 3, 4, 5}, result)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_25_TEST_HPP diff --git a/algorithm/list/leetcode_25_test.hpp b/algorithm/list/leetcode_25_test.hpp deleted file mode 100644 index 42607242..00000000 --- a/algorithm/list/leetcode_25_test.hpp +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_25_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_25_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_25 { -using LISTNODE::ListNode; - -struct leetcode_25 { - static ListNode *reverseKGroup(ListNode *head, int32_t k); -}; - -using LISTNODE::ListNodeLink; - -TEST_CASE("1 [test _25]", "[test _25]") { - const ListNodeLink vec1{1, 2, 3, 4, 5}; - const ListNode *const result = leetcode_25::reverseKGroup(vec1[0], 2); - CHECK(ListNode::equal({2, 1, 4, 3, 5}, result)); -} - -TEST_CASE("2 [test _25]", "[test _25]") { - const ListNode *const result = leetcode_25::reverseKGroup(nullptr, 2); - CHECK(ListNode::equal({}, result)); -} - -TEST_CASE("3 [test _25]", "[test _25]") { - const ListNodeLink vec1{1}; - const ListNode *const result = leetcode_25::reverseKGroup(vec1[0], 2); - CHECK(ListNode::equal({1}, result)); -} - -TEST_CASE("4 [test _25]", "[test _25]") { - const ListNodeLink vec1{1, 2, 3, 4, 5}; - const ListNode *const result = leetcode_25::reverseKGroup(vec1[0], 3); - CHECK(ListNode::equal({3, 2, 1, 4, 5}, result)); -} - -TEST_CASE("5 [test _25]", "[test _25]") { - const ListNodeLink vec1{1, 2, 3, 4, 5}; - const ListNode *const result = leetcode_25::reverseKGroup(vec1[0], 1); - CHECK(ListNode::equal({1, 2, 3, 4, 5}, result)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_25_TEST_HPP diff --git a/algorithm/list/leetcode_2_test.hpp b/algorithm/list/leetcode_2_test.cpp similarity index 57% rename from algorithm/list/leetcode_2_test.hpp rename to algorithm/list/leetcode_2_test.cpp index 4d42af48..0887d071 100644 --- a/algorithm/list/leetcode_2_test.hpp +++ b/algorithm/list/leetcode_2_test.cpp @@ -1,47 +1,39 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_2_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_2_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_2_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_2_TEST_HPP #include -#include #include -#include +#include "leetcode_2.cpp" namespace leetcode_2 { using LISTNODE::ListNode; - -struct leetcode_2 { - static ListNode *addTwoNumbers(ListNode *l1, ListNode *l2); -}; - using LISTNODE::ListNodeLink; TEST_CASE("basic tests [test_2]", "[test_2]") { const ListNodeLink vec1{2, 4, 3}, vec2{5, 6, 4}; - const ListNode *const result = leetcode_2::addTwoNumbers(vec1[0], vec2[0]); + auto clas = Solution(); + const ListNode *const result = clas.addTwoNumbers(vec1[0], vec2[0]); CHECK(ListNode::equal({7, 0, 8}, result)); const ListNodeLink removed{const_cast(result)}; } TEST_CASE("basic tests 2 [test_2]", "[test_2]") { const ListNodeLink vec1{0}, vec2{0}; - const ListNode *const result = leetcode_2::addTwoNumbers(vec1[0], vec2[0]); + auto clas = Solution(); + const ListNode *const result = clas.addTwoNumbers(vec1[0], vec2[0]); CHECK(ListNode::equal({0}, result)); const ListNodeLink removed{const_cast(result)}; } TEST_CASE("basic tests 3 [test_2]", "[test_2]") { const ListNodeLink vec1{9, 9, 9, 9, 9, 9, 9}, vec2{9, 9, 9, 9}; - const ListNode *const result = leetcode_2::addTwoNumbers(vec1[0], vec2[0]); + auto clas = Solution(); + const ListNode *const result = clas.addTwoNumbers(vec1[0], vec2[0]); CHECK(ListNode::equal({8, 9, 9, 9, 0, 0, 0, 1}, result)); const ListNodeLink removed{const_cast(result)}; @@ -49,4 +41,4 @@ TEST_CASE("basic tests 3 [test_2]", "[test_2]") { } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_2_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_2_TEST_HPP diff --git a/algorithm/list/leetcode_61.cpp b/algorithm/list/leetcode_61.cpp index fcd78f69..c23be403 100644 --- a/algorithm/list/leetcode_61.cpp +++ b/algorithm/list/leetcode_61.cpp @@ -1,40 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_61_test.hpp" +#include namespace leetcode_61 { -ListNode *leetcode_61::rotateRight(ListNode *head, int32_t k) { - if (head == nullptr) { - return nullptr; - } - int32_t node_size{0}; - for (const ListNode *count_node{head}; - count_node != nullptr; - count_node = count_node->next) { - node_size++; - } - k = k % node_size; - ListNode *kth{head}; - for (int32_t count{0}; count < k && kth != nullptr; count++) { - kth = kth->next; - } - if (kth == nullptr || k == 0) { - return head; - } - ListNode *last_element{head}; - while (kth->next != nullptr) { - kth = kth->next; - last_element = last_element->next; +using LISTNODE::ListNode; + +#endif + +class Solution { +public: + ListNode *rotateRight(ListNode *head, int32_t k) { + if (head == nullptr) { + return nullptr; + } + int32_t node_size{0}; + for (const ListNode *count_node{head}; + count_node != nullptr; + count_node = count_node->next) { + node_size++; + } + k = k % node_size; + ListNode *kth{head}; + for (int32_t count{0}; count < k && kth != nullptr; count++) { + kth = kth->next; + } + if (kth == nullptr || k == 0) { + return head; + } + ListNode *last_element{head}; + while (kth->next != nullptr) { + kth = kth->next; + last_element = last_element->next; + } + kth->next = head; + auto *const will_return = last_element->next; + last_element->next = nullptr; + return will_return; } - kth->next = head; - auto *const will_return = last_element->next; - last_element->next = nullptr; - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_61_test.hpp b/algorithm/list/leetcode_61_test.cpp similarity index 53% rename from algorithm/list/leetcode_61_test.hpp rename to algorithm/list/leetcode_61_test.cpp index a5d1b97c..2598bec2 100644 --- a/algorithm/list/leetcode_61_test.hpp +++ b/algorithm/list/leetcode_61_test.cpp @@ -1,74 +1,70 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_61_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_61_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_61_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_61_TEST_HPP #include -#include -#include -#include +#include "leetcode_61.cpp" namespace leetcode_61 { -using LISTNODE::ListNode; - -struct leetcode_61 { - static ListNode *rotateRight(ListNode *head, int32_t k); -}; using LISTNODE::ListNodeLink; TEST_CASE("-1 [test _61]", "[test _61]") { const ListNodeLink vec1{1}; - const ListNode *const result = leetcode_61::rotateRight(vec1[0], 0); + Solution solution; + const ListNode *const result = solution.rotateRight(vec1[0], 0); CHECK(ListNode::equal({1}, result)); } TEST_CASE("0 [test _61]", "[test _61]") { const ListNodeLink vec1{1, 2}; - const ListNode *const result = leetcode_61::rotateRight(vec1[0], 2); + Solution solution; + const ListNode *const result = solution.rotateRight(vec1[0], 2); CHECK(ListNode::equal({1, 2}, result)); } TEST_CASE("1 [test _61]", "[test _61]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const ListNode *const result = leetcode_61::rotateRight(vec1[0], 2); + Solution solution; + const ListNode *const result = solution.rotateRight(vec1[0], 2); CHECK(ListNode::equal({4, 5, 1, 2, 3}, result)); } TEST_CASE("2 [test _61]", "[test _61]") { - const ListNode *const result = leetcode_61::rotateRight(nullptr, 2); + Solution solution; + const ListNode *const result = solution.rotateRight(nullptr, 2); CHECK(ListNode::equal({}, result)); } TEST_CASE("3 [test _61]", "[test _61]") { const ListNodeLink vec1{1}; - const ListNode *const result = leetcode_61::rotateRight(vec1[0], 2); + Solution solution; + const ListNode *const result = solution.rotateRight(vec1[0], 2); CHECK(ListNode::equal({1}, result)); } TEST_CASE("4 [test _61]", "[test _61]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const ListNode *const result = leetcode_61::rotateRight(vec1[0], 3); + Solution solution; + const ListNode *const result = solution.rotateRight(vec1[0], 3); CHECK(ListNode::equal({3, 4, 5, 1, 2}, result)); } TEST_CASE("5 [test _61]", "[test _61]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const ListNode *const result = leetcode_61::rotateRight(vec1[0], 4); + Solution solution; + const ListNode *const result = solution.rotateRight(vec1[0], 4); CHECK(ListNode::equal({2, 3, 4, 5, 1}, result)); } TEST_CASE("6 [test _61]", "[test _61]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const ListNode *const result = leetcode_61::rotateRight(vec1[0], 1234); + Solution solution; + const ListNode *const result = solution.rotateRight(vec1[0], 1234); CHECK(ListNode::equal({2, 3, 4, 5, 1}, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_61_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_61_TEST_HPP diff --git a/algorithm/list/leetcode_82.cpp b/algorithm/list/leetcode_82.cpp index 390ef8af..11e43d07 100644 --- a/algorithm/list/leetcode_82.cpp +++ b/algorithm/list/leetcode_82.cpp @@ -1,29 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_82_test.hpp" +#include namespace leetcode_82 { -ListNode *leetcode_82::deleteDuplicates(ListNode *head) { - ListNode will_return(-1); - ListNode *will_return_ptr = &will_return; - while (head != nullptr) { - ListNode *const head_back{head}; - size_t count{0}; - for (int32_t v = head->val; head != nullptr && head->val == v; head = head->next) { - count++; - } - if (count == 1) { - will_return_ptr->next = head_back; - will_return_ptr = will_return_ptr->next; +using LISTNODE::ListNode; + +#endif + +class Solution { +public: + ListNode *deleteDuplicates(ListNode *head) { + ListNode will_return(-1); + ListNode *will_return_ptr = &will_return; + while (head != nullptr) { + ListNode *const head_back{head}; + size_t count{0}; + for (int32_t v = head->val; head != nullptr && head->val == v; head = head->next) { + count++; + } + if (count == 1) { + will_return_ptr->next = head_back; + will_return_ptr = will_return_ptr->next; + } } + will_return_ptr->next = nullptr; + return will_return.next; } - will_return_ptr->next = nullptr; - return will_return.next; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_82_test.hpp b/algorithm/list/leetcode_82_test.cpp similarity index 53% rename from algorithm/list/leetcode_82_test.hpp rename to algorithm/list/leetcode_82_test.cpp index 43316d2c..4559c312 100644 --- a/algorithm/list/leetcode_82_test.hpp +++ b/algorithm/list/leetcode_82_test.cpp @@ -1,74 +1,70 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_82_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_82_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_82_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_82_TEST_HPP #include -#include -#include -#include +#include "leetcode_82.cpp" namespace leetcode_82 { -using LISTNODE::ListNode; - -struct leetcode_82 { - static ListNode *deleteDuplicates(ListNode *head); -}; using LISTNODE::ListNodeLink; TEST_CASE("-1 [test _82]", "[test _82]") { const ListNodeLink vec1{1}; - const ListNode *const result = leetcode_82::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1}, result)); } TEST_CASE("0 [test _82]", "[test _82]") { const ListNodeLink vec1{1, 2}; - const ListNode *const result = leetcode_82::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1, 2}, result)); } TEST_CASE("1 [test _82]", "[test _82]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const ListNode *const result = leetcode_82::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1, 2, 3, 4, 5}, result)); } TEST_CASE("2 [test _82]", "[test _82]") { - const ListNode *const result = leetcode_82::deleteDuplicates(nullptr); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(nullptr); CHECK(ListNode::equal({}, result)); } TEST_CASE("3 [test _82]", "[test _82]") { const ListNodeLink vec1{1}; - const ListNode *const result = leetcode_82::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1}, result)); } TEST_CASE("4 [test _82]", "[test _82]") { const ListNodeLink vec1{1, 2, 2, 3, 4, 5}; - const ListNode *const result = leetcode_82::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1, 3, 4, 5}, result)); } TEST_CASE("5 [test _82]", "[test _82]") { const ListNodeLink vec1{1, 2, 2, 3, 3, 4, 5}; - const ListNode *const result = leetcode_82::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1, 4, 5}, result)); } TEST_CASE("6 [test _82]", "[test _82]") { const ListNodeLink vec1{1, 1, 2, 2, 3, 3, 4, 4, 5}; - const ListNode *const result = leetcode_82::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({5}, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_82_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_82_TEST_HPP diff --git a/algorithm/list/leetcode_83.cpp b/algorithm/list/leetcode_83.cpp index 2b3c1062..06c8df79 100644 --- a/algorithm/list/leetcode_83.cpp +++ b/algorithm/list/leetcode_83.cpp @@ -1,23 +1,29 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_83_test.hpp" +#include namespace leetcode_83 { +using LISTNODE::ListNode; + +#endif -ListNode *leetcode_83::deleteDuplicates(ListNode *head) { - if (head == nullptr || head->next == nullptr) { +class Solution { +public: + ListNode *deleteDuplicates(ListNode *head) { + if (head == nullptr || head->next == nullptr) { + return head; + } + head->next = deleteDuplicates(head->next); + if (head->val == head->next->val) { + head = head->next; + } return head; } - head->next = deleteDuplicates(head->next); - if (head->val == head->next->val) { - head = head->next; - } - return head; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_83_test.hpp b/algorithm/list/leetcode_83_test.cpp similarity index 54% rename from algorithm/list/leetcode_83_test.hpp rename to algorithm/list/leetcode_83_test.cpp index 21957d9f..923bafce 100644 --- a/algorithm/list/leetcode_83_test.hpp +++ b/algorithm/list/leetcode_83_test.cpp @@ -1,75 +1,71 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 //@Plan 数据结构入门 Day8 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_83_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_83_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_83_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_83_TEST_HPP #include -#include -#include -#include +#include "leetcode_83.cpp" namespace leetcode_83 { -using LISTNODE::ListNode; - -struct leetcode_83 { - static ListNode *deleteDuplicates(ListNode *head); -}; using LISTNODE::ListNodeLink; TEST_CASE("-1 [test _83]", "[test _83]") { const ListNodeLink vec1{1}; - const ListNode *const result = leetcode_83::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1}, result)); } TEST_CASE("0 [test _83]", "[test _83]") { const ListNodeLink vec1{1, 2}; - const ListNode *const result = leetcode_83::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1, 2}, result)); } TEST_CASE("1 [test _83]", "[test _83]") { const ListNodeLink vec1{1, 2, 3, 4, 5}; - const ListNode *const result = leetcode_83::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1, 2, 3, 4, 5}, result)); } TEST_CASE("2 [test _83]", "[test _83]") { - const ListNode *const result = leetcode_83::deleteDuplicates(nullptr); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(nullptr); CHECK(ListNode::equal({}, result)); } TEST_CASE("3 [test _83]", "[test _83]") { const ListNodeLink vec1{1}; - const ListNode *const result = leetcode_83::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1}, result)); } TEST_CASE("4 [test _83]", "[test _83]") { const ListNodeLink vec1{1, 2, 2, 3, 4, 5}; - const ListNode *const result = leetcode_83::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1, 2, 3, 4, 5}, result)); } TEST_CASE("5 [test _83]", "[test _83]") { const ListNodeLink vec1{1, 2, 2, 3, 3, 4, 5}; - const ListNode *const result = leetcode_83::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1, 2, 3, 4, 5}, result)); } TEST_CASE("6 [test _83]", "[test _83]") { const ListNodeLink vec1{1, 1, 2, 2, 3, 3, 4, 4, 5}; - const ListNode *const result = leetcode_83::deleteDuplicates(vec1[0]); + Solution solution; + const ListNode *const result = solution.deleteDuplicates(vec1[0]); CHECK(ListNode::equal({1, 2, 3, 4, 5}, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_83_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_83_TEST_HPP diff --git a/algorithm/list/leetcode_86.cpp b/algorithm/list/leetcode_86.cpp index f5fa633a..1bb36105 100644 --- a/algorithm/list/leetcode_86.cpp +++ b/algorithm/list/leetcode_86.cpp @@ -1,30 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_86_test.hpp" +#include namespace leetcode_86 { +using LISTNODE::ListNode; + +#endif -ListNode *leetcode_86::partition(ListNode *head, int32_t x) { - ListNode node1{-1}, node2{-1}; - ListNode *p_node1{&node1}, *p_node2{&node2}; - while (head != nullptr) { - if (head->val >= x) { - p_node2->next = new ListNode(head->val); - p_node2 = p_node2->next; - } else { - p_node1->next = new ListNode(head->val); - p_node1 = p_node1->next; +class Solution { +public: + ListNode *partition(ListNode *head, int32_t x) { + ListNode node1{-1}, node2{-1}; + ListNode *p_node1{&node1}, *p_node2{&node2}; + while (head != nullptr) { + if (head->val >= x) { + p_node2->next = new ListNode(head->val); + p_node2 = p_node2->next; + } else { + p_node1->next = new ListNode(head->val); + p_node1 = p_node1->next; + } + head = head->next; } - head = head->next; + p_node1->next = node2.next; + return node1.next; } - p_node1->next = node2.next; - return node1.next; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_86_test.cpp b/algorithm/list/leetcode_86_test.cpp new file mode 100644 index 00000000..2d2d66b6 --- /dev/null +++ b/algorithm/list/leetcode_86_test.cpp @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_86_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_86_TEST_HPP + +#include +#include "leetcode_86.cpp" + +namespace leetcode_86 { + +using LISTNODE::ListNodeLink; + +TEST_CASE("-1 [test _86]", "[test _86]") { + const ListNodeLink vec1{1, 4, 3, 2, 5, 2}; + Solution solution; + const ListNode *const result = solution.partition(vec1[0], 3); + CHECK(ListNode::equal({1, 2, 2, 4, 3, 5}, result)); + const ListNodeLink removed{const_cast(result)}; +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_86_TEST_HPP diff --git a/algorithm/list/leetcode_86_test.hpp b/algorithm/list/leetcode_86_test.hpp deleted file mode 100644 index 5202bdc2..00000000 --- a/algorithm/list/leetcode_86_test.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_86_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_86_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_86 { -using LISTNODE::ListNode; - -struct leetcode_86 { - static ListNode *partition(ListNode *head, int32_t x); -}; - -using LISTNODE::ListNodeLink; - -TEST_CASE("-1 [test _86]", "[test _86]") { - const ListNodeLink vec1{1, 4, 3, 2, 5, 2}; - const ListNode *const result = leetcode_86::partition(vec1[0], 3); - CHECK(ListNode::equal({1, 2, 2, 4, 3, 5}, result)); - const ListNodeLink removed{const_cast(result)}; -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_86_TEST_HPP diff --git a/algorithm/list/leetcode_876.cpp b/algorithm/list/leetcode_876.cpp index ddf63b25..89f6cc3d 100644 --- a/algorithm/list/leetcode_876.cpp +++ b/algorithm/list/leetcode_876.cpp @@ -1,26 +1,31 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_876_test.hpp" +#include namespace leetcode_876 { +using LISTNODE::ListNode; + +#endif -ListNode *leetcode_876::middleNode(ListNode *const head) { - ListNode *one = head; - for (const ListNode *two = head; two != nullptr;) { - if (two->next != nullptr) { +class Solution { +public: + ListNode *middleNode(ListNode *const head) { + ListNode *one = head; + for (const ListNode *two = head; two != nullptr;) { + if (two->next != nullptr) { + two = two->next; + } else { + return one; + } two = two->next; - } else { - return one; + one = one->next; } - two = two->next; - one = one->next; + return one; } - return one; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_876_test.hpp b/algorithm/list/leetcode_876_test.cpp similarity index 52% rename from algorithm/list/leetcode_876_test.hpp rename to algorithm/list/leetcode_876_test.cpp index a693b8a6..21fd6054 100644 --- a/algorithm/list/leetcode_876_test.hpp +++ b/algorithm/list/leetcode_876_test.cpp @@ -1,43 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 //@Description 链表中点,经典双指针 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_876_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_876_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_876_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_876_TEST_HPP #include #include +#include "leetcode_876.cpp" namespace leetcode_876 { -using LISTNODE::ListNode; - -struct leetcode_876 final : private nonCopyMoveAble { - static ListNode *middleNode(ListNode *head); -}; TEST_CASE("test case 1 [test_876]", "[test_876]") { const LISTNODE::ListNodeLink vec1{1, 2, 3, 4, 5}; - const auto result = leetcode_876::middleNode(vec1[0]); + Solution solution; + const auto result = solution.middleNode(vec1[0]); CHECK(3 == result->val); } TEST_CASE("test case 2 [test_876]", "[test_876]") { const LISTNODE::ListNodeLink vec1{1, 1, 4, 5, 1, 4}; - const auto result = leetcode_876::middleNode(vec1[0]); + Solution solution; + const auto result = solution.middleNode(vec1[0]); CHECK(5 == result->val); } TEST_CASE("test case 3 [test_876]", "[test_876]") { const LISTNODE::ListNodeLink vec1{1, 9, 1, 9, 8, 1, 0}; - const auto result = leetcode_876::middleNode(vec1[0]); + Solution solution; + const auto result = solution.middleNode(vec1[0]); CHECK(9 == result->val); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_876_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_876_TEST_HPP diff --git a/algorithm/list/leetcode_92.cpp b/algorithm/list/leetcode_92.cpp index e1c38e6e..1f53c898 100644 --- a/algorithm/list/leetcode_92.cpp +++ b/algorithm/list/leetcode_92.cpp @@ -1,30 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_92_test.hpp" +#include namespace leetcode_92 { -ListNode *leetcode_92::reverseBetween(ListNode *head, int32_t left, int32_t right) { - ListNode will_return{-1}; - will_return.next = head; - ListNode *pre{&will_return}; - for (int32_t i{1}; i < left; i++) { - pre = pre->next; - } - ListNode *iter{pre->next}; +using LISTNODE::ListNode; +#endif + +class Solution { +public: + ListNode *reverseBetween(ListNode *head, int32_t left, int32_t right) { + ListNode will_return{-1}; + will_return.next = head; + ListNode *pre{&will_return}; + for (int32_t i{1}; i < left; i++) { + pre = pre->next; + } + ListNode *iter{pre->next}; - for (int32_t i{left}; i < right; i++) { - ListNode *next{iter->next}; - ListNode *const prenext = pre->next; - iter->next = next->next; - pre->next = next; - next->next = prenext; + for (int32_t i{left}; i < right; i++) { + ListNode *next{iter->next}; + ListNode *const prenext = pre->next; + iter->next = next->next; + pre->next = next; + next->next = prenext; + } + return will_return.next; } - return will_return.next; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_92_test.cpp b/algorithm/list/leetcode_92_test.cpp new file mode 100644 index 00000000..c232aa3b --- /dev/null +++ b/algorithm/list/leetcode_92_test.cpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_92_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_92_TEST_HPP + +#include +#include "leetcode_92.cpp" + +namespace leetcode_92 { + +using LISTNODE::ListNodeLink; + +TEST_CASE("-1 [test _92]", "[test _92]") { + const ListNodeLink vec1{1, 2, 3, 4, 5}; + Solution solution; + const ListNode *const result = solution.reverseBetween(vec1[0], 2, 4); + CHECK(ListNode::equal({1, 4, 3, 2, 5}, result)); +} + +TEST_CASE("0 [test _92]", "[test _92]") { + const ListNodeLink vec1{5}; + Solution solution; + const ListNode *const result = solution.reverseBetween(vec1[0], 1, 1); + CHECK(ListNode::equal({5}, result)); +} + +TEST_CASE("1 [test _92]", "[test _92]") { + const ListNodeLink vec1{3, 5}; + Solution solution; + const ListNode *const result = solution.reverseBetween(vec1[0], 1, 1); + CHECK(ListNode::equal({3, 5}, result)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_92_TEST_HPP diff --git a/algorithm/list/leetcode_92_test.hpp b/algorithm/list/leetcode_92_test.hpp deleted file mode 100644 index e2a5e1cc..00000000 --- a/algorithm/list/leetcode_92_test.hpp +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_92_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_92_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_92 { -using LISTNODE::ListNode; - -struct leetcode_92 { - static ListNode *reverseBetween(ListNode *head, int32_t left, int32_t right); -}; - -using LISTNODE::ListNodeLink; - -TEST_CASE("-1 [test _92]", "[test _92]") { - const ListNodeLink vec1{1, 2, 3, 4, 5}; - const ListNode *const result = leetcode_92::reverseBetween(vec1[0], 2, 4); - CHECK(ListNode::equal({1, 4, 3, 2, 5}, result)); -} - -TEST_CASE("0 [test _92]", "[test _92]") { - const ListNodeLink vec1{5}; - const ListNode *const result = leetcode_92::reverseBetween(vec1[0], 1, 1); - CHECK(ListNode::equal({5}, result)); -} - -TEST_CASE("1 [test _92]", "[test _92]") { - const ListNodeLink vec1{3, 5}; - const ListNode *const result = leetcode_92::reverseBetween(vec1[0], 1, 1); - CHECK(ListNode::equal({3, 5}, result)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_92_TEST_HPP diff --git a/algorithm/list/leetcode_so_06.cpp b/algorithm/list/leetcode_so_06.cpp index 84943e6d..18931f33 100644 --- a/algorithm/list/leetcode_so_06.cpp +++ b/algorithm/list/leetcode_so_06.cpp @@ -1,27 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_so_06_test.hpp" +#include +#include +#include #include +#include namespace leetcode_so_06 { +using std::vector; +using LISTNODE::ListNode; +#endif -vector leetcode_so_06::reversePrint(ListNode *head) { - std::stack sta; - while (head != nullptr) { - sta.push(head->val); - head = head->next; - } - vector will_return; - while (!sta.empty()) { - will_return.push_back(sta.top()); - sta.pop(); +class Solution { +public: + vector reversePrint(ListNode *head) { + std::stack sta; + while (head != nullptr) { + sta.push(head->val); + head = head->next; + } + vector will_return; + while (!sta.empty()) { + will_return.push_back(sta.top()); + sta.pop(); + } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_so_06_test.cpp b/algorithm/list/leetcode_so_06_test.cpp new file mode 100644 index 00000000..d6926667 --- /dev/null +++ b/algorithm/list/leetcode_so_06_test.cpp @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 +//@Plan 剑指OfferII-I Day02 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_06_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_06_TEST_HPP + +#include +#include "leetcode_so_06.cpp" + +namespace leetcode_so_06 { + +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_206]", "[test_206]") { + const LISTNODE::ListNodeLink vec1{1, 2, 3, 4, 5}; + Solution solution; + const auto result = solution.reversePrint(vec1[0]); + CHECK_THAT(result, Equals(vector{5, 4, 3, 2, 1})); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_06_TEST_HPP diff --git a/algorithm/list/leetcode_so_06_test.hpp b/algorithm/list/leetcode_so_06_test.hpp deleted file mode 100644 index 7290a6db..00000000 --- a/algorithm/list/leetcode_so_06_test.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 -//@Plan 剑指OfferII-I Day02 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_06_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_06_TEST_HPP - -#include -#include - -namespace leetcode_so_06 { -using LISTNODE::ListNode; - -struct leetcode_so_06 final : private nonCopyMoveAble { - static vector reversePrint(ListNode *head); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_206]", "[test_206]") { - const LISTNODE::ListNodeLink vec1{1, 2, 3, 4, 5}; - const auto result = leetcode_so_06::reversePrint(vec1[0]); - CHECK_THAT(result, Equals(vector{5, 4, 3, 2, 1})); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_06_TEST_HPP diff --git a/algorithm/list/leetcode_so_18.cpp b/algorithm/list/leetcode_so_18.cpp index 45a4909a..7a66c86d 100644 --- a/algorithm/list/leetcode_so_18.cpp +++ b/algorithm/list/leetcode_so_18.cpp @@ -1,23 +1,28 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_so_18_test.hpp" +#include namespace leetcode_so_18 { +using LISTNODE::ListNode; +#endif -ListNode *leetcode_so_18::deleteNode(ListNode *head, int32_t val) { - ListNode base{-1}; - base.next = head; - for (ListNode *root{&base}; root->next != nullptr; root = root->next) { - if (root->next->val == val) { - root->next = root->next->next; - break; +class Solution { +public: + ListNode *deleteNode(ListNode *head, int32_t val) { + ListNode base{-1}; + base.next = head; + for (ListNode *root{&base}; root->next != nullptr; root = root->next) { + if (root->next->val == val) { + root->next = root->next->next; + break; + } } + return base.next; } - return base.next; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_so_18_test.cpp b/algorithm/list/leetcode_so_18_test.cpp new file mode 100644 index 00000000..ede60a2c --- /dev/null +++ b/algorithm/list/leetcode_so_18_test.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 +//@Plan 剑指OfferII-I Day11 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_18_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_18_TEST_HPP + +#include +#include "leetcode_so_18.cpp" + +namespace leetcode_so_18 { + +using LISTNODE::ListNodeLink; +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_206]", "[test_206]") { + const LISTNODE::ListNodeLink vec1{4, 5, 1, 9}; + Solution solution; + const auto result = solution.deleteNode(vec1[0], 5); + CHECK(ListNode::equal({4, 1, 9}, result)); +} + +TEST_CASE("test case 2 [test_206]", "[test_206]") { + const LISTNODE::ListNodeLink vec1{4, 5, 1, 9}; + Solution solution; + const auto result = solution.deleteNode(vec1[0], 1); + CHECK(ListNode::equal({4, 5, 9}, result)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_18_TEST_HPP diff --git a/algorithm/list/leetcode_so_18_test.hpp b/algorithm/list/leetcode_so_18_test.hpp deleted file mode 100644 index 7f4c613d..00000000 --- a/algorithm/list/leetcode_so_18_test.hpp +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 -//@Plan 剑指OfferII-I Day11 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_18_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_18_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_so_18 { - -using LISTNODE::ListNode; - -struct leetcode_so_18 final : private nonCopyMoveAble { - static ListNode *deleteNode(ListNode *head, int32_t val); -}; - -using LISTNODE::ListNodeLink; -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_206]", "[test_206]") { - const LISTNODE::ListNodeLink vec1{4, 5, 1, 9}; - const auto result = leetcode_so_18::deleteNode(vec1[0], 5); - CHECK(ListNode::equal({4, 1, 9}, result)); -} - -TEST_CASE("test case 2 [test_206]", "[test_206]") { - const LISTNODE::ListNodeLink vec1{4, 5, 1, 9}; - const auto result = leetcode_so_18::deleteNode(vec1[0], 1); - CHECK(ListNode::equal({4, 5, 9}, result)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_18_TEST_HPP diff --git a/algorithm/list/leetcode_so_22.cpp b/algorithm/list/leetcode_so_22.cpp index aaa1acf2..55c4ec62 100644 --- a/algorithm/list/leetcode_so_22.cpp +++ b/algorithm/list/leetcode_so_22.cpp @@ -1,22 +1,27 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_so_22_test.hpp" +#include namespace leetcode_so_22 { +using LISTNODE::ListNode; + +#endif -ListNode *leetcode_so_22::getKthFromEnd(ListNode *head, int32_t k) { - const ListNode *slow{head}, *fast{head}; - for (int32_t i{0}; fast != nullptr && i < k; (fast = fast->next) && ++i) {} - if (fast == nullptr) { - return const_cast(slow); +class Solution { +public: + ListNode *getKthFromEnd(ListNode *head, int32_t k) { + const ListNode *slow{head}, *fast{head}; + for (int32_t i{0}; fast != nullptr && i < k; (fast = fast->next) && ++i) {} + if (fast == nullptr) { + return const_cast(slow); + } + for (; fast != nullptr; (fast = fast->next) && (slow = slow->next)) {} + return slow->next; } - for (; fast != nullptr; (fast = fast->next) && (slow = slow->next)) {} - return slow->next; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_so_22_test.cpp b/algorithm/list/leetcode_so_22_test.cpp new file mode 100644 index 00000000..a6f8c432 --- /dev/null +++ b/algorithm/list/leetcode_so_22_test.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 +//@Plan 剑指OfferII-I Day11 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_22_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_22_TEST_HPP + +#include +#include "leetcode_so_22.cpp" + +namespace leetcode_so_22 { + +using LISTNODE::ListNodeLink; +using Catch::Matchers::Equals; + +TEST_CASE("test case 1 [test_206]", "[test_206]") { + const LISTNODE::ListNodeLink vec1{1}; + Solution solution; + const auto result = solution.getKthFromEnd(vec1[0], 1); + CHECK(ListNode::equal({1}, result)); +} + +TEST_CASE("test case 2 [test_206]", "[test_206]") { + const LISTNODE::ListNodeLink vec1{4, 5, 1, 9}; + Solution solution; + const auto result = solution.getKthFromEnd(vec1[0], 3); + CHECK(ListNode::equal({5, 1, 9}, result)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_22_TEST_HPP diff --git a/algorithm/list/leetcode_so_22_test.hpp b/algorithm/list/leetcode_so_22_test.hpp deleted file mode 100644 index f94d2030..00000000 --- a/algorithm/list/leetcode_so_22_test.hpp +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 -//@Plan 剑指OfferII-I Day11 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_22_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_22_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_so_22 { - -using LISTNODE::ListNode; - -struct leetcode_so_22 final : private nonCopyMoveAble { - static ListNode *getKthFromEnd(ListNode *head, int32_t k); -}; - -using LISTNODE::ListNodeLink; -using Catch::Matchers::Equals; - -TEST_CASE("test case 1 [test_206]", "[test_206]") { - const LISTNODE::ListNodeLink vec1{1}; - const auto result = leetcode_so_22::getKthFromEnd(vec1[0], 1); - CHECK(ListNode::equal({1}, result)); -} - -TEST_CASE("test case 2 [test_206]", "[test_206]") { - const LISTNODE::ListNodeLink vec1{4, 5, 1, 9}; - const auto result = leetcode_so_22::getKthFromEnd(vec1[0], 3); - CHECK(ListNode::equal({5, 1, 9}, result)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_22_TEST_HPP diff --git a/algorithm/list/leetcode_so_35.cpp b/algorithm/list/leetcode_so_35.cpp index 26e7fd52..15927e65 100644 --- a/algorithm/list/leetcode_so_35.cpp +++ b/algorithm/list/leetcode_so_35.cpp @@ -1,43 +1,63 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_so_35_test.hpp" +#include +#include +#include +#include +#include namespace leetcode_so_35 { +using std::vector; +using std::unordered_map; -Node *leetcode_so_35::copyRandomList(Node *head) { - std::unordered_map umap; - Node *head2 = head; - for (size_t i{0}; head2 != nullptr; head2 = head2->next, ++i) { - umap[reinterpret_cast(head2)] = i; - } - const auto length = umap.size(); - vector random_map(length); - Node *head3 = head; - for (size_t i{0}; head3 != nullptr; head3 = head3->next, ++i) { - if (head3->random == nullptr) { - random_map[i] = std::numeric_limits::max(); - } else { - random_map[i] = umap[reinterpret_cast(head3->random)]; +struct Node { +public: + int val; + Node *next; + Node *random; + + explicit Node(int32_t _val) : val(_val), next(nullptr), random(nullptr) {} +}; + +#endif + +class Solution { +public: + Node *copyRandomList(Node *head) { + std::unordered_map umap; + Node *head2 = head; + for (size_t i{0}; head2 != nullptr; head2 = head2->next, ++i) { + umap[reinterpret_cast(head2)] = i; } - } - std::vector nodes(length); - Node *head4 = head; - for (size_t i{0}; head4 != nullptr; head4 = head4->next, ++i) { - nodes[i] = new Node(head4->val); - } - for (size_t i{0}; i + 1 < length; ++i) { - nodes[i]->next = nodes[i + 1]; - } - for (size_t i{0}; i < length; ++i) { - if (random_map[i] != std::numeric_limits::max()) { - nodes[i]->random = nodes[random_map[i]]; + const auto length = umap.size(); + vector random_map(length); + Node *head3 = head; + for (size_t i{0}; head3 != nullptr; head3 = head3->next, ++i) { + if (head3->random == nullptr) { + random_map[i] = std::numeric_limits::max(); + } else { + random_map[i] = umap[reinterpret_cast(head3->random)]; + } + } + std::vector nodes(length); + Node *head4 = head; + for (size_t i{0}; head4 != nullptr; head4 = head4->next, ++i) { + nodes[i] = new Node(head4->val); + } + for (size_t i{0}; i + 1 < length; ++i) { + nodes[i]->next = nodes[i + 1]; } + for (size_t i{0}; i < length; ++i) { + if (random_map[i] != std::numeric_limits::max()) { + nodes[i]->random = nodes[random_map[i]]; + } + } + return nodes[0]; } - return nodes[0]; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/list/leetcode_so_35_test.cpp b/algorithm/list/leetcode_so_35_test.cpp new file mode 100644 index 00000000..c932cffe --- /dev/null +++ b/algorithm/list/leetcode_so_35_test.cpp @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 +//@Description 深复制 +//@Plan 剑指OfferII-I Day02 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_35_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_35_TEST_HPP + +#include +#include "leetcode_so_35.cpp" + +namespace leetcode_so_35 { + +TEST_CASE("test case 1 [test_206]", "[test_206]") {} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_35_TEST_HPP diff --git a/algorithm/list/leetcode_so_35_test.hpp b/algorithm/list/leetcode_so_35_test.hpp deleted file mode 100644 index 6851015a..00000000 --- a/algorithm/list/leetcode_so_35_test.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 -//@Description 深复制 -//@Plan 剑指OfferII-I Day02 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_35_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_35_TEST_HPP - -#include -#include -#include - -namespace leetcode_so_35 { -struct Node { -public: - int val; - Node *next; - Node *random; - - explicit Node(int32_t _val) : val(_val), next(nullptr), random(nullptr) {} -}; - -struct leetcode_so_35 final : private nonCopyMoveAble { - static Node *copyRandomList(Node *head); -}; - -TEST_CASE("test case 1 [test_206]", "[test_206]") {} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_SO_35_TEST_HPP diff --git a/algorithm/math/CMakeLists.txt b/algorithm/math/CMakeLists.txt index 88480b24..8720ca6f 100644 --- a/algorithm/math/CMakeLists.txt +++ b/algorithm/math/CMakeLists.txt @@ -21,9 +21,10 @@ set(dependencies ${dependencies} ${leetcode_order}) unset(leetcode_order) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) endforeach () unset(dependencies) diff --git a/algorithm/math/leetcode_1018.cpp b/algorithm/math/leetcode_1018.cpp index 4402c143..bd0150e0 100644 --- a/algorithm/math/leetcode_1018.cpp +++ b/algorithm/math/leetcode_1018.cpp @@ -1,22 +1,28 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_1018_test.hpp" +#include +#include +#include namespace leetcode_1018 { +using std::vector; +#endif -vector leetcode_1018::prefixesDivBy5(const vector &nums) { - const auto nums_size{nums.size()}; - vector willreturn(nums_size); - for (size_t i{0}, num{0}; i < nums_size; ++i) { - num = (2 * num + nums[i]) % 5; - willreturn[i] = (num == 0); +class Solution { +public: + vector prefixesDivBy5(const vector &nums) { + const auto nums_size{nums.size()}; + vector willreturn(nums_size); + for (size_t i{0}, num{0}; i < nums_size; ++i) { + num = (2 * num + nums[i]) % 5; + willreturn[i] = (num == 0); + } + return willreturn; } - return willreturn; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_1018_test.cpp b/algorithm/math/leetcode_1018_test.cpp new file mode 100644 index 00000000..ce360107 --- /dev/null +++ b/algorithm/math/leetcode_1018_test.cpp @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag Math +//@Tag 数学 +//@Tag 记忆化 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1018_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1018_TEST_HPP + +#include +#include "leetcode_1018.cpp" + +namespace leetcode_1018 { + +using Catch::Matchers::Equals; + +TEST_CASE("1 [test_1018]", "[test_1018]") { + const vector input{0, 1, 1}; + const vector result{true, false, false}; + Solution solution; + CHECK_THAT(result, Equals(solution.prefixesDivBy5(input))); +} + +TEST_CASE("2 [test_1018]", "[test_1018]") { + const vector input{0, 1, 1}; + const vector result{true, false, false}; + Solution solution; + CHECK_THAT(result, Equals(solution.prefixesDivBy5(input))); +} + +TEST_CASE("3 [test_1018]", "[test_1018]") { + const vector input{0, 1, 1}; + const vector result{true, false, false}; + Solution solution; + CHECK_THAT(result, Equals(solution.prefixesDivBy5(input))); +} + +} + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1018_TEST_HPP + diff --git a/algorithm/math/leetcode_1018_test.hpp b/algorithm/math/leetcode_1018_test.hpp deleted file mode 100644 index 4c0f2137..00000000 --- a/algorithm/math/leetcode_1018_test.hpp +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag Math -//@Tag 数学 -//@Tag 记忆化 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1018_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1018_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_1018 { -using std::vector; - -struct leetcode_1018 { - static vector prefixesDivBy5(const vector &nums); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("1 [test_1018]", "[test_1018]") { - const vector input{0, 1, 1}; - const vector result{true, false, false}; - CHECK_THAT(result, Equals(leetcode_1018::prefixesDivBy5(input))); -} - -TEST_CASE("2 [test_1018]", "[test_1018]") { - const vector input{0, 1, 1}; - const vector result{true, false, false}; - CHECK_THAT(result, Equals(leetcode_1018::prefixesDivBy5(input))); -} - -TEST_CASE("3 [test_1018]", "[test_1018]") { - const vector input{0, 1, 1}; - const vector result{true, false, false}; - CHECK_THAT(result, Equals(leetcode_1018::prefixesDivBy5(input))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1018_TEST_HPP - diff --git a/algorithm/math/leetcode_1185.cpp b/algorithm/math/leetcode_1185.cpp index c099d420..6a3ac41d 100644 --- a/algorithm/math/leetcode_1185.cpp +++ b/algorithm/math/leetcode_1185.cpp @@ -1,14 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_1185_test.hpp" +#include +#include +#include #include namespace leetcode_1185 { +using std::string; + +inline constexpr const std::array weekStrs + {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; int32_t getYearDays(int32_t year) { assert(1971 <= year & year <= 2100); @@ -30,29 +33,35 @@ int32_t getMonthDays(int32_t year, int32_t month) { // 7*31+5*30+28=187+180+28=365 return monthDays[month]; } +#endif -string leetcode_1185::dayOfTheWeek(int day, int month, int year) { - // 1993 08 15 是sunday周日 - // 1993 08 01 是周日 - // 1993 01 01 间隔 31+28+31+30+31+30+31= 212天 %7 == 2天,因此是周五 - // 1971 01 01 间隔 22年,其中有1972,1976,1980,1984,1988,1992六个闰年,所以是22*365+6=7300+730+6=8036天 % 7 = 336 % 7 = 56 % 7 = 0,所以也是周五 - const auto yearDays{[](const auto lastYear) { - int32_t will_return{0}; - for (auto begin{1971}; begin < lastYear; ++begin) { - will_return += getYearDays(begin); - } - return will_return; - }(year)}; - const auto monthDays{[](const auto lastMonth, const auto year) { - int32_t will_return{0}; - for (auto begin{1}; begin < lastMonth; ++begin) { - will_return += getMonthDays(year, begin); - } - return will_return; - }(month, year)}; - const auto daysDiff{day - 1}; - const auto choice{(yearDays + monthDays + daysDiff + 5) % 7}; - return weekStrs[choice]; -} +class Solution { +public: + string dayOfTheWeek(int day, int month, int year) { + // 1993 08 15 是sunday周日 + // 1993 08 01 是周日 + // 1993 01 01 间隔 31+28+31+30+31+30+31= 212天 %7 == 2天,因此是周五 + // 1971 01 01 间隔 22年,其中有1972,1976,1980,1984,1988,1992六个闰年,所以是22*365+6=7300+730+6=8036天 % 7 = 336 % 7 = 56 % 7 = 0,所以也是周五 + const auto yearDays{[](const auto lastYear) { + int32_t will_return{0}; + for (auto begin{1971}; begin < lastYear; ++begin) { + will_return += getYearDays(begin); + } + return will_return; + }(year)}; + const auto monthDays{[](const auto lastMonth, const auto year) { + int32_t will_return{0}; + for (auto begin{1}; begin < lastMonth; ++begin) { + will_return += getMonthDays(year, begin); + } + return will_return; + }(month, year)}; + const auto daysDiff{day - 1}; + const auto choice{(yearDays + monthDays + daysDiff + 5) % 7}; + return weekStrs[choice]; + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_1185_test.cpp b/algorithm/math/leetcode_1185_test.cpp new file mode 100644 index 00000000..f7973664 --- /dev/null +++ b/algorithm/math/leetcode_1185_test.cpp @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag 常识 +//@Tag 暴力 +//@Tag 先验知识 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1185_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1185_TEST_HPP + +#include +#include "leetcode_1185.cpp" + +namespace leetcode_1185 { + +using Catch::Matchers::Equals; + +TEST_CASE("1-1 [test_1185]", "[test_1185]") { + Solution solution; + CHECK(weekStrs[5] == solution.dayOfTheWeek(1, 1, 1971)); +} + +TEST_CASE("1-2 [test_1185]", "[test_1185]") { + Solution solution; + CHECK(weekStrs[5] == solution.dayOfTheWeek(15, 1, 1971)); +} + +TEST_CASE("1-3 [test_1185]", "[test_1185]") { + Solution solution; + CHECK(weekStrs[1] == solution.dayOfTheWeek(1, 2, 1971)); +} + +TEST_CASE("2-1 [test_1185]", "[test_1185]") { + Solution solution; + CHECK(weekStrs[6] == solution.dayOfTheWeek(31, 8, 2019)); +} + +TEST_CASE("2-2 [test_1185]", "[test_1185]") { + Solution solution; + CHECK(weekStrs[0] == solution.dayOfTheWeek(18, 7, 1999)); +} + +TEST_CASE("2-3 [test_1185]", "[test_1185]") { + Solution solution; + CHECK(weekStrs[0] == solution.dayOfTheWeek(15, 8, 1993)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1185_TEST_HPP + diff --git a/algorithm/math/leetcode_1185_test.hpp b/algorithm/math/leetcode_1185_test.hpp deleted file mode 100644 index 77af4454..00000000 --- a/algorithm/math/leetcode_1185_test.hpp +++ /dev/null @@ -1,57 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ -//@Tag 常识 -//@Tag 暴力 -//@Tag 先验知识 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1185_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1185_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_1185 { -using std::vector; - -struct leetcode_1185 { - static string dayOfTheWeek(int32_t day, int32_t month, int32_t year); -}; - -inline constexpr const std::array weekStrs - {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; - -using Catch::Matchers::Equals; - -TEST_CASE("1-1 [test_1185]", "[test_1185]") { - CHECK(weekStrs[5] == leetcode_1185::dayOfTheWeek(1, 1, 1971)); -} - -TEST_CASE("1-2 [test_1185]", "[test_1185]") { - CHECK(weekStrs[5] == leetcode_1185::dayOfTheWeek(15, 1, 1971)); -} - -TEST_CASE("1-3 [test_1185]", "[test_1185]") { - CHECK(weekStrs[1] == leetcode_1185::dayOfTheWeek(1, 2, 1971)); -} - -TEST_CASE("2-1 [test_1185]", "[test_1185]") { - CHECK(weekStrs[6] == leetcode_1185::dayOfTheWeek(31, 8, 2019)); -} - -TEST_CASE("2-2 [test_1185]", "[test_1185]") { - CHECK(weekStrs[0] == leetcode_1185::dayOfTheWeek(18, 7, 1999)); -} - -TEST_CASE("2-3 [test_1185]", "[test_1185]") { - CHECK(weekStrs[0] == leetcode_1185::dayOfTheWeek(15, 8, 1993)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1185_TEST_HPP - diff --git a/algorithm/math/leetcode_118_119.cpp b/algorithm/math/leetcode_118_119.cpp index c7aeefba..d95f887b 100644 --- a/algorithm/math/leetcode_118_119.cpp +++ b/algorithm/math/leetcode_118_119.cpp @@ -1,13 +1,14 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_118_119_test.hpp" +#include +#include +#include namespace leetcode_118 { +using std::vector; +#endif inline vector generate_help(vector vec, size_t order) { vector will_return{vec.cbegin(), vec.cend()}; @@ -18,42 +19,54 @@ inline vector generate_help(vector vec, size_t order) { return will_return; } -vector> leetcode_118::generate(int32_t numRows) { - vector> will_return{}; - vector temp{}; - for (int32_t i{0}; i < numRows; i++) { - temp = generate_help(temp, i); - will_return.emplace_back(temp); + +class Solution { +public: + vector> generate(int32_t numRows) { + vector> will_return{}; + vector temp{}; + for (int32_t i{0}; i < numRows; i++) { + temp = generate_help(temp, i); + will_return.emplace_back(temp); + } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } namespace leetcode_119 { +using std::vector; +#endif - -vector leetcode_119::getRow(int32_t rowIndex) { - vector will_return(rowIndex + 1, 1); - for (int32_t i{1}; i <= rowIndex; i++) { - for (int j = i - 1; j > 0; j--) { - will_return[j] += will_return[j - 1]; +class Solution119 { +public: + vector getRow(int32_t rowIndex) { + vector will_return(rowIndex + 1, 1); + for (int32_t i{1}; i <= rowIndex; i++) { + for (int j = i - 1; j > 0; j--) { + will_return[j] += will_return[j - 1]; + } } + return will_return; } - return will_return; -} -/** - * C^{N}_{M} = (m!) / ((n!) * (m-n)!)
- * C^{N+1}_{M} / C^{N}_{M} = (M-N)/(N+1)
- * C^{N+1}_{M} = ((M-N)/(N+1)) * C^{N}_{M} - * */ -vector leetcode_119::getRowN(int32_t rowIndex) { - vector will_return(rowIndex + 1, 1); - for (int32_t i{1}; i <= rowIndex; i++) { - const int64_t temp = static_cast(will_return[i - 1] ) * static_cast(rowIndex + 1 - i) / i; - will_return[i] = static_cast(temp); + /** + * C^{N}_{M} = (m!) / ((n!) * (m-n)!)
+ * C^{N+1}_{M} / C^{N}_{M} = (M-N)/(N+1)
+ * C^{N+1}_{M} = ((M-N)/(N+1)) * C^{N}_{M} + * */ + vector getRowN(int32_t rowIndex) { + vector will_return(rowIndex + 1, 1); + for (int32_t i{1}; i <= rowIndex; i++) { + const int64_t temp = static_cast(will_return[i - 1] ) * static_cast(rowIndex + 1 - i) / i; + will_return[i] = static_cast(temp); + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_118_119_test.hpp b/algorithm/math/leetcode_118_119_test.cpp similarity index 50% rename from algorithm/math/leetcode_118_119_test.hpp rename to algorithm/math/leetcode_118_119_test.cpp index 59de254f..7d7787ac 100644 --- a/algorithm/math/leetcode_118_119_test.hpp +++ b/algorithm/math/leetcode_118_119_test.cpp @@ -1,28 +1,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 数学问题 //@Plan 动态规划入门 Day12 //@Plan 数据结构入门 Day4 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_118_119_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_118_119_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_118_119_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_118_119_TEST_HPP + #include -#include -#include -#include +#include "leetcode_118_119.cpp" namespace leetcode_118 { -using std::vector; - -struct leetcode_118 { - static vector> generate(int32_t numRows); -}; using Catch::Matchers::Equals; @@ -35,7 +24,8 @@ TEST_CASE("1 [test_118]", "[test_118]") { {1, 3, 3, 1}, {1, 4, 6, 4, 1}, }; - CHECK_THAT(result, Equals(leetcode_118::generate(input))); + Solution solution; + CHECK_THAT(result, Equals(solution.generate(input))); } @@ -44,33 +34,29 @@ TEST_CASE("2 [test_118]", "[test_118]") { const vector> result{ {1}, }; - CHECK_THAT(result, Equals(leetcode_118::generate(input))); + Solution solution; + CHECK_THAT(result, Equals(solution.generate(input))); } } namespace leetcode_119 { -using std::vector; - -struct leetcode_119 { - static vector getRow(int32_t rowIndex); - - static vector getRowN(int32_t rowIndex); -}; using Catch::Matchers::Equals; TEST_CASE("1 [test_119]", "[test_119]") { static constexpr const auto input{3}; const vector result{1, 3, 3, 1}; - CHECK_THAT(result, Equals(leetcode_119::getRow(input))); - CHECK_THAT(result, Equals(leetcode_119::getRowN(input))); + Solution119 solution; + CHECK_THAT(result, Equals(solution.getRow(input))); + CHECK_THAT(result, Equals(solution.getRowN(input))); } TEST_CASE("2 [test_119]", "[test_119]") { static constexpr const auto input{1}; const vector result{1, 1}; - CHECK_THAT(result, Equals(leetcode_119::getRow(input))); - CHECK_THAT(result, Equals(leetcode_119::getRowN(input))); + Solution119 solution; + CHECK_THAT(result, Equals(solution.getRow(input))); + CHECK_THAT(result, Equals(solution.getRowN(input))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_118_119_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_118_119_TEST_HPP diff --git a/algorithm/math/leetcode_1252.cpp b/algorithm/math/leetcode_1252.cpp index 5a97c606..53402bce 100644 --- a/algorithm/math/leetcode_1252.cpp +++ b/algorithm/math/leetcode_1252.cpp @@ -1,42 +1,48 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_1252_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include #include namespace leetcode_1252 { +using std::vector; +#endif -int leetcode_1252::oddCells(int32_t m, int32_t n, const vector> &indices) { - vector ms(m, 0), ns(n, 0); - int32_t mOnes{0}, nOnes{0}; - for (const auto &indice: indices) { - assert(indice.size() == 2); - const auto mElement = indice[0]; - const auto nElement = indice[1]; - ms[mElement] = static_cast((ms[mElement] + 1) & 1); - ns[nElement] = static_cast((ns[nElement] + 1) & 1); - if (ms[mElement]) { - ++mOnes; - } else { - --mOnes; - } - if (ns[nElement]) { - ++nOnes; - } else { - --nOnes; +class Solution { +public: + int oddCells(int32_t m, int32_t n, const vector> &indices) { + vector ms(m, 0), ns(n, 0); + int32_t mOnes{0}, nOnes{0}; + for (const auto &indice: indices) { + assert(indice.size() == 2); + const auto mElement = indice[0]; + const auto nElement = indice[1]; + ms[mElement] = static_cast((ms[mElement] + 1) & 1); + ns[nElement] = static_cast((ns[nElement] + 1) & 1); + if (ms[mElement]) { + ++mOnes; + } else { + --mOnes; + } + if (ns[nElement]) { + ++nOnes; + } else { + --nOnes; + } } + // 在matrix中, row exchange or column exchange do not effect the 0,1 , + // so, we can move them to the same side: + // move the 0 (ms and ns) element to the leftest and uppest corner + // that will make left-upper and right-down corner is both 0 (one from 0+0,another from (1+1)%2 == 0) + // finally, the odds is the left-down and right-upper corner + // the row-one-element-size * column-zero-element-size + row-zero-element-size * column-one-element-size + return mOnes * (n - nOnes) + nOnes * (m - mOnes); } - // 在matrix中, row exchange or column exchange do not effect the 0,1 , - // so, we can move them to the same side: - // move the 0 (ms and ns) element to the leftest and uppest corner - // that will make left-upper and right-down corner is both 0 (one from 0+0,another from (1+1)%2 == 0) - // finally, the odds is the left-down and right-upper corner - // the row-one-element-size * column-zero-element-size + row-zero-element-size * column-one-element-size - return mOnes * (n - nOnes) + nOnes * (m - mOnes); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_1252_test.hpp b/algorithm/math/leetcode_1252_test.cpp similarity index 69% rename from algorithm/math/leetcode_1252_test.hpp rename to algorithm/math/leetcode_1252_test.cpp index d3f87725..47608a27 100644 --- a/algorithm/math/leetcode_1252_test.hpp +++ b/algorithm/math/leetcode_1252_test.cpp @@ -1,26 +1,14 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag 数学图像 //@Tag 归纳 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1252_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1252_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1252_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1252_TEST_HPP #include -#include -#include -#include +#include "leetcode_1252.cpp" namespace leetcode_1252 { -using std::vector; - -namespace leetcode_1252 { -int oddCells(int32_t m, int32_t n, const vector> &indices); -} using Catch::Matchers::Equals; @@ -29,7 +17,8 @@ TEST_CASE("1-1 [test_1252]", "[test_1252]") { const vector> indices{{1, 1}, {4, 5}, {1, 4}}; - const auto result = leetcode_1252::oddCells(m, n, indices); + Solution solution; + const auto result = solution.oddCells(m, n, indices); constexpr const auto output{15}; CHECK(output == result); } @@ -42,7 +31,8 @@ TEST_CASE("1-2 [test_1252]", "[test_1252]") { {1, 1}, {0, 1}, {1, 1}}; - const auto result = leetcode_1252::oddCells(m, n, indices); + Solution solution; + const auto result = solution.oddCells(m, n, indices); constexpr const auto output{6}; CHECK(output == result); } @@ -55,7 +45,8 @@ TEST_CASE("1-3 [test_1252]", "[test_1252]") { {1, 1}, {0, 0}, {1, 1}}; - const auto result = leetcode_1252::oddCells(m, n, indices); + Solution solution; + const auto result = solution.oddCells(m, n, indices); constexpr const auto output{0}; CHECK(output == result); } @@ -63,11 +54,12 @@ TEST_CASE("1-3 [test_1252]", "[test_1252]") { TEST_CASE("2-1 [test_1252]", "[test_1252]") { constexpr const auto m{48}, n{37}; const vector> indices{{40, 5}}; - const auto result = leetcode_1252::oddCells(m, n, indices); + Solution solution; + const auto result = solution.oddCells(m, n, indices); constexpr const auto output{83}; CHECK(output == result); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1252_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1252_TEST_HPP diff --git a/algorithm/math/leetcode_136.cpp b/algorithm/math/leetcode_136.cpp index 792f5d45..fe5676ea 100644 --- a/algorithm/math/leetcode_136.cpp +++ b/algorithm/math/leetcode_136.cpp @@ -1,20 +1,25 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_136_test.hpp" +#include +#include namespace leetcode_136 { +using std::vector; +#endif -int leetcode_136::singleNumber(const vector &nums) { - int will_return{0}; - for (const auto num: nums) { - will_return ^= num; +class Solution { +public: + int singleNumber(const vector &nums) { + int will_return{0}; + for (const auto num: nums) { + will_return ^= num; + } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_1362.cpp b/algorithm/math/leetcode_1362.cpp index 88f9d8f5..30fcb601 100644 --- a/algorithm/math/leetcode_1362.cpp +++ b/algorithm/math/leetcode_1362.cpp @@ -1,41 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_1362_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include #include #include +#include +#include +#include namespace leetcode_1362 { +using std::array; +#endif using num_type = int64_t; -array closetDivisors_inside(num_type num) { - assert(num > 0); - num_type a{0}, b{0}; - num_type min_diff{INT64_MAX}; - const auto sqrt_num = static_cast(std::sqrt(num)); - for (num_type i{sqrt_num}; i > 0; i--) { - if (num % i == 0) { - const auto j = num / i; - return {std::min(i,j), std::max(i,j)}; + +class Solution { + array closetDivisors_inside(num_type num) { + assert(num > 0); + num_type a{0}, b{0}; + num_type min_diff{std::numeric_limits::max()}; + const auto sqrt_num = static_cast(std::sqrt(num)); + for (num_type i{sqrt_num}; i > 0; i--) { + if (num % i == 0) { + const auto j = num / i; + return {std::min(i, j), std::max(i, j)}; + } } + return {0, 0}; + // 复杂度是 O(sqrt(num)) + // if num is 10^9, sqrt(num) is 10^5 } - return {0,0}; - // 复杂度是 O(sqrt(num)) - // if num is 10^9, sqrt(num) is 10^5 -} -// 将数字分解成多个质因数, 之后多个质因数之间组合, 找出差最小的两个 - -array leetcode_1362::closetDivisors(num_type num){ - const auto result1 = closetDivisors_inside(num + 1); - const auto result2 = closetDivisors_inside(num + 2); - if (std::abs(result1[0] - result1[1]) < std::abs(result2[0] - result2[1])) { - return result1; +public: + array closetDivisors(num_type num) { + const auto result1 = closetDivisors_inside(num + 1); + const auto result2 = closetDivisors_inside(num + 2); + if (std::abs(result1[0] - result1[1]) < std::abs(result2[0] - result2[1])) { + return result1; + } + return result2; } - return result2; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_1362_test.cpp b/algorithm/math/leetcode_1362_test.cpp new file mode 100644 index 00000000..941d5a54 --- /dev/null +++ b/algorithm/math/leetcode_1362_test.cpp @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag 数学 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1362_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1362_TEST_HPP + +#include +#include "leetcode_1362.cpp" + +namespace leetcode_1362 { + +using Catch::Matchers::Equals; + +TEST_CASE("1-1 [test_1362]", "[test_1362]") { + constexpr const auto input{8}; + constexpr const auto m{3}, n{3}; + Solution solution; + const std::array result = solution.closetDivisors(input); + CHECK(result[0] == m); + CHECK(result[1] == n); +} +TEST_CASE("1-2 [test_1362]", "[test_1362]") { + constexpr const auto input{123}; + constexpr const auto m{5}, n{25}; + Solution solution; + const std::array result = solution.closetDivisors(input); + CHECK(result[0] == m); + CHECK(result[1] == n); +} +TEST_CASE("1-3 [test_1362]", "[test_1362]") { + constexpr const auto input{999}; + constexpr const auto m{25}, n{40}; + Solution solution; + const std::array result = solution.closetDivisors(input); + CHECK(result[0] == m); + CHECK(result[1] == n); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1362_TEST_HPP + diff --git a/algorithm/math/leetcode_1362_test.hpp b/algorithm/math/leetcode_1362_test.hpp deleted file mode 100644 index 005e2660..00000000 --- a/algorithm/math/leetcode_1362_test.hpp +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ -//@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1362_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1362_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_1362 { -using std::vector; -using std::array; - -namespace leetcode_1362 { -array closetDivisors(int64_t num); -} - -using Catch::Matchers::Equals; - -TEST_CASE("1-1 [test_1362]", "[test_1362]") { - constexpr const auto input{8}; - constexpr const auto m{3}, n{3}; - const std::array result = leetcode_1362::closetDivisors(input); - constexpr const std::array correct{m, n}; - CHECK(result[0] == m); - CHECK(result[1] == n); -} -TEST_CASE("1-2 [test_1362]", "[test_1362]") { - constexpr const auto input{123}; - constexpr const auto m{5}, n{25}; - const std::array result = leetcode_1362::closetDivisors(input); - constexpr const std::array correct{m, n}; - CHECK(result[0] == m); - CHECK(result[1] == n); -} -TEST_CASE("1-3 [test_1362]", "[test_1362]") { - constexpr const auto input{999}; - constexpr const auto m{25}, n{40}; - const std::array result = leetcode_1362::closetDivisors(input); - constexpr const std::array correct{m, n}; - CHECK(result[0] == m); - CHECK(result[1] == n); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1362_TEST_HPP - diff --git a/algorithm/math/leetcode_1363.cpp b/algorithm/math/leetcode_1363.cpp index 6239f690..490e57bb 100644 --- a/algorithm/math/leetcode_1363.cpp +++ b/algorithm/math/leetcode_1363.cpp @@ -1,17 +1,21 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_1363_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include #include +#include +#include namespace leetcode_1363 { -inline string removeLastZeros(const string &input) { +using std::vector; +using std::string; +#endif + +static inline string removeLastZeros(const string &input) { if (input.empty()) { return input; } @@ -31,125 +35,128 @@ inline string removeLastZeros(const string &input) { return will_return; } -string leetcode_1363::largestMultipleOfThree(const vector &digits) { - const auto sums = std::accumulate(digits.begin(), digits.end(), 0); - if (sums % 3 == 0) { - string result{}; - vector sorted{digits}; - std::sort(sorted.begin(), sorted.end(), std::greater<>()); - for (const auto &digit: sorted) { - result += std::to_string(digit); +class Solution { +public: + string largestMultipleOfThree(const vector &digits) { + const auto sums = std::accumulate(digits.begin(), digits.end(), 0); + if (sums % 3 == 0) { + string result{}; + vector sorted{digits}; + std::sort(sorted.begin(), sorted.end(), std::greater<>()); + for (const auto &digit: sorted) { + result += std::to_string(digit); + } + return removeLastZeros(result); } - return removeLastZeros(result); - } - vector triples{}, triples_plusone{}, triples_plustwo{}; - for (const auto &digit: digits) { - if (digit % 3 == 0) { - triples.push_back(digit); - } else if (digit % 3 == 1) { - triples_plusone.push_back(digit); - } else { - triples_plustwo.push_back(digit); + vector triples{}, triples_plusone{}, triples_plustwo{}; + for (const auto &digit: digits) { + if (digit % 3 == 0) { + triples.push_back(digit); + } else if (digit % 3 == 1) { + triples_plusone.push_back(digit); + } else { + triples_plustwo.push_back(digit); + } } - } - std::sort(triples_plusone.begin(), triples_plusone.end(), std::greater<>()); - std::sort(triples_plustwo.begin(), triples_plustwo.end(), std::greater<>()); + std::sort(triples_plusone.begin(), triples_plusone.end(), std::greater<>()); + std::sort(triples_plustwo.begin(), triples_plustwo.end(), std::greater<>()); - if (sums % 3 == 1) { - if (triples_plusone.empty()) { - if (triples_plustwo.size() < 2) { - return {}; + if (sums % 3 == 1) { + if (triples_plusone.empty()) { + if (triples_plustwo.size() < 2) { + return {}; + } + triples_plustwo.pop_back(); + triples_plustwo.pop_back(); + } else { + triples_plusone.pop_back(); } - triples_plustwo.pop_back(); - triples_plustwo.pop_back(); - } else { - triples_plusone.pop_back(); - } - for (const auto plusone: triples_plusone) { - triples.push_back(plusone); - } - for (const auto plustwo: triples_plustwo) { - triples.push_back(plustwo); - } - std::sort(triples.begin(), triples.end(), std::greater<>()); - string result{}; - for (const auto &digit: triples) { - result += std::to_string(digit); - } - return removeLastZeros(result); - } else if (sums % 3 == 2) { - if (triples_plustwo.empty()) { - if (triples_plusone.size() < 2) { - return {}; + for (const auto plusone: triples_plusone) { + triples.push_back(plusone); } - triples_plusone.pop_back(); - triples_plusone.pop_back(); - } else { - triples_plustwo.pop_back(); - } - for (const auto plusone: triples_plusone) { - triples.push_back(plusone); - } - for (const auto plustwo: triples_plustwo) { - triples.push_back(plustwo); - } - std::sort(triples.begin(), triples.end(), std::greater<>()); - string result{}; - for (const auto &digit: triples) { - result += std::to_string(digit); + for (const auto plustwo: triples_plustwo) { + triples.push_back(plustwo); + } + std::sort(triples.begin(), triples.end(), std::greater<>()); + string result{}; + for (const auto &digit: triples) { + result += std::to_string(digit); + } + return removeLastZeros(result); + } else if (sums % 3 == 2) { + if (triples_plustwo.empty()) { + if (triples_plusone.size() < 2) { + return {}; + } + triples_plusone.pop_back(); + triples_plusone.pop_back(); + } else { + triples_plustwo.pop_back(); + } + for (const auto plusone: triples_plusone) { + triples.push_back(plusone); + } + for (const auto plustwo: triples_plustwo) { + triples.push_back(plustwo); + } + std::sort(triples.begin(), triples.end(), std::greater<>()); + string result{}; + for (const auto &digit: triples) { + result += std::to_string(digit); + } + return removeLastZeros(result); } - return removeLastZeros(result); + return {}; } - return {}; -} -namespace leetcode_1363::optimize { -string largestMultipleOfThree(const vector &digits) { - const auto sums = std::accumulate(digits.begin(), digits.end(), 0); - std::array cnt{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - for (const auto &digit: digits) { - cnt[digit] += 1; - } - if (sums % 3 == 1) { - if ((cnt[1] + cnt[4] + cnt[7]) >= 1) { - for (const auto num: {1, 4, 7}) { - cnt[num] -= 1; - break; - } - } else if ((cnt[2] + cnt[5] + cnt[8]) >= 2) { - for (uint8_t x{0}; x < 2u; x++) { - for (const auto num: {2, 5, 8}) { +}; + +class Optimize { +public: + string largestMultipleOfThree(const vector &digits) { + const auto sums = std::accumulate(digits.begin(), digits.end(), 0); + std::array cnt{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + for (const auto &digit: digits) { + cnt[digit] += 1; + } + if (sums % 3 == 1) { + if ((cnt[1] + cnt[4] + cnt[7]) >= 1) { + for (const auto num: {1, 4, 7}) { cnt[num] -= 1; break; } + } else if ((cnt[2] + cnt[5] + cnt[8]) >= 2) { + for (uint8_t x{0}; x < 2u; x++) { + for (const auto num: {2, 5, 8}) { + cnt[num] -= 1; + break; + } + } + } else { + return {}; } - } else { - return {}; - } - } else if (sums % 3 == 2) { - if ((cnt[2] + cnt[5] + cnt[8]) >= 1) { - for (const auto num: {2, 5, 8}) { - cnt[num] -= 1; - break; - } - } else if ((cnt[1] + cnt[4] + cnt[7]) >= 2) { - for (uint8_t x{0}; x < 2u; x++) { - for (const auto num: {1, 4, 7}) { + } else if (sums % 3 == 2) { + if ((cnt[2] + cnt[5] + cnt[8]) >= 1) { + for (const auto num: {2, 5, 8}) { cnt[num] -= 1; break; } + } else if ((cnt[1] + cnt[4] + cnt[7]) >= 2) { + for (uint8_t x{0}; x < 2u; x++) { + for (const auto num: {1, 4, 7}) { + cnt[num] -= 1; + break; + } + } + } else { + return {}; } - } else { - return {}; } + string result{}; + for (int32_t i{9}; i >= 0; i--) { + result += std::string(cnt[i], static_cast('0' + i)); + } + return leetcode_1363::removeLastZeros(result); } - string result{}; - for (int32_t i{9}; i >= 0; i--) { - result += std::string(cnt[i], static_cast('0' + i)); - } - return removeLastZeros(result); -} - -} - +}; } diff --git a/algorithm/math/leetcode_1363_test.cpp b/algorithm/math/leetcode_1363_test.cpp new file mode 100644 index 00000000..3555b179 --- /dev/null +++ b/algorithm/math/leetcode_1363_test.cpp @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag 数学 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1363_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1363_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_1363.cpp" + +namespace leetcode_1363 { +using Catch::Matchers::Equals; + +TEST_CASE("1-1 [test_1363]", "[test_1363]") { + const vector input{8, 1, 9}; + constexpr const char *const result{"981"}; + Solution solution; + Optimize optimize; + CHECK(result == solution.largestMultipleOfThree(input)); + CHECK(result == optimize.largestMultipleOfThree(input)); +} + +TEST_CASE("1-2 [test_1363]", "[test_1363]") { + const vector input{8, 6, 7, 1, 0}; + constexpr const char *const result{"8760"}; + Solution solution; + Optimize optimize; + CHECK(result == solution.largestMultipleOfThree(input)); + CHECK(result == optimize.largestMultipleOfThree(input)); +} + +TEST_CASE("1-3 [test_1363]", "[test_1363]") { + const vector input{1}; + constexpr const char *const result{""}; + Solution solution; + Optimize optimize; + CHECK(result == solution.largestMultipleOfThree(input)); + CHECK(result == optimize.largestMultipleOfThree(input)); +} + +TEST_CASE("1-4 [test_1363]", "[test_1363]") { + const vector input{0, 0, 0, 0, 0, 0}; + constexpr const char *const result{"0"}; + Solution solution; + Optimize optimize; + CHECK(result == solution.largestMultipleOfThree(input)); + CHECK(result == optimize.largestMultipleOfThree(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1363_TEST_HPP + diff --git a/algorithm/math/leetcode_1363_test.hpp b/algorithm/math/leetcode_1363_test.hpp deleted file mode 100644 index fe324516..00000000 --- a/algorithm/math/leetcode_1363_test.hpp +++ /dev/null @@ -1,58 +0,0 @@ - -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ -//@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1363_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1363_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_1363 { - -namespace leetcode_1363 { -string largestMultipleOfThree(const vector &digits); -namespace optimize{ -string largestMultipleOfThree(const vector &digits); -} -} - -using Catch::Matchers::Equals; - -TEST_CASE("1-1 [test_1363]", "[test_1363]") { - const vector input{8, 1, 9}; - constexpr const char *const result{"981"}; - CHECK(result == leetcode_1363::largestMultipleOfThree(input)); - CHECK(result == leetcode_1363::optimize::largestMultipleOfThree(input)); -} - -TEST_CASE("1-2 [test_1363]", "[test_1363]") { - const vector input{8, 6, 7, 1, 0}; - constexpr const char *const result{"8760"}; - CHECK(result == leetcode_1363::largestMultipleOfThree(input)); - CHECK(result == leetcode_1363::optimize::largestMultipleOfThree(input)); -} - -TEST_CASE("1-3 [test_1363]", "[test_1363]") { - const vector input{1}; - constexpr const char *const result{""}; - CHECK(result == leetcode_1363::largestMultipleOfThree(input)); - CHECK(result == leetcode_1363::optimize::largestMultipleOfThree(input)); -} - -TEST_CASE("1-4 [test_1363]", "[test_1363]") { - const vector input{0, 0, 0, 0, 0, 0}; - constexpr const char *const result{"0"}; - CHECK(result == leetcode_1363::largestMultipleOfThree(input)); - CHECK(result == leetcode_1363::optimize::largestMultipleOfThree(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1363_TEST_HPP - diff --git a/algorithm/math/leetcode_136_test.cpp b/algorithm/math/leetcode_136_test.cpp new file mode 100644 index 00000000..bcde5bf3 --- /dev/null +++ b/algorithm/math/leetcode_136_test.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_136_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_136_TEST_HPP + +#include +#include "leetcode_136.cpp" + +namespace leetcode_136 { + +using Catch::Matchers::Equals; + +TEST_CASE("1 [test_136]", "[test_136]") { + const vector input{3, 4, 3}; + static constexpr const auto result{4}; + Solution solution; + CHECK(result == solution.singleNumber(input)); +} + +TEST_CASE("2 [test_136]", "[test_136]") { + const vector input{1, 1, 2, 2, 3, 3, 4}; + static constexpr const auto result{4}; + Solution solution; + CHECK(result == solution.singleNumber(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_136_TEST_HPP + diff --git a/algorithm/math/leetcode_136_test.hpp b/algorithm/math/leetcode_136_test.hpp deleted file mode 100644 index 679d169c..00000000 --- a/algorithm/math/leetcode_136_test.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_136_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_136_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_136 { -using std::vector; - -struct leetcode_136 { - static int singleNumber(const vector &nums); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("1 [test_136]", "[test_136]") { - const vector input{3, 4, 3}; - static constexpr const auto result{4}; - CHECK(result == leetcode_136::singleNumber(input)); -} - -TEST_CASE("2 [test_136]", "[test_136]") { - const vector input{1, 1, 2, 2, 3, 3, 4}; - static constexpr const auto result{4}; - CHECK(result == leetcode_136::singleNumber(input)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_136_TEST_HPP - diff --git a/algorithm/math/leetcode_1390.cpp b/algorithm/math/leetcode_1390.cpp index b1a10f2a..f5efc531 100644 --- a/algorithm/math/leetcode_1390.cpp +++ b/algorithm/math/leetcode_1390.cpp @@ -1,36 +1,40 @@ - // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_1390_test.hpp" +#include +#include #include namespace leetcode_1390 { +using std::vector; +#endif -int32_t leetcode_1390::sumFourDivisors(const vector &nums) { - int32_t will_return{0}; - for (const auto &num: nums) { - int32_t count{0}, sum{0}; - for (int32_t i{1}; i <= std::sqrt(num) && count <= 4; ++i) { - if (num % i == 0) { - count += 1; - sum += i; - if (i * i != num) { +class Solution { +public: + int32_t sumFourDivisors(const vector &nums) { + int32_t will_return{0}; + for (const auto &num: nums) { + int32_t count{0}, sum{0}; + for (int32_t i{1}; i <= std::sqrt(num) && count <= 4; ++i) { + if (num % i == 0) { count += 1; - sum += num / i; + sum += i; + if (i * i != num) { + count += 1; + sum += num / i; + } } } + if (count == 4) { + will_return += sum; + } } - if (count == 4) { - will_return += sum; - } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_1390_test.hpp b/algorithm/math/leetcode_1390_test.cpp similarity index 50% rename from algorithm/math/leetcode_1390_test.hpp rename to algorithm/math/leetcode_1390_test.cpp index 49c91669..d38bb59b 100644 --- a/algorithm/math/leetcode_1390_test.hpp +++ b/algorithm/math/leetcode_1390_test.cpp @@ -1,40 +1,31 @@ - - // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1390_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1390_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1390_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1390_TEST_HPP #include #include #include #include +#include "leetcode_1390.cpp" namespace leetcode_1390 { - -namespace leetcode_1390 { -int32_t sumFourDivisors(const vector &nums); -} - using Catch::Matchers::Equals; TEST_CASE("1-1 [test_1390]", "[test_1390]") { const vector input{1, 1, 4, 5, 1, 4}; constexpr const auto result{0}; - CHECK(result == leetcode_1390::sumFourDivisors(input)); + Solution solution; + CHECK(result == solution.sumFourDivisors(input)); } TEST_CASE("1-2 [test_1390]", "[test_1390]") { const vector input{21, 4, 7}; constexpr const auto result{32}; - CHECK(result == leetcode_1390::sumFourDivisors(input)); + Solution solution; + CHECK(result == solution.sumFourDivisors(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1390_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1390_TEST_HPP diff --git a/algorithm/math/leetcode_1402.cpp b/algorithm/math/leetcode_1402.cpp index f44803c3..aadca0d4 100644 --- a/algorithm/math/leetcode_1402.cpp +++ b/algorithm/math/leetcode_1402.cpp @@ -1,51 +1,53 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_1402_test.hpp" +#include +#include #include +#include namespace leetcode_1402 { - -namespace leetcode_1402 { -int32_t maxSatisfaction(const vector &satisfaction) { - vector vec{}; - std::map> map{}; - for (const auto x: satisfaction) { - if (x >= 0) { - vec.push_back(x); - } else { - map[x]++; // 又或者可以从中心向两边分别遍历 - } - } - std::sort(vec.begin(), vec.end(), [](const auto a, const auto b) { return a < b; }); - const auto size{vec.size()}; - int32_t mul1{0},sum1{0}; - for (size_t i{size}; i > 0; i--) { - mul1 = mul1 + (vec[i - 1]) * static_cast(i); - sum1 = sum1 + (vec[i - 1]) ; - }// 后面排序根本就不会变化 - // 只有前面会变化, 但是排序是从小到大固定的, 问题只是到哪里停罢了 - for (const auto &[k, v]: map) { - for (int32_t i{0}; i < v; i++) { - const auto diff = k + sum1; - if (diff > 0) { - mul1 += diff; - sum1 += k; +using std::vector; +#endif + +class Solution { +public: + int32_t maxSatisfaction(const vector &satisfaction) { + vector vec{}; + std::map> map{}; + for (const auto x: satisfaction) { + if (x >= 0) { + vec.push_back(x); } else { - break; + map[x]++; // 又或者可以从中心向两边分别遍历 } } + std::sort(vec.begin(), vec.end(), [](const auto a, const auto b) { return a < b; }); + const auto size{vec.size()}; + int32_t mul1{0},sum1{0}; + for (size_t i{size}; i > 0; i--) { + mul1 = mul1 + (vec[i - 1]) * static_cast(i); + sum1 = sum1 + (vec[i - 1]) ; + }// 后面排序根本就不会变化 + // 只有前面会变化, 但是排序是从小到大固定的, 问题只是到哪里停罢了 + for (const auto &[k, v]: map) { + for (int32_t i{0}; i < v; i++) { + const auto diff = k + sum1; + if (diff > 0) { + mul1 += diff; + sum1 += k; + } else { + break; + } + } + } + return mul1; } - return mul1; -} - -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_1402_test.hpp b/algorithm/math/leetcode_1402_test.cpp similarity index 57% rename from algorithm/math/leetcode_1402_test.hpp rename to algorithm/math/leetcode_1402_test.cpp index adc8e3a0..eb5df8de 100644 --- a/algorithm/math/leetcode_1402_test.hpp +++ b/algorithm/math/leetcode_1402_test.cpp @@ -1,64 +1,59 @@ - - // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1402_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1402_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1402_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1402_TEST_HPP #include #include #include #include +#include "leetcode_1402.cpp" namespace leetcode_1402 { - -namespace leetcode_1402 { -int32_t maxSatisfaction(const vector &satisfaction); -} - using Catch::Matchers::Equals; TEST_CASE("1-1 [test_1402]", "[test_1402]") { const vector input{1, 1, 4, 5, 1, 4}; constexpr const auto result{72}; - CHECK(result == leetcode_1402::maxSatisfaction(input)); + Solution solution; + CHECK(result == solution.maxSatisfaction(input)); } TEST_CASE("1-2 [test_1402]", "[test_1402]") { const vector input{21, 4, 7}; constexpr const auto result{81}; - CHECK(result == leetcode_1402::maxSatisfaction(input)); + Solution solution; + CHECK(result == solution.maxSatisfaction(input)); } TEST_CASE("1-3 [test_1402]", "[test_1402]") { const vector input{-1, 0, 5, -8, -9}; constexpr const auto result{14}; - CHECK(result == leetcode_1402::maxSatisfaction(input)); + Solution solution; + CHECK(result == solution.maxSatisfaction(input)); } TEST_CASE("1-4 [test_1402]", "[test_1402]") { const vector input{2, 4, 3}; constexpr const auto result{20}; - CHECK(result == leetcode_1402::maxSatisfaction(input)); + Solution solution; + CHECK(result == solution.maxSatisfaction(input)); } TEST_CASE("1-5 [test_1402]", "[test_1402]") { const vector input{-1, -4, -5}; constexpr const auto result{0}; - CHECK(result == leetcode_1402::maxSatisfaction(input)); + Solution solution; + CHECK(result == solution.maxSatisfaction(input)); } TEST_CASE("1-6 [test_1402]", "[test_1402]") { const vector input{2, -2, -3, 1}; constexpr const auto result{6}; - CHECK(result == leetcode_1402::maxSatisfaction(input)); + Solution solution; + CHECK(result == solution.maxSatisfaction(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_1402_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_1402_TEST_HPP diff --git a/algorithm/math/leetcode_169.cpp b/algorithm/math/leetcode_169.cpp index 252de798..268eb7c4 100644 --- a/algorithm/math/leetcode_169.cpp +++ b/algorithm/math/leetcode_169.cpp @@ -1,53 +1,60 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_169_test.hpp" +#include +#include #include +#include namespace leetcode_169 { +using std::vector; using std::unordered_map; +#endif -int32_t leetcode_169::majorityElement(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size == 1) { - return nums[0]; - } - unordered_map umaps{}; - int32_t val{std::numeric_limits::min()}, count{0}; - for (const auto i: nums) { - umaps[i]++; - if (umaps[i] > count) { - count = umaps[i]; - val = i; +class Solution { +public: + int32_t majorityElement(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size == 1) { + return nums[0]; } + unordered_map umaps{}; + int32_t val{std::numeric_limits::min()}, count{0}; + for (const auto i: nums) { + umaps[i]++; + if (umaps[i] > count) { + count = umaps[i]; + val = i; + } + } + return val; } - return val; -} -int32_t leetcode_169::majorityElement2(const vector &nums) { - const auto nums_size{nums.size()}; - if (nums_size == 0) { - return -1; - } else if (nums_size == 1) { - return nums.front(); - } - int32_t val{std::numeric_limits::min()}, count{0}; - for (const auto i: nums) { - if (count > 0) { - if (val == i) { - count++; + int32_t majorityElement2(const vector &nums) { + const auto nums_size{nums.size()}; + if (nums_size == 0) { + return -1; + } else if (nums_size == 1) { + return nums.front(); + } + int32_t val{std::numeric_limits::min()}, count{0}; + for (const auto i: nums) { + if (count > 0) { + if (val == i) { + count++; + } else { + count--; + } } else { - count--; + count = 1; + val = i; } - } else { - count = 1; - val = i; } + return val; } - return val; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_169_test.cpp b/algorithm/math/leetcode_169_test.cpp new file mode 100644 index 00000000..0fb923ea --- /dev/null +++ b/algorithm/math/leetcode_169_test.cpp @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_169_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_169_TEST_HPP + +#include +#include "leetcode_169.cpp" + +namespace leetcode_169 { + +TEST_CASE("1 [test_169]", "[test_169]") { + const vector input{3, 4, 3}; + static constexpr const auto result{3}; + Solution solution; + CHECK(result == solution.majorityElement(input)); + CHECK(result == solution.majorityElement2(input)); +} + +TEST_CASE("2 [test_169]", "[test_169]") { + const vector input{1, 0, 1, 1, 0, 1}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.majorityElement(input)); + CHECK(result == solution.majorityElement2(input)); +} + +TEST_CASE("3 [test_169]", "[test_169]") { + const vector input{1}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.majorityElement(input)); + CHECK(result == solution.majorityElement2(input)); +} + +TEST_CASE("4 [test_169]", "[test_169]") { + const vector input{1, 1, 4, 5, 1, 4, 1, 9, 1}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.majorityElement(input)); + CHECK(result == solution.majorityElement2(input)); +} + +TEST_CASE("5 [test_169]", "[test_169]") { + const vector input{2, 2, 1, 1, 1, 2, 2}; + static constexpr const auto result{2}; + Solution solution; + CHECK(result == solution.majorityElement(input)); + CHECK(result == solution.majorityElement2(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_169_TEST_HPP + diff --git a/algorithm/math/leetcode_169_test.hpp b/algorithm/math/leetcode_169_test.hpp deleted file mode 100644 index 52cb3d97..00000000 --- a/algorithm/math/leetcode_169_test.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_169_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_169_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_169 { -using std::vector; - -struct leetcode_169 { - static int32_t majorityElement(const vector &nums); - - static int32_t majorityElement2(const vector &nums); -}; - -TEST_CASE("1 [test_169]", "[test_169]") { - const vector input{3, 4, 3}; - static constexpr const auto result{3}; - CHECK(result == leetcode_169::majorityElement(input)); - CHECK(result == leetcode_169::majorityElement2(input)); -} - -TEST_CASE("2 [test_169]", "[test_169]") { - const vector input{1, 0, 1, 1, 0, 1}; - static constexpr const auto result{1}; - CHECK(result == leetcode_169::majorityElement(input)); - CHECK(result == leetcode_169::majorityElement2(input)); -} - -TEST_CASE("3 [test_169]", "[test_169]") { - const vector input{1}; - static constexpr const auto result{1}; - CHECK(result == leetcode_169::majorityElement(input)); - CHECK(result == leetcode_169::majorityElement2(input)); -} - -TEST_CASE("4 [test_169]", "[test_169]") { - const vector input{1, 1, 4, 5, 1, 4, 1, 9, 1}; - static constexpr const auto result{1}; - CHECK(result == leetcode_169::majorityElement(input)); - CHECK(result == leetcode_169::majorityElement2(input)); -} - -TEST_CASE("5 [test_169]", "[test_169]") { - const vector input{2, 2, 1, 1, 1, 2, 2}; - static constexpr const auto result{2}; - CHECK(result == leetcode_169::majorityElement(input)); - CHECK(result == leetcode_169::majorityElement2(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_169_TEST_HPP - diff --git a/algorithm/math/leetcode_217.cpp b/algorithm/math/leetcode_217.cpp index 4d1b1879..94aa47bf 100644 --- a/algorithm/math/leetcode_217.cpp +++ b/algorithm/math/leetcode_217.cpp @@ -1,26 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_217_test.hpp" +#include +#include +#include #include namespace leetcode_217 { +using std::vector; using std::unordered_set; +#endif -bool leetcode_217::containsDuplicate(const vector &nums) { - unordered_set judges; - for (size_t i{0}, nums_size{nums.size()}; i < nums_size; i++) { - if (judges.count(nums[i]) != 0) { - return true; - } else { - judges.insert(nums[i]); +class Solution { +public: + bool containsDuplicate(const vector &nums) { + unordered_set judges; + for (size_t i{0}, nums_size{nums.size()}; i < nums_size; i++) { + if (judges.count(nums[i]) != 0) { + return true; + } else { + judges.insert(nums[i]); + } } + return false; } - return false; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_217_test.hpp b/algorithm/math/leetcode_217_test.cpp similarity index 51% rename from algorithm/math/leetcode_217_test.hpp rename to algorithm/math/leetcode_217_test.cpp index c31baaf7..69375320 100644 --- a/algorithm/math/leetcode_217_test.hpp +++ b/algorithm/math/leetcode_217_test.cpp @@ -1,62 +1,57 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 //@Plan 数据结构入门 Day1 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_217_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_217_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_217_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_217_TEST_HPP #include -#include -#include -#include +#include "leetcode_217.cpp" namespace leetcode_217 { -using std::vector; - -struct leetcode_217 { - static bool containsDuplicate(const vector &nums); -}; TEST_CASE("1 [test_217]", "[test_217]") { const vector input{3, 4, 3}; - CHECK(leetcode_217::containsDuplicate(input)); + Solution solution; + CHECK(solution.containsDuplicate(input)); } TEST_CASE("2 [test_217]", "[test_217]") { const vector input{1, 0, 1, 1, 0, 1}; - CHECK(leetcode_217::containsDuplicate(input)); + Solution solution; + CHECK(solution.containsDuplicate(input)); } TEST_CASE("3 [test_217]", "[test_217]") { const vector input{1}; - CHECK_FALSE(leetcode_217::containsDuplicate(input)); + Solution solution; + CHECK_FALSE(solution.containsDuplicate(input)); } TEST_CASE("4 [test_217]", "[test_217]") { const vector input{1, 1, 4, 5, 1, 4, 1, 9, 1}; - CHECK(leetcode_217::containsDuplicate(input)); + Solution solution; + CHECK(solution.containsDuplicate(input)); } TEST_CASE("5 [test_217]", "[test_217]") { const vector input{2, 2, 1, 1, 1, 2, 2}; - CHECK(leetcode_217::containsDuplicate(input)); + Solution solution; + CHECK(solution.containsDuplicate(input)); } TEST_CASE("6 [test_217]", "[test_217]") { const vector input{1, 2, 3, 4}; - CHECK_FALSE(leetcode_217::containsDuplicate(input)); + Solution solution; + CHECK_FALSE(solution.containsDuplicate(input)); } TEST_CASE("7 [test_217]", "[test_217]") { const vector input{1, 1, 1, 3, 3, 4, 3, 2, 4, 2}; - CHECK(leetcode_217::containsDuplicate(input)); + Solution solution; + CHECK(solution.containsDuplicate(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_217_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_217_TEST_HPP diff --git a/algorithm/math/leetcode_263.cpp b/algorithm/math/leetcode_263.cpp index dd41baee..8162d694 100644 --- a/algorithm/math/leetcode_263.cpp +++ b/algorithm/math/leetcode_263.cpp @@ -1,31 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_263_test.hpp" +#include namespace leetcode_263 { -bool isUgly2(const int32_t n) { - if (n <= 6) { - return true; - } else if (n % 2 == 0) { - return isUgly2(n >> 1); - } else if (n % 3 == 0) { - return isUgly2(n / 3); - } else if (n % 5 == 0) { - return isUgly2(n / 5); - } - return false; -} +#endif -bool leetcode_263::isUgly(int32_t n) { - if (n <= 0) { +class Solution { + private: + bool isUgly2(const int32_t n) { + if (n <= 6) { + return true; + } else if (n % 2 == 0) { + return isUgly2(n >> 1); + } else if (n % 3 == 0) { + return isUgly2(n / 3); + } else if (n % 5 == 0) { + return isUgly2(n / 5); + } return false; } - return isUgly2(n); -} + public: + bool isUgly(int32_t n) { + if (n <= 0) { + return false; + } + return isUgly2(n); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_263_test.hpp b/algorithm/math/leetcode_263_test.cpp similarity index 54% rename from algorithm/math/leetcode_263_test.hpp rename to algorithm/math/leetcode_263_test.cpp index da0adf43..3c9f2d0b 100644 --- a/algorithm/math/leetcode_263_test.hpp +++ b/algorithm/math/leetcode_263_test.cpp @@ -1,70 +1,69 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Math //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_263_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_263_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_263_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_263_TEST_HPP #include -#include -#include +#include "leetcode_263.cpp" namespace leetcode_263 { -struct leetcode_263 { - static bool isUgly(int32_t n); -}; - TEST_CASE("1 [test_263]", "[test_263]") { static constexpr const auto input{6}; - CHECK(leetcode_263::isUgly(input)); + Solution solution; + CHECK(solution.isUgly(input)); } TEST_CASE("2 [test_263]", "[test_263]") { static constexpr const auto input{8}; - CHECK(leetcode_263::isUgly(input)); + Solution solution; + CHECK(solution.isUgly(input)); } TEST_CASE("3 [test_263]", "[test_263]") { static constexpr const auto input{14}; - CHECK_FALSE(leetcode_263::isUgly(input)); + Solution solution; + CHECK_FALSE(solution.isUgly(input)); } TEST_CASE("4 [test_263]", "[test_263]") { static constexpr const auto input{1}; - CHECK(leetcode_263::isUgly(input)); + Solution solution; + CHECK(solution.isUgly(input)); } TEST_CASE("5 [test_263]", "[test_263]") { static constexpr const auto input{-1}; - CHECK_FALSE(leetcode_263::isUgly(input)); + Solution solution; + CHECK_FALSE(solution.isUgly(input)); } TEST_CASE("6 [test_263]", "[test_263]") { static constexpr const auto input{0}; - CHECK_FALSE(leetcode_263::isUgly(input)); + Solution solution; + CHECK_FALSE(solution.isUgly(input)); } TEST_CASE("7 [test_263]", "[test_263]") { static constexpr const auto input{std::numeric_limits::min()}; - CHECK_FALSE(leetcode_263::isUgly(input)); + Solution solution; + CHECK_FALSE(solution.isUgly(input)); } TEST_CASE("8 [test_263]", "[test_263]") { static constexpr const auto input{std::numeric_limits::max()}; - CHECK_FALSE(leetcode_263::isUgly(input)); + Solution solution; + CHECK_FALSE(solution.isUgly(input)); } TEST_CASE("9 [test_263]", "[test_263]") { static constexpr const auto input{233}; - CHECK_FALSE(leetcode_263::isUgly(input)); + Solution solution; + CHECK_FALSE(solution.isUgly(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_263_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_263_TEST_HPP diff --git a/algorithm/math/leetcode_268.cpp b/algorithm/math/leetcode_268.cpp index 1b9b8286..bcf3e077 100644 --- a/algorithm/math/leetcode_268.cpp +++ b/algorithm/math/leetcode_268.cpp @@ -1,17 +1,24 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_268_test.hpp" #include +#include +#include +#include namespace leetcode_268 { +using std::vector; +#endif -int32_t leetcode_268::missingNumber(const vector &nums) { - const auto nums_size = static_cast(nums.size()); - return nums_size * (nums_size + 1) / 2 - std::accumulate(nums.begin(), nums.end(), 0); -} +class Solution { +public: + int32_t missingNumber(const vector &nums) { + const auto nums_size = static_cast(nums.size()); + return nums_size * (nums_size + 1) / 2 - std::accumulate(nums.begin(), nums.end(), 0); + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_268_test.hpp b/algorithm/math/leetcode_268_test.cpp similarity index 50% rename from algorithm/math/leetcode_268_test.hpp rename to algorithm/math/leetcode_268_test.cpp index 27214722..31448c08 100644 --- a/algorithm/math/leetcode_268_test.hpp +++ b/algorithm/math/leetcode_268_test.cpp @@ -1,53 +1,45 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Math //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_268_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_268_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_268_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_268_TEST_HPP #include -#include -#include -#include +#include "leetcode_268.cpp" namespace leetcode_268 { -using std::vector; - -struct leetcode_268 { - static int32_t missingNumber(const vector &nums); -}; TEST_CASE("1 [test_268]", "[test_268]") { const vector input{3, 0, 1}; static constexpr const auto result{2}; - CHECK(result == leetcode_268::missingNumber(input)); + Solution solution; + CHECK(result == solution.missingNumber(input)); } TEST_CASE("2 [test_268]", "[test_268]") { const vector input{0, 1}; static constexpr const auto result{2}; - CHECK(result == leetcode_268::missingNumber(input)); + Solution solution; + CHECK(result == solution.missingNumber(input)); } TEST_CASE("3 [test_268]", "[test_268]") { const vector input{9, 6, 4, 2, 3, 5, 7, 0, 1}; static constexpr const auto result{8}; - CHECK(result == leetcode_268::missingNumber(input)); + Solution solution; + CHECK(result == solution.missingNumber(input)); } TEST_CASE("4 [test_268]", "[test_268]") { const vector input{0}; static constexpr const auto result{1}; - CHECK(result == leetcode_268::missingNumber(input)); + Solution solution; + CHECK(result == solution.missingNumber(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_268_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_268_TEST_HPP diff --git a/algorithm/math/leetcode_283.cpp b/algorithm/math/leetcode_283.cpp index 2604044b..87f69149 100644 --- a/algorithm/math/leetcode_283.cpp +++ b/algorithm/math/leetcode_283.cpp @@ -1,34 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_283_test.hpp" +#include +#include +#include +#include namespace leetcode_283 { +using std::vector; +#endif -void leetcode_283::moveZeroes(vector &nums) { - const auto nums_size{nums.size()}; - int64_t fill{0}; - for (size_t i{0}; i < nums_size; i++) { - if (nums[i] != 0) { - nums[fill] = nums[i]; - fill++; +class Solution { +public: + void moveZeroes(vector &nums) { + const auto nums_size{nums.size()}; + int64_t fill{0}; + for (size_t i{0}; i < nums_size; i++) { + if (nums[i] != 0) { + nums[fill] = nums[i]; + fill++; + } } + std::fill(nums.begin() + fill, nums.end(), 0); } - std::fill(nums.begin() + fill, nums.end(), 0); -} -void leetcode_283::moveZeroes2(vector &nums) { - const auto nums_size{nums.size()}; - for (size_t left{0}, right{0}; right < nums_size; right++) { - if (nums[right] != 0) { - std::swap(nums[left], nums[right]); - left++; + void moveZeroes2(vector &nums) { + const auto nums_size{nums.size()}; + for (size_t left{0}, right{0}; right < nums_size; right++) { + if (nums[right] != 0) { + std::swap(nums[left], nums[right]); + left++; + } } } -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_283_test.hpp b/algorithm/math/leetcode_283_test.cpp similarity index 56% rename from algorithm/math/leetcode_283_test.hpp rename to algorithm/math/leetcode_283_test.cpp index 0e7d3b11..265a394c 100644 --- a/algorithm/math/leetcode_283_test.hpp +++ b/algorithm/math/leetcode_283_test.cpp @@ -1,42 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Math //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_283_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_283_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_283_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_283_TEST_HPP #include #include #include #include +#include "leetcode_283.cpp" namespace leetcode_283 { using std::vector; - -struct leetcode_283 { - static void moveZeroes(vector &nums); - - static void moveZeroes2(vector &nums); -}; - using Catch::Matchers::Equals; TEST_CASE("1 [test_283]", "[test_283]") { vector input{0, 1, 0, 3, 12}; const vector result{1, 3, 12, 0, 0}; + Solution solution; WHEN("one node") { - leetcode_283::moveZeroes(input); + solution.moveZeroes(input); THEN("the values") { CHECK_THAT(result, Equals(input)); } }WHEN("one node") { - leetcode_283::moveZeroes2(input); + solution.moveZeroes2(input); THEN("the values") { CHECK_THAT(result, Equals(input)); } @@ -44,5 +34,5 @@ TEST_CASE("1 [test_283]", "[test_283]") { } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_283_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_283_TEST_HPP diff --git a/algorithm/math/leetcode_29.cpp b/algorithm/math/leetcode_29.cpp index 669668d7..88ad50cb 100644 --- a/algorithm/math/leetcode_29.cpp +++ b/algorithm/math/leetcode_29.cpp @@ -1,48 +1,52 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_29_test.hpp" +#include +#include namespace leetcode_29 { +#endif -int leetcode_29::divide(int32_t dividend, int32_t divisor) { - if (dividend == divisor) { - return 1; - } else if (divisor == std::numeric_limits::min()) { - return 0; - } else if (divisor == 1) { - return dividend; - } - int32_t will_return{0}, signs{1}; - if (dividend == std::numeric_limits::min()) { - if (divisor == -1) { - return std::numeric_limits::max(); +class Solution { +public: + int divide(int32_t dividend, int32_t divisor) { + if (dividend == divisor) { + return 1; + } else if (divisor == std::numeric_limits::min()) { + return 0; + } else if (divisor == 1) { + return dividend; } - will_return += 1; - // pay attention to the `sign` function - dividend += sign(divisor) * divisor; - } - signs *= sign(dividend) * sign(divisor); - dividend *= sign(dividend); - divisor *= sign(divisor); - while (dividend >= divisor) { - short temp{0}; - //cout << dividend << " " << divisor << endl; + int32_t will_return{0}, signs{1}; + if (dividend == std::numeric_limits::min()) { + if (divisor == -1) { + return std::numeric_limits::max(); + } + will_return += 1; + // pay attention to the `sign` function + dividend += sign(divisor) * divisor; + } + signs *= sign(dividend) * sign(divisor); + dividend *= sign(dividend); + divisor *= sign(divisor); while (dividend >= divisor) { - //cout << dividend << " " << temp << " " << divisor << endl; - if ((dividend >> 1) < (divisor << temp)) { - dividend -= (divisor << temp); - will_return += (1 << temp); - break; + short temp{0}; + //cout << dividend << " " << divisor << endl; + while (dividend >= divisor) { + //cout << dividend << " " << temp << " " << divisor << endl; + if ((dividend >> 1) < (divisor << temp)) { + dividend -= (divisor << temp); + will_return += (1 << temp); + break; + } + temp++; } - temp++; } + return will_return * signs; } - return will_return * signs; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_29_test.cpp b/algorithm/math/leetcode_29_test.cpp new file mode 100644 index 00000000..898c9e0d --- /dev/null +++ b/algorithm/math/leetcode_29_test.cpp @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_29_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_29_TEST_HPP + +#include +#include "leetcode_29.cpp" + +namespace leetcode_29 { + +TEST_CASE("1 [test _29]", "[test _29]") { + Solution solution; + CHECK(solution.divide(std::numeric_limits::min(), -1) == std::numeric_limits::max()); + CHECK(solution.divide(std::numeric_limits::min(), 1) == std::numeric_limits::min()); + CHECK(solution.divide(std::numeric_limits::min(), 2) == -1073741824); + CHECK(solution.divide(std::numeric_limits::min(), -2) == 1073741824); + CHECK(solution.divide(10, 3) == 3); + CHECK(solution.divide(7, -3) == -2); + CHECK(solution.divide(std::numeric_limits::min(), std::numeric_limits::min()) == 1); + CHECK(solution.divide(-1010369383, -2147483648) == 0); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_29_TEST_HPP diff --git a/algorithm/math/leetcode_29_test.hpp b/algorithm/math/leetcode_29_test.hpp deleted file mode 100644 index bd129be8..00000000 --- a/algorithm/math/leetcode_29_test.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_29_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_29_TEST_HPP - -#include -#include -#include - -namespace leetcode_29 { -struct leetcode_29 { - static int divide(int dividend, int divisor); -}; - -TEST_CASE("1 [test _29]", "[test _29]") { - CHECK(leetcode_29::divide(std::numeric_limits::min(), -1) == std::numeric_limits::max()); - CHECK(leetcode_29::divide(std::numeric_limits::min(), 1) == std::numeric_limits::min()); - CHECK(leetcode_29::divide(std::numeric_limits::min(), 2) == -1073741824); - CHECK(leetcode_29::divide(std::numeric_limits::min(), -2) == 1073741824); - CHECK(leetcode_29::divide(10, 3) == 3); - CHECK(leetcode_29::divide(7, -3) == -2); - CHECK(leetcode_29::divide(std::numeric_limits::min(), std::numeric_limits::min()) == 1); - CHECK(leetcode_29::divide(-1010369383, -2147483648) == 0); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_29_TEST_HPP diff --git a/algorithm/math/leetcode_338.cpp b/algorithm/math/leetcode_338.cpp index a8203ccd..8025eddd 100644 --- a/algorithm/math/leetcode_338.cpp +++ b/algorithm/math/leetcode_338.cpp @@ -1,25 +1,30 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_338_test.hpp" +#include +#include namespace leetcode_338 { +using std::vector; +#endif -vector leetcode_338::countBits(int32_t num) { - if (num == 0) { - return {0}; - } - vector will_return(num + 1, 0); - will_return[0] = 0; - will_return[1] = 1; - for (int32_t i{2}; i < num + 1; ++i) { - will_return[i] = will_return[i / 2] + i % 2; +class Solution { +public: + vector countBits(int32_t num) { + if (num == 0) { + return {0}; + } + vector will_return(num + 1, 0); + will_return[0] = 0; + will_return[1] = 1; + for (int32_t i{2}; i < num + 1; ++i) { + will_return[i] = will_return[i / 2] + i % 2; + } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_338_test.hpp b/algorithm/math/leetcode_338_test.cpp similarity index 64% rename from algorithm/math/leetcode_338_test.hpp rename to algorithm/math/leetcode_338_test.cpp index 54dba8bb..adc1425f 100644 --- a/algorithm/math/leetcode_338_test.hpp +++ b/algorithm/math/leetcode_338_test.cpp @@ -1,59 +1,55 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Math //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_338_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_338_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_338_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_338_TEST_HPP #include #include #include #include +#include "leetcode_338.cpp" namespace leetcode_338 { using std::vector; - -struct leetcode_338 { - static vector countBits(int32_t num); -}; - using Catch::Matchers::Equals; TEST_CASE("1 [test_338]", "[test_338]") { static constexpr const auto input{0}; const vector result{0}; - CHECK_THAT(result, Equals(leetcode_338::countBits(input))); + Solution solution; + CHECK_THAT(result, Equals(solution.countBits(input))); } TEST_CASE("2 [test_338]", "[test_338]") { static constexpr const auto input{1}; const vector result{0, 1}; - CHECK_THAT(result, Equals(leetcode_338::countBits(input))); + Solution solution; + CHECK_THAT(result, Equals(solution.countBits(input))); } TEST_CASE("3 [test_338]", "[test_338]") { static constexpr const auto input{2}; const vector result{0, 1, 1}; - CHECK_THAT(result, Equals(leetcode_338::countBits(input))); + Solution solution; + CHECK_THAT(result, Equals(solution.countBits(input))); } TEST_CASE("4 [test_338]", "[test_338]") { static constexpr const auto input{5}; const vector result{0, 1, 1, 2, 1, 2}; - CHECK_THAT(result, Equals(leetcode_338::countBits(input))); + Solution solution; + CHECK_THAT(result, Equals(solution.countBits(input))); } TEST_CASE("5 [test_338]", "[test_338]") { static constexpr const auto input{33}; const vector result{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2}; - CHECK_THAT(result, Equals(leetcode_338::countBits(input))); + Solution solution; + CHECK_THAT(result, Equals(solution.countBits(input))); } TEST_CASE("6 [test_338]", "[test_338]") { @@ -61,8 +57,9 @@ TEST_CASE("6 [test_338]", "[test_338]") { const vector result{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6}; - CHECK_THAT(result, Equals(leetcode_338::countBits(input))); + Solution solution; + CHECK_THAT(result, Equals(solution.countBits(input))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_338_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_338_TEST_HPP diff --git a/algorithm/math/leetcode_343.cpp b/algorithm/math/leetcode_343.cpp index 245c0183..d38a8b31 100644 --- a/algorithm/math/leetcode_343.cpp +++ b/algorithm/math/leetcode_343.cpp @@ -1,27 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_343_test.hpp" +#include +#include +#include namespace leetcode_343 { +using std::vector; +#endif -template -T leetcode_343::integerBreak(T n) { - if (n <= 3) { - return n - 1; - } - vector dp{0, 1, 2, 3}; - dp.resize(n + 4); - for (T i{4}; i <= n; i++) { - dp[i] = std::max(2 * dp[i - 2], 3 * dp[i - 3]); - // 根源在于要用接近e(2.71828)的那一个 - // 理论上拆分成e的和之后乘积最大化 +class Solution { +public: + template + T integerBreak(T n) { + if (n <= 3) { + return n - 1; + } + vector dp{0, 1, 2, 3}; + dp.resize(n + 4); + for (T i{4}; i <= n; i++) { + dp[i] = std::max(2 * dp[i - 2], 3 * dp[i - 3]); + // 根源在于要用接近e(2.71828)的那一个 + // 理论上拆分成e的和之后乘积最大化 + } + return dp[n]; } - return dp[n]; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_343_test.hpp b/algorithm/math/leetcode_343_test.cpp similarity index 57% rename from algorithm/math/leetcode_343_test.hpp rename to algorithm/math/leetcode_343_test.cpp index f9e8ef29..af794964 100644 --- a/algorithm/math/leetcode_343_test.hpp +++ b/algorithm/math/leetcode_343_test.cpp @@ -1,50 +1,45 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Math //@Tag 数学 //@Plan 动态规划入门 Day21 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_343_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_343_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_343_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_343_TEST_HPP #include #include #include +#include "leetcode_343.cpp" namespace leetcode_343 { -struct leetcode_343 { - template - static T integerBreak(T n); -}; - TEST_CASE("1 [test_343]", "[test_343]") { static constexpr const auto input{2}; static constexpr const auto result{1}; - CHECK(result == leetcode_343::integerBreak(input)); + Solution solution; + CHECK(result == solution.integerBreak(input)); } TEST_CASE("2 [test_343]", "[test_343]") { static constexpr const auto input{10}; static constexpr const auto result{36}; - CHECK(result == leetcode_343::integerBreak(input)); + Solution solution; + CHECK(result == solution.integerBreak(input)); } TEST_CASE("3 [test_343]", "[test_343]") { static constexpr const auto input{45}; static constexpr const auto result{14348907}; - CHECK(result == leetcode_343::integerBreak(input)); + Solution solution; + CHECK(result == solution.integerBreak(input)); } TEST_CASE("4 [test_343]", "[test_343]") { static constexpr const int64_t input{114}; static constexpr const int64_t result{1350851717672992089}; - CHECK(result == leetcode_343::integerBreak(input)); + Solution solution; + CHECK(result == solution.integerBreak(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_343_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_343_TEST_HPP diff --git a/algorithm/math/leetcode_372.cpp b/algorithm/math/leetcode_372.cpp index 92fd2b59..5b44558a 100644 --- a/algorithm/math/leetcode_372.cpp +++ b/algorithm/math/leetcode_372.cpp @@ -1,40 +1,51 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_372_test.hpp" +#include +#include +#include +#include +#include namespace leetcode_372 { -static constexpr const int32_t divided{1337}; +using std::vector; +#endif + +class Solution { +private: + static constexpr const int32_t divided{1337}; -static std::array power10(int32_t a) { - std::array power10{1, a % divided,}; - for (size_t i = 2; i < 10; i++) { - power10[i] = (power10[i - 1] * power10[1]) % divided; + static std::array power10(int32_t a) { + std::array power10{1, a % divided,}; + for (size_t i = 2; i < 10; i++) { + power10[i] = (power10[i - 1] * power10[1]) % divided; + } + return power10; } - return power10; -} -int32_t superPower(int32_t a, const vector &b, size_t length, const std::array &nums) { - CHECK((0 < length && length <= 2000)); // TODO, catch2 why do not support && in CHECK? - CHECK((0 <= b[length - 1] && b[length - 1] <= 9)); - int32_t will_return{nums[b[length - 1]]}; - if (length == 1) { - return will_return; + int32_t superPower(int32_t a, const vector &b, size_t length, const std::array &nums) { + assert((0 < length && length <= 2000)); + assert((0 <= b[length - 1] && b[length - 1] <= 9)); + int32_t will_return{nums[b[length - 1]]}; + if (length == 1) { + return will_return; + } + auto next = superPower(a, b, length - 1, nums); + const auto next2{(next * next) % divided}; + next = (next2 * next2) % divided; + next = (next * next) % divided; + return (will_return * ((next * next2) % divided)) % divided; } - auto next = superPower(a, b, length - 1, nums); - const auto next2{(next * next) % divided}; - next = (next2 * next2) % divided; - next = (next * next) % divided; - return (will_return * ((next * next2) % divided)) % divided; -} -int32_t leetcode_372::superPow(int32_t a, const vector &b) { - CHECK((1 <= a && a <= std::numeric_limits::max())); - std::array nums = power10(a); - return superPower(a, b, b.size(), nums); -} +public: + int32_t superPow(int32_t a, const vector &b) { + assert((1 <= a && a <= std::numeric_limits::max())); + std::array nums = power10(a); + return superPower(a, b, b.size(), nums); + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_372_test.hpp b/algorithm/math/leetcode_372_test.cpp similarity index 60% rename from algorithm/math/leetcode_372_test.hpp rename to algorithm/math/leetcode_372_test.cpp index e815bfa3..5d38732c 100644 --- a/algorithm/math/leetcode_372_test.hpp +++ b/algorithm/math/leetcode_372_test.cpp @@ -1,55 +1,51 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Math //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_372_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_372_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_372_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_372_TEST_HPP #include #include #include #include +#include "leetcode_372.cpp" namespace leetcode_372 { -struct leetcode_372 { - static int32_t superPow(int32_t a, const vector &b); -}; - TEST_CASE("1 [test_372]", "[test_372]") { static constexpr const auto inputA{2}; const vector inputB{3}; static constexpr const auto result{8}; - CHECK(result == leetcode_372::superPow(inputA, inputB)); + Solution solution; + CHECK(result == solution.superPow(inputA, inputB)); } TEST_CASE("2 [test_372]", "[test_372]") { static constexpr const auto inputA{2}; const vector inputB{1, 0}; static constexpr const auto result{1024}; - CHECK(result == leetcode_372::superPow(inputA, inputB)); + Solution solution; + CHECK(result == solution.superPow(inputA, inputB)); } TEST_CASE("3 [test_372]", "[test_372]") { static constexpr const auto inputA{1}; const vector inputB{1, 1, 4, 5, 1, 4}; static constexpr const auto result{1}; - CHECK(result == leetcode_372::superPow(inputA, inputB)); + Solution solution; + CHECK(result == solution.superPow(inputA, inputB)); } TEST_CASE("4 [test_372]", "[test_372]") { static constexpr const auto inputA{2147483647}; const vector inputB{2, 0, 0}; static constexpr const auto result{1198}; - CHECK(result == leetcode_372::superPow(inputA, inputB)); + Solution solution; + CHECK(result == solution.superPow(inputA, inputB)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_372_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_372_TEST_HPP diff --git a/algorithm/math/leetcode_401.cpp b/algorithm/math/leetcode_401.cpp index 255df38b..0131a838 100644 --- a/algorithm/math/leetcode_401.cpp +++ b/algorithm/math/leetcode_401.cpp @@ -1,109 +1,118 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_401_test.hpp" +#include +#include +#include +#include namespace leetcode_401 { +using std::vector; +using std::string; +#endif -string minutes_toString(const int x) { - string will_return; - if (x < 10) { - will_return.push_back('0'); - will_return.push_back(x + '0'); - } else { - will_return.push_back((x / 10) + '0'); - will_return.push_back((x % 10) + '0'); +class Solution { +private: + string minutes_toString(const int x) { + string will_return; + if (x < 10) { + will_return.push_back('0'); + will_return.push_back(x + '0'); + } else { + will_return.push_back((x / 10) + '0'); + will_return.push_back((x % 10) + '0'); + } + return will_return; } - return will_return; -} -vector hours_complex(const int x) { - switch (x) { - case 0: { - return {"0"}; - } - case 1: { - return {"1", "2", "4", "8"}; - } - case 2: { - return {"3", "5", "6", "9", "10"}; - } - case 3: { - return {"7", "11"}; - } - default: { - return {}; + vector hours_complex(const int x) { + switch (x) { + case 0: { + return {"0"}; + } + case 1: { + return {"1", "2", "4", "8"}; + } + case 2: { + return {"3", "5", "6", "9", "10"}; + } + case 3: { + return {"7", "11"}; + } + default: { + return {}; + } } } -} -vector minutes_complex(const int x) { - vector nums; - switch (x) { - case 0: { - return {"00"}; - } - case 1: { - return {"01", "02", "04", "08", "16", "32"}; - } - case 5: { - return {"31", "47", "55", "59"}; - } - case 2: { - for (int32_t i{0}; i < 6; i++) { - for (int32_t j{i + 1}; j < 6; j++) { - nums.push_back((1 << i) + (1 << j)); + vector minutes_complex(const int x) { + vector nums; + switch (x) { + case 0: { + return {"00"}; + } + case 1: { + return {"01", "02", "04", "08", "16", "32"}; + } + case 5: { + return {"31", "47", "55", "59"}; + } + case 2: { + for (int32_t i{0}; i < 6; i++) { + for (int32_t j{i + 1}; j < 6; j++) { + nums.push_back((1 << i) + (1 << j)); + } } + break; } - break; - } - case 3: { - for (int32_t i{0}; i < 6; i++) { - for (int32_t j{i + 1}; j < 6; j++) { - for (int32_t k{j + 1}; k < 6; k++) { - nums.push_back((1 << i) + (1 << j) + (1 << k)); + case 3: { + for (int32_t i{0}; i < 6; i++) { + for (int32_t j{i + 1}; j < 6; j++) { + for (int32_t k{j + 1}; k < 6; k++) { + nums.push_back((1 << i) + (1 << j) + (1 << k)); + } } } + break; } - break; - } - case 4: { - for (int32_t i{0}; i < 6; i++) { - for (int32_t j{i + 1}; j < 6; j++) { - if (63 - (1 << i) - (1 << j) < 60) { - nums.push_back(63 - (1 << i) - (1 << j)); + case 4: { + for (int32_t i{0}; i < 6; i++) { + for (int32_t j{i + 1}; j < 6; j++) { + if (63 - (1 << i) - (1 << j) < 60) { + nums.push_back(63 - (1 << i) - (1 << j)); + } } } + break; + } + default: { + return {}; } - break; } - default: { - return {}; + vector will_return; + for (auto i: nums) { + will_return.push_back(minutes_toString(i)); } + return will_return; } - vector will_return; - for (auto i: nums) { - will_return.push_back(minutes_toString(i)); - } - return will_return; -} - -vector leetcode_401::readBinaryWatch(const int32_t num) { - vector will_return; - for (int32_t k{0}; k <= std::min(4, num); k++) { - vector hours = hours_complex(k); - vector minutes = minutes_complex(num - k); - for (const auto &i: hours) { - for (const auto &j: minutes) { - will_return.push_back(i + ":" + j); +public: + vector readBinaryWatch(const int32_t num) { + vector will_return; + for (int32_t k{0}; k <= std::min(4, num); k++) { + vector hours = hours_complex(k); + vector minutes = minutes_complex(num - k); + for (const auto &i: hours) { + for (const auto &j: minutes) { + will_return.push_back(i + ":" + j); + } } } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_401_test.hpp b/algorithm/math/leetcode_401_test.cpp similarity index 52% rename from algorithm/math/leetcode_401_test.hpp rename to algorithm/math/leetcode_401_test.cpp index da4d39da..442d388e 100644 --- a/algorithm/math/leetcode_401_test.hpp +++ b/algorithm/math/leetcode_401_test.cpp @@ -1,28 +1,19 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Math //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_401_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_401_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_401_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_401_TEST_HPP #include #include #include #include +#include "leetcode_401.cpp" namespace leetcode_401 { using std::vector; - -struct leetcode_401 { - static vector readBinaryWatch(int32_t num); -}; - using Catch::Matchers::UnorderedEquals; TEST_CASE("1 [test_401]", "[test_401]") { @@ -30,9 +21,10 @@ TEST_CASE("1 [test_401]", "[test_401]") { const vector result{ "0:01", "0:02", "0:04", "0:08", "0:16", "0:32", "1:00", "2:00", "4:00", "8:00" }; - CHECK_THAT(result, UnorderedEquals(leetcode_401::readBinaryWatch(input))); + Solution solution; + CHECK_THAT(result, UnorderedEquals(solution.readBinaryWatch(input))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_401_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_401_TEST_HPP diff --git a/algorithm/math/leetcode_414.cpp b/algorithm/math/leetcode_414.cpp index 8c101f07..a501320c 100644 --- a/algorithm/math/leetcode_414.cpp +++ b/algorithm/math/leetcode_414.cpp @@ -1,38 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_414_test.hpp" +#include +#include +#include +#include #include +#include namespace leetcode_414 { using std::unordered_set; +using std::vector; +#endif -int32_t leetcode_414::thirdMax(const vector &nums) { - unordered_set uset; - for (const auto i: nums) { - uset.insert(i); - } - if (uset.size() < 3) { - return *(std::max_element(uset.cbegin(), uset.cend())); - } - std::array fst{std::numeric_limits::min(), std::numeric_limits::min(), - std::numeric_limits::min()}; - for (const auto i: uset) { - if (i > fst[2] && i != fst[1] && i != fst[0]) { - fst[2] = i; +class Solution { + public: + int32_t thirdMax(const vector &nums) { + unordered_set uset; + for (const auto i : nums) { + uset.insert(i); } - if (fst[2] > fst[1]) { - std::swap(fst[1], fst[2]); + if (uset.size() < 3) { + return *(std::max_element(uset.cbegin(), uset.cend())); } - if (fst[1] > fst[0]) { - std::swap(fst[0], fst[1]); + std::array fst{std::numeric_limits::min(), + std::numeric_limits::min(), + std::numeric_limits::min()}; + for (const auto i : uset) { + if (i > fst[2] && i != fst[1] && i != fst[0]) { + fst[2] = i; + } + if (fst[2] > fst[1]) { + std::swap(fst[1], fst[2]); + } + if (fst[1] > fst[0]) { + std::swap(fst[0], fst[1]); + } } + return fst[2]; } - return fst[2]; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_414_test.hpp b/algorithm/math/leetcode_414_test.cpp similarity index 56% rename from algorithm/math/leetcode_414_test.hpp rename to algorithm/math/leetcode_414_test.cpp index 647a55e6..be7cfec3 100644 --- a/algorithm/math/leetcode_414_test.hpp +++ b/algorithm/math/leetcode_414_test.cpp @@ -1,51 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Math //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_414_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_414_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_414_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_414_TEST_HPP #include #include #include #include +#include "leetcode_414.cpp" namespace leetcode_414 { -struct leetcode_414 { - static int32_t thirdMax(const vector &nums); -}; - TEST_CASE("1 [test_414]", "[test_414]") { const vector input{3, 2, 1}; static constexpr const auto result{1}; - CHECK(result == leetcode_414::thirdMax(input)); + Solution solution; + CHECK(result == solution.thirdMax(input)); } TEST_CASE("2 [test_414]", "[test_414]") { const vector input{2, 1}; static constexpr const auto result{2}; - CHECK(result == leetcode_414::thirdMax(input)); + Solution solution; + CHECK(result == solution.thirdMax(input)); } TEST_CASE("3 [test_414]", "[test_414]") { const vector input{1, 1, 4, 5, 1, 4}; static constexpr const auto result{1}; - CHECK(result == leetcode_414::thirdMax(input)); + Solution solution; + CHECK(result == solution.thirdMax(input)); } TEST_CASE("4 [test_414]", "[test_414]") { const vector input{1, 9, 1, 9, 8, 1, 0}; static constexpr const auto result{1}; - CHECK(result == leetcode_414::thirdMax(input)); + Solution solution; + CHECK(result == solution.thirdMax(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_414_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_414_TEST_HPP diff --git a/algorithm/math/leetcode_43.cpp b/algorithm/math/leetcode_43.cpp index b86facb2..7f3e4f6c 100644 --- a/algorithm/math/leetcode_43.cpp +++ b/algorithm/math/leetcode_43.cpp @@ -1,41 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_43_test.hpp" #include +#include +#include +#include +#include namespace leetcode_43 { +using std::string; +using std::vector; +#endif - -string leetcode_43::multiply(const string &num1, const string &num2) { - static constexpr const char zeroC{'0'}; - static constexpr const char *const zero{"0"}; - if (num1 == zero || num2 == zero) { - return zero; - } - const auto num1_size{num1.size()}, num2_size{num2.size()}, sum_size{num1_size + num2_size}; - vector sum(sum_size, 0); - for (size_t i{num2_size}; i > 0; i--) { - for (size_t j{num1_size}; j > 0; j--) { - const auto plus{i + j - 1}; - const int32_t mul = static_cast(num2[i - 1] - zeroC) * static_cast(num1[j - 1] - zeroC); - //cout << i << " " << j << " " << mul << endl; - sum[plus - 1] += (mul + sum[plus]) / 10; - sum[plus] = (mul + sum[plus]) % 10; +class Solution { +public: + string multiply(const string &num1, const string &num2) { + static constexpr const char zeroC{'0'}; + static constexpr const char *const zero{"0"}; + if (num1 == zero || num2 == zero) { + return zero; } + const auto num1_size{num1.size()}, num2_size{num2.size()}, sum_size{num1_size + num2_size}; + vector sum(sum_size, 0); + for (size_t i{num2_size}; i > 0; i--) { + for (size_t j{num1_size}; j > 0; j--) { + const auto plus{i + j - 1}; + const int32_t mul = static_cast(num2[i - 1] - zeroC) * static_cast(num1[j - 1] - zeroC); + //cout << i << " " << j << " " << mul << endl; + sum[plus - 1] += (mul + sum[plus]) / 10; + sum[plus] = (mul + sum[plus]) % 10; + } + } + string will_return; + will_return.reserve(sum.size()); + for (size_t i = std::find_if(sum.begin(), sum.end(), [](int x) { return x != 0; }) - sum.begin(); + i < sum_size; i++) { + will_return += static_cast(sum[i] + static_cast(zeroC)); + } + return will_return; } - string will_return; - will_return.reserve(sum.size()); - for (size_t i = std::find_if(sum.begin(), sum.end(), [](int x) { return x != 0; }) - sum.begin(); - i < sum_size; i++) { - will_return += static_cast(sum[i] + static_cast(zeroC)); - } - return will_return; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_43_test.hpp b/algorithm/math/leetcode_43_test.cpp similarity index 52% rename from algorithm/math/leetcode_43_test.hpp rename to algorithm/math/leetcode_43_test.cpp index 6a39dfb9..41c15652 100644 --- a/algorithm/math/leetcode_43_test.hpp +++ b/algorithm/math/leetcode_43_test.cpp @@ -1,52 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_43_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_43_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_43_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_43_TEST_HPP #include -#include -#include -#include +#include "leetcode_43.cpp" namespace leetcode_43 { -struct leetcode_43 { - static string multiply(const string &num1, const string &num2); -}; TEST_CASE("1 [test _43]", "[test _43]") { const string num1{"9"}; const string num2{"9"}; const string result{"81"}; - CHECK(result == leetcode_43::multiply(num1, num2)); + Solution solution; + CHECK(result == solution.multiply(num1, num2)); } TEST_CASE("2 [test _43]", "[test _43]") { const string num1{"2"}; const string num2{"3"}; const string result{"6"}; - CHECK(result == leetcode_43::multiply(num1, num2)); + Solution solution; + CHECK(result == solution.multiply(num1, num2)); } TEST_CASE("3 [test _43]", "[test _43]") { const string num1{"123"}; const string num2{"456"}; const string result{"56088"}; - CHECK(result == leetcode_43::multiply(num1, num2)); + Solution solution; + CHECK(result == solution.multiply(num1, num2)); } TEST_CASE("4 [test _43]", "[test _43]") { const string num1{"114514"}; const string num2{"1919810"}; const string result{"219845122340"}; - CHECK(result == leetcode_43::multiply(num1, num2)); + Solution solution; + CHECK(result == solution.multiply(num1, num2)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_43_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_43_TEST_HPP diff --git a/algorithm/math/leetcode_461.cpp b/algorithm/math/leetcode_461.cpp index d65dfbe3..c959dbaf 100644 --- a/algorithm/math/leetcode_461.cpp +++ b/algorithm/math/leetcode_461.cpp @@ -1,20 +1,23 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_461_test.hpp" +#include namespace leetcode_461 { +#endif -int32_t leetcode_461::hammingDistance(int32_t x, int32_t y) { - int32_t count{0}; - for (int32_t temp{x ^ y}; temp != 0; temp = temp >> 1) { - count += (temp & 1); +class Solution { +public: + int32_t hammingDistance(int32_t x, int32_t y) { + int32_t count{0}; + for (int32_t temp{x ^ y}; temp != 0; temp = temp >> 1) { + count += (temp & 1); + } + return count; } - return count; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_461_test.cpp b/algorithm/math/leetcode_461_test.cpp new file mode 100644 index 00000000..12f86df8 --- /dev/null +++ b/algorithm/math/leetcode_461_test.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag Math +//@Tag 数学 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_461_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_461_TEST_HPP + +#include +#include +#include +#include "leetcode_461.cpp" + +namespace leetcode_461 { + +TEST_CASE("1 [test_461]", "[test_461]") { + static constexpr const auto inputX{1}, inputY{4}; + static constexpr const auto result{2}; + Solution solution; + CHECK(result == solution.hammingDistance(inputX, inputY)); +} + +TEST_CASE("2 [test_461]", "[test_461]") { + static constexpr const auto inputX{3}, inputY{1}; + static constexpr const auto result{1}; + Solution solution; + CHECK(result == solution.hammingDistance(inputX, inputY)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_461_TEST_HPP + diff --git a/algorithm/math/leetcode_461_test.hpp b/algorithm/math/leetcode_461_test.hpp deleted file mode 100644 index b5dd001f..00000000 --- a/algorithm/math/leetcode_461_test.hpp +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag Math -//@Tag 数学 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_461_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_461_TEST_HPP - -#include -#include -#include - -namespace leetcode_461 { - -struct leetcode_461 { - static int32_t hammingDistance(int32_t x, int32_t y); -}; - -TEST_CASE("1 [test_461]", "[test_461]") { - static constexpr const auto inputX{1}, inputY{4}; - static constexpr const auto result{2}; - CHECK(result == leetcode_461::hammingDistance(inputX, inputY)); -} - -TEST_CASE("2 [test_461]", "[test_461]") { - static constexpr const auto inputX{3}, inputY{1}; - static constexpr const auto result{1}; - CHECK(result == leetcode_461::hammingDistance(inputX, inputY)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_461_TEST_HPP - diff --git a/algorithm/math/leetcode_50.cpp b/algorithm/math/leetcode_50.cpp index e889360f..0e87e561 100644 --- a/algorithm/math/leetcode_50.cpp +++ b/algorithm/math/leetcode_50.cpp @@ -1,56 +1,72 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_50_test.hpp" +#include +#include +#include +#include +#include +#include +#include +#include namespace leetcode_50 { +using std::vector; +#endif -double quick_pow(vector &pows, double num, int32_t n) { - CHECK((0 <= n && n < 32)); - CHECK((pows.size() == 32)); +class Solution { +private: + double quick_pow(vector &pows, double num, int32_t n) { +#ifdef ALGORITHM_TEST_MACRO + CHECK((0 <= n && n < 32)); + CHECK((pows.size() == 32)); +#endif - if (pows[n] != 0) { - return pows[n]; + if (pows[n] != 0) { + return pows[n]; + } + pows[n - 1] = quick_pow(pows, num, n - 1); + return pows[n - 1] * pows[n - 1]; } - pows[n - 1] = quick_pow(pows, num, n - 1); - return pows[n - 1] * pows[n - 1]; -} -double leetcode_50::myPow(double x, int32_t n) { - CHECK((-100 < x && x < 100)); - CHECK((std::numeric_limits::min() <= n && n <= std::numeric_limits::max())); - if (0 == n) { - return 1; - } else if (1 == x || 0 == x) { - return x; - } else if (n < 0 && n != std::numeric_limits::min()) { - return 1 / myPow(x, -n); - } else if (std::numeric_limits::min() == n) { - return 1 / (myPow(x, std::numeric_limits::max()) * x); - } - vector pows(32, 0); - pows[0] = x; - pows[1] = x * x; - vector nums{}; - nums.reserve(32); - for (short i{1}; i <= 32; i++) { - if ((n & (1 << (i - 1))) > 0) { - nums.push_back(i); +public: + double myPow(double x, int32_t n) { +#ifdef ALGORITHM_TEST_MACRO + CHECK((-100 < x && x < 100)); + CHECK((std::numeric_limits::min() <= n && n <= std::numeric_limits::max())); +#endif + if (0 == n) { + return 1; + } else if (1 == x || 0 == x) { + return x; + } else if (n < 0 && n != std::numeric_limits::min()) { + return 1 / myPow(x, -n); + } else if (std::numeric_limits::min() == n) { + return 1 / (myPow(x, std::numeric_limits::max()) * x); } + vector pows(32, 0); + pows[0] = x; + pows[1] = x * x; + vector nums{}; + nums.reserve(32); + for (short i{1}; i <= 32; i++) { + if ((n & (1 << (i - 1))) > 0) { + nums.push_back(i); + } + } + std::sort(nums.begin(), nums.end(), std::less<>()); + for (const auto i: nums) { + quick_pow(pows, x, i); + } + double will_return{1.0f}; + for (const auto i: nums) { + will_return *= pows[i - 1]; + } + return will_return; } - std::sort(nums.begin(), nums.end(), std::less<>()); - for (const auto i: nums) { - quick_pow(pows, x, i); - } - double will_return{1.0f}; - for (const auto i: nums) { - will_return *= pows[i - 1]; - } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_50_test.hpp b/algorithm/math/leetcode_50_test.cpp similarity index 56% rename from algorithm/math/leetcode_50_test.hpp rename to algorithm/math/leetcode_50_test.cpp index 685c116b..5b1523ad 100644 --- a/algorithm/math/leetcode_50_test.hpp +++ b/algorithm/math/leetcode_50_test.cpp @@ -1,26 +1,15 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_50_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_50_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_50_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_50_TEST_HPP #include -#include - -#include -#include +#include "leetcode_50.cpp" namespace leetcode_50 { -struct leetcode_50 { - static double myPow(double x, int n); -}; using Catch::Approx; static constexpr const auto epsilon{1e-3}; @@ -29,28 +18,32 @@ TEST_CASE("1 [test_50]", "[test_50]") { static constexpr const auto x{2.00000}; static constexpr const auto n{-2147483648}; static constexpr const auto result{0.0}; - CHECK(Approx(result).epsilon(epsilon) == leetcode_50::myPow(x, n)); + Solution solution; + CHECK(Approx(result).epsilon(epsilon) == solution.myPow(x, n)); } TEST_CASE("2 [test_50]", "[test_50]") { static constexpr const auto x{2.00000}; static constexpr const auto n{10}; static constexpr const auto result{1024.0}; - CHECK(Approx(result).epsilon(epsilon) == leetcode_50::myPow(x, n)); + Solution solution; + CHECK(Approx(result).epsilon(epsilon) == solution.myPow(x, n)); } TEST_CASE("3 [test_50]", "[test_50]") { static constexpr const auto x{2.00000}; static constexpr const auto n{-2}; static constexpr const auto result{0.25}; - CHECK(Approx(result).epsilon(epsilon) == leetcode_50::myPow(x, n)); + Solution solution; + CHECK(Approx(result).epsilon(epsilon) == solution.myPow(x, n)); } TEST_CASE("4 [test_50]", "[test_50]") { static constexpr const auto x{2.1}; static constexpr const auto n{3}; static constexpr const auto result{9.261}; - CHECK(Approx(result).epsilon(epsilon) == leetcode_50::myPow(x, n)); + Solution solution; + CHECK(Approx(result).epsilon(epsilon) == solution.myPow(x, n)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_50_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_50_TEST_HPP diff --git a/algorithm/math/leetcode_60.cpp b/algorithm/math/leetcode_60.cpp index f4da01c1..e1da9a82 100644 --- a/algorithm/math/leetcode_60.cpp +++ b/algorithm/math/leetcode_60.cpp @@ -1,76 +1,94 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_60_test.hpp" +#include +#include +#include +#include #include +#include +#include namespace leetcode_60 { -constexpr int32_t facts(int32_t t) { - int32_t will_return{1}; - for (int32_t x{1}; x <= t; x++) { - will_return *= x; - } - return will_return; -}// c++ 14 constexpr, count facts in complier time. -string leetcode_60::getPermutation(int32_t n, int32_t k) { - vector fact(10, 1); - for (int32_t i{0}; i < 10; i++) { - fact[i] = facts(i); - } - assert(fact[n] >= k && k >= 1); - assert(1 <= n && n <= 9); - vector nums; - char will_return[10]{'\0'}; - int32_t k_count = k - 1; - vector ordres; - for (int32_t i{1}; i <= n; i++) { - nums.push_back(i); - } - for (int32_t i{0}; i < n; i++) { - int32_t temp = k_count / fact[n - 1 - i]; - ordres.push_back(temp); - k_count = k_count % fact[n - 1 - i]; - will_return[i] = '0' + nums[ordres[i]]; - nums.erase(std::remove(nums.begin(), nums.end(), nums[ordres[i]]), nums.end()); - } - return will_return; -} +using std::string; +using std::vector; +#endif -string getPermutation_rec_in(int32_t n, int32_t k, vector nums) { - vector fact(10, 1); - for (int32_t i{0}; i < 10; i++) { - fact[i] = facts(i); - } - assert(fact[n] >= k && k >= 0); - assert(n >= 1 && n <= 9); - char will_return[2]; - memset(will_return, '\0', sizeof(char) * 2); - if (1 == n) { - will_return[0] = '0' + nums[0]; +class Solution { + private: + constexpr int32_t facts(int32_t t) { + int32_t will_return{1}; + for (int32_t x{1}; x <= t; x++) { + will_return *= x; + } return will_return; - } - will_return[0] = '0' + nums[k / fact[n - 1]]; - nums.erase(std::remove(nums.begin(), nums.end(), will_return[0] - '0'), nums.end()); - return will_return + getPermutation_rec_in(n - 1, k % fact[n - 1], nums); -} + } // c++ 14 constexpr, count facts in complier time. -string leetcode_60::getPermutation_rec_out(int32_t n, int32_t k) { - vector fact(10, 1); - for (int32_t i{0}; i < 10; i++) { - fact[i] = facts(i); + string getPermutation_rec_in(int32_t n, int32_t k, vector nums) { + vector fact(10, 1); + for (int32_t i{0}; i < 10; i++) { + fact[i] = facts(i); + } +#ifdef ALGORITHM_TEST_MACRO + assert(fact[n] >= k && k >= 0); + assert(n >= 1 && n <= 9); +#endif + char will_return[2]; + memset(will_return, '\0', sizeof(char) * 2); + if (1 == n) { + will_return[0] = '0' + nums[0]; + return will_return; + } + will_return[0] = '0' + nums[k / fact[n - 1]]; + nums.erase(std::remove(nums.begin(), nums.end(), will_return[0] - '0'), nums.end()); + return will_return + getPermutation_rec_in(n - 1, k % fact[n - 1], nums); } - assert(fact[n] >= k && k >= 1); - assert(n >= 1 && n <= 9); - vector nums; - for (int32_t i{1}; i <= n; i++) { - nums.push_back(i); + + public: + string getPermutation(int32_t n, int32_t k) { + vector fact(10, 1); + for (int32_t i{0}; i < 10; i++) { + fact[i] = facts(i); + } +#ifdef ALGORITHM_TEST_MACRO + assert(fact[n] >= k && k >= 1); + assert(1 <= n && n <= 9); +#endif + vector nums; + char will_return[10]{'\0'}; + int32_t k_count = k - 1; + vector ordres; + for (int32_t i{1}; i <= n; i++) { + nums.push_back(i); + } + for (int32_t i{0}; i < n; i++) { + int32_t temp = k_count / fact[n - 1 - i]; + ordres.push_back(temp); + k_count = k_count % fact[n - 1 - i]; + will_return[i] = '0' + nums[ordres[i]]; + nums.erase(std::remove(nums.begin(), nums.end(), nums[ordres[i]]), nums.end()); + } + return will_return; } - return getPermutation_rec_in(n, k - 1, nums); -} + string getPermutation_rec_out(int32_t n, int32_t k) { + vector fact(10, 1); + for (int32_t i{0}; i < 10; i++) { + fact[i] = facts(i); + } +#ifdef ALGORITHM_TEST_MACRO + assert(fact[n] >= k && k >= 1); + assert(n >= 1 && n <= 9); +#endif + vector nums; + for (int32_t i{1}; i <= n; i++) { + nums.push_back(i); + } + return getPermutation_rec_in(n, k - 1, nums); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_60_test.cpp b/algorithm/math/leetcode_60_test.cpp new file mode 100644 index 00000000..27b38473 --- /dev/null +++ b/algorithm/math/leetcode_60_test.cpp @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_60_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_60_TEST_HPP + +#include +#include "leetcode_60.cpp" + +namespace leetcode_60 { + +using Catch::Matchers::Equals; + +TEST_CASE("1 [test_60]", "[test_60]") { + static constexpr const auto n{3}, k{3}; + static constexpr const char *const result{"213"}; + Solution solution; + CHECK_THAT(result,Equals(solution.getPermutation(n, k))); + CHECK_THAT(result,Equals(solution.getPermutation_rec_out(n, k))); +} + +TEST_CASE("2 [test_60]", "[test_60]") { + static constexpr const auto n{4}, k{9}; + static constexpr const char *const result{"2314"}; + Solution solution; + CHECK_THAT(result,Equals(solution.getPermutation(n, k))); + CHECK_THAT(result,Equals(solution.getPermutation_rec_out(n, k))); +} + +TEST_CASE("3 [test_60]", "[test_60]") { + static constexpr const auto n{3}, k{1}; + static constexpr const char *const result{"123"}; + Solution solution; + CHECK_THAT(result,Equals(solution.getPermutation(n, k))); + CHECK_THAT(result,Equals(solution.getPermutation_rec_out(n, k))); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_60_TEST_HPP + diff --git a/algorithm/math/leetcode_60_test.hpp b/algorithm/math/leetcode_60_test.hpp deleted file mode 100644 index 3536ccab..00000000 --- a/algorithm/math/leetcode_60_test.hpp +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_60_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_60_TEST_HPP - -#include -#include -#include - -namespace leetcode_60 { -struct leetcode_60 { - static string getPermutation(int32_t n, int32_t k); - - static string getPermutation_rec_out(int32_t n, int32_t k); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("1 [test_60]", "[test_60]") { - static constexpr const auto n{3}, k{3}; - static constexpr const char *const result{"213"}; - CHECK_THAT(result,Equals(leetcode_60::getPermutation(n, k))); - CHECK_THAT(result,Equals(leetcode_60::getPermutation_rec_out(n, k))); -} - -TEST_CASE("2 [test_60]", "[test_60]") { - static constexpr const auto n{4}, k{9}; - static constexpr const char *const result{"2314"}; - CHECK_THAT(result,Equals(leetcode_60::getPermutation(n, k))); - CHECK_THAT(result,Equals(leetcode_60::getPermutation_rec_out(n, k))); -} - -TEST_CASE("3 [test_60]", "[test_60]") { - static constexpr const auto n{3}, k{1}; - static constexpr const char *const result{"123"}; - CHECK_THAT(result,Equals(leetcode_60::getPermutation(n, k))); - CHECK_THAT(result,Equals(leetcode_60::getPermutation_rec_out(n, k))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_60_TEST_HPP - diff --git a/algorithm/math/leetcode_670.cpp b/algorithm/math/leetcode_670.cpp index 3057c783..0a8033ae 100644 --- a/algorithm/math/leetcode_670.cpp +++ b/algorithm/math/leetcode_670.cpp @@ -1,74 +1,81 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_670_test.hpp" +#include +#include +#include namespace leetcode_670 { +using std::vector; +#endif -int32_t leetcode_670::maximumSwap(int32_t num) { - vector nums_{}; - while (num > 0) { - nums_.push_back(num % 10); - num /= 10; - } - vector nums{nums_.crbegin(), nums_.crend()}; - int32_t maximum{num}; - const auto vec_to_number = [](const vector &vec) { - int32_t i{0}; - for (const int iter: vec) { - i *= 10; - i += iter; +class Solution { + public: + int32_t maximumSwap(int32_t num) { + vector nums_{}; + while (num > 0) { + nums_.push_back(num % 10); + num /= 10; } - return i; - }; - for (size_t i{nums.size()}; i > 0; --i) { - size_t change = i - 1; - for (size_t j{i - 1}; j > 0; --j) { - if (nums[j - 1] < nums[i - 1]) { - change = j - 1; + vector nums{nums_.crbegin(), nums_.crend()}; + int32_t maximum{num}; + const auto vec_to_number = [](const vector &vec) { + int32_t i{0}; + for (const int iter : vec) { + i *= 10; + i += iter; + } + return i; + }; + for (size_t i{nums.size()}; i > 0; --i) { + size_t change = i - 1; + for (size_t j{i - 1}; j > 0; --j) { + if (nums[j - 1] < nums[i - 1]) { + change = j - 1; + } } + std::swap(nums[i - 1], nums[change]); + const auto number = vec_to_number(nums); + std::swap(nums[i - 1], nums[change]); + maximum = std::max(number, maximum); } - std::swap(nums[i - 1], nums[change]); - const auto number = vec_to_number(nums); - std::swap(nums[i - 1], nums[change]); - maximum = std::max(number, maximum); + return maximum; } - return maximum; -} -int32_t leetcode_670::maximumSwap2(int32_t num) { - vector nums_{}; - while (num > 0) { - nums_.push_back(num % 10); - num /= 10; - } - vector nums{nums_.crbegin(), nums_.crend()}; - const auto vec_to_number = [](const vector &vec) { - int32_t i{0}; - for (const int iter: vec) { - i *= 10; - i += iter; + int32_t maximumSwap2(int32_t num) { + vector nums_{}; + while (num > 0) { + nums_.push_back(num % 10); + num /= 10; } - return i; - }; - size_t max_loca{nums.size() - 1}; - size_t small{0}, big{0}; - for (size_t i{nums.size()}; i > 0; --i) { - if (nums[i - 1] > nums[max_loca]) { - max_loca = i - 1; - } else if (nums[i - 1] < nums[max_loca]) { - // 触发条件是 “发现右侧寻找到的最大值的左侧存在一个比他小的数字” - small = i - 1; - big = max_loca; + vector nums{nums_.crbegin(), nums_.crend()}; + const auto vec_to_number = [](const vector &vec) { + int32_t i{0}; + for (const int iter : vec) { + i *= 10; + i += iter; + } + return i; + }; + size_t max_loca{nums.size() - 1}; + size_t small{0}, big{0}; + for (size_t i{nums.size()}; i > 0; --i) { + if (nums[i - 1] > nums[max_loca]) { + max_loca = i - 1; + } else if (nums[i - 1] < nums[max_loca]) { + // 触发条件是 “发现右侧寻找到的最大值的左侧存在一个比他小的数字” + small = i - 1; + big = max_loca; + } + // equal条件下,max_loca优先采用右侧的数值,无需更新max_local + // 倘若更新,岂不是big在small相同或左侧。 } - // equal条件下,max_loca优先采用右侧的数值,无需更新max_local - // 倘若更新,岂不是big在small相同或左侧。 + std::swap(nums[small], nums[big]); + return vec_to_number(nums); } - std::swap(nums[small], nums[big]); - return vec_to_number(nums); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_670_test.cpp b/algorithm/math/leetcode_670_test.cpp new file mode 100644 index 00000000..d5b3ca7c --- /dev/null +++ b/algorithm/math/leetcode_670_test.cpp @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag Math +//@Tag 数学 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_670_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_670_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_670.cpp" + +namespace leetcode_670 { + +TEST_CASE("1 [test_670]", "[test_670]") { + static constexpr const auto input{2763}; + static constexpr const auto result{7263}; + Solution solution; + CHECK(result == solution.maximumSwap(input)); + CHECK(result == solution.maximumSwap2(input)); +} + +TEST_CASE("2 [test_670]", "[test_670]") { + static constexpr const auto input{9973}; + static constexpr const auto result{9973}; + Solution solution; + CHECK(result == solution.maximumSwap(input)); + CHECK(result == solution.maximumSwap2(input)); +} + +TEST_CASE("3 [test_670]", "[test_670]") { + static constexpr const auto input{114514}; + static constexpr const auto result{514114}; + Solution solution; + CHECK(result == solution.maximumSwap(input)); + CHECK(result == solution.maximumSwap2(input)); +} + +TEST_CASE("4 [test_670]", "[test_670]") { + static constexpr const auto input{1919810}; + static constexpr const auto result{9911810}; + Solution solution; + CHECK(result == solution.maximumSwap(input)); + CHECK(result == solution.maximumSwap2(input)); +} + +TEST_CASE("5 [test_670]", "[test_670]") { + static constexpr const auto input{99901}; + static constexpr const auto result{99910}; + Solution solution; + CHECK(result == solution.maximumSwap(input)); + CHECK(result == solution.maximumSwap2(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_670_TEST_HPP + diff --git a/algorithm/math/leetcode_670_test.hpp b/algorithm/math/leetcode_670_test.hpp deleted file mode 100644 index a5e45afb..00000000 --- a/algorithm/math/leetcode_670_test.hpp +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag Math -//@Tag 数学 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_670_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_670_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_670 { - -namespace leetcode_670 { -int32_t maximumSwap(int32_t num); -int32_t maximumSwap2(int32_t num); -} - -TEST_CASE("1 [test_670]", "[test_670]") { - static constexpr const auto input{2763}; - static constexpr const auto result{7263}; - CHECK(result == leetcode_670::maximumSwap(input)); - CHECK(result == leetcode_670::maximumSwap2(input)); -} - -TEST_CASE("2 [test_670]", "[test_670]") { - static constexpr const auto input{9973}; - static constexpr const auto result{9973}; - CHECK(result == leetcode_670::maximumSwap(input)); - CHECK(result == leetcode_670::maximumSwap2(input)); -} - -TEST_CASE("3 [test_670]", "[test_670]") { - static constexpr const auto input{114514}; - static constexpr const auto result{514114}; - CHECK(result == leetcode_670::maximumSwap(input)); - CHECK(result == leetcode_670::maximumSwap2(input)); -} - -TEST_CASE("4 [test_670]", "[test_670]") { - static constexpr const auto input{1919810}; - static constexpr const auto result{9911810}; - CHECK(result == leetcode_670::maximumSwap(input)); - CHECK(result == leetcode_670::maximumSwap2(input)); -} - -TEST_CASE("5 [test_670]", "[test_670]") { - static constexpr const auto input{99901}; - static constexpr const auto result{99910}; - CHECK(result == leetcode_670::maximumSwap(input)); - CHECK(result == leetcode_670::maximumSwap2(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_670_TEST_HPP - diff --git a/algorithm/math/leetcode_728.cpp b/algorithm/math/leetcode_728.cpp index 7c94514a..aae7dd3d 100644 --- a/algorithm/math/leetcode_728.cpp +++ b/algorithm/math/leetcode_728.cpp @@ -1,31 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_728_test.hpp" +#include +#include namespace leetcode_728 { -vector leetcode_728::selfDividingNumbers(int32_t left, int32_t right) { - vector will_return{}; - for (; left <= right; ++left) { - int32_t now{left}; - while (now > 0) { - const auto ten = now % 10; - now /= 10; - if (ten == 0 || left % ten != 0) { - now = -1; - break; +using std::vector; +#endif + +class Solution { +public: + vector selfDividingNumbers(int32_t left, int32_t right) { + vector will_return{}; + for (; left <= right; ++left) { + int32_t now{left}; + while (now > 0) { + const auto ten = now % 10; + now /= 10; + if (ten == 0 || left % ten != 0) { + now = -1; + break; + } + } + if (now == 0) { + will_return.push_back(left); } } - if (now == 0) { - will_return.push_back(left); - } + return will_return; } - return will_return; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_728_test.hpp b/algorithm/math/leetcode_728_test.cpp similarity index 50% rename from algorithm/math/leetcode_728_test.hpp rename to algorithm/math/leetcode_728_test.cpp index 52f30ff6..f6215fd7 100644 --- a/algorithm/math/leetcode_728_test.hpp +++ b/algorithm/math/leetcode_728_test.cpp @@ -1,40 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Math //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_728_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_728_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_728_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_728_TEST_HPP #include #include #include #include +#include "leetcode_728.cpp" namespace leetcode_728 { - -struct leetcode_728 { - static vector selfDividingNumbers(int32_t left, int32_t right); -}; - using Catch::Matchers::Equals; TEST_CASE("1 [test_728]", "[test_728]") { static constexpr const auto left{1}, right{22}; const vector results{1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22}; - CHECK_THAT(results, Equals(leetcode_728::selfDividingNumbers(left, right))); + Solution solution; + CHECK_THAT(results, Equals(solution.selfDividingNumbers(left, right))); } TEST_CASE("2 [test_728]", "[test_728]") { static constexpr const auto left{47}, right{85}; const vector results{48, 55, 66, 77}; - CHECK_THAT(results, Equals(leetcode_728::selfDividingNumbers(left, right))); + Solution solution; + CHECK_THAT(results, Equals(solution.selfDividingNumbers(left, right))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_728_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_728_TEST_HPP diff --git a/algorithm/math/leetcode_75.cpp b/algorithm/math/leetcode_75.cpp index e633045d..5f3da0d9 100644 --- a/algorithm/math/leetcode_75.cpp +++ b/algorithm/math/leetcode_75.cpp @@ -1,24 +1,31 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_75_test.hpp" +#include +#include +#include +#include namespace leetcode_75 { +using std::vector; +#endif -void leetcode_75::sortColors(vector &nums) { - std::array counts{0, 0, 0}; - for (const auto num: nums) { - counts[num]++; - } - for (int32_t i{0}, count{0}; i < 3; ++i) { - for (int32_t j{0}; j < counts[i]; ++j, ++count) { - nums[count] = i; +class Solution { +public: + void sortColors(vector &nums) { + std::array counts{0, 0, 0}; + for (const auto num: nums) { + counts[num]++; + } + for (int32_t i{0}, count{0}; i < 3; ++i) { + for (int32_t j{0}; j < counts[i]; ++j, ++count) { + nums[count] = i; + } } } -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_75_test.hpp b/algorithm/math/leetcode_75_test.cpp similarity index 56% rename from algorithm/math/leetcode_75_test.hpp rename to algorithm/math/leetcode_75_test.cpp index 77d8b7ba..ac674e36 100644 --- a/algorithm/math/leetcode_75_test.hpp +++ b/algorithm/math/leetcode_75_test.cpp @@ -1,26 +1,15 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag list //@Tag 链表 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_75_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_75_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_75_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_75_TEST_HPP #include -#include - -#include -#include +#include "leetcode_75.cpp" namespace leetcode_75 { -struct leetcode_75 { - static void sortColors(vector &nums); -}; using Catch::Matchers::Equals; @@ -28,7 +17,8 @@ TEST_CASE("1 [test_75]", "[test_75]") { const vector input{2, 0, 1, 2, 2, 2, 0, 0, 0, 0, 1, 1}; const vector result{0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2}; vector input_v{input}; - leetcode_75::sortColors(input_v); + Solution solution; + solution.sortColors(input_v); CHECK_THAT(result, Equals(input_v)); } @@ -36,8 +26,9 @@ TEST_CASE("2 [test_75]", "[test_75]") { const vector input{2, 0, 1}; const vector result{0, 1, 2}; vector input_v{input}; - leetcode_75::sortColors(input_v); + Solution solution; + solution.sortColors(input_v); CHECK_THAT(result, Equals(input_v)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_75_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_75_TEST_HPP diff --git a/algorithm/math/leetcode_781.cpp b/algorithm/math/leetcode_781.cpp index bf066378..ebad9530 100644 --- a/algorithm/math/leetcode_781.cpp +++ b/algorithm/math/leetcode_781.cpp @@ -1,27 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_781_test.hpp" +#include +#include #include namespace leetcode_781 { +using std::vector; using std::unordered_map; +#endif -int32_t leetcode_781::numRabbits(const vector &answers) { - unordered_map umap; - for (const auto &num: answers) { - ++umap[num]; - } - int32_t will_return{0}; - for (const auto &[key, value]: umap) { - const auto key1 = key + 1; - will_return += key1 * (value / key1 + static_cast(value % key1 != 0)); +class Solution { +public: + int32_t numRabbits(const vector &answers) { + unordered_map umap; + for (const auto &num: answers) { + ++umap[num]; + } + int32_t will_return{0}; + for (const auto &[key, value]: umap) { + const auto key1 = key + 1; + will_return += key1 * (value / key1 + static_cast(value % key1 != 0)); + } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_781_test.hpp b/algorithm/math/leetcode_781_test.cpp similarity index 55% rename from algorithm/math/leetcode_781_test.hpp rename to algorithm/math/leetcode_781_test.cpp index 952465d0..6c129c80 100644 --- a/algorithm/math/leetcode_781_test.hpp +++ b/algorithm/math/leetcode_781_test.cpp @@ -1,47 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Math //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_781_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_781_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_781_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_781_TEST_HPP #include #include #include #include +#include "leetcode_781.cpp" namespace leetcode_781 { using std::vector; - -struct leetcode_781 { - static int32_t numRabbits(const vector &answers); -}; - using Catch::Matchers::Equals; TEST_CASE("1 [test_781]", "[test_781]") { const vector input{1, 1, 2}; static constexpr const auto output{5}; - CHECK(output == leetcode_781::numRabbits(input)); + Solution solution; + CHECK(output == solution.numRabbits(input)); } TEST_CASE("2 [test_781]", "[test_781]") { const vector input{1, 1, 4, 5, 1, 4}; static constexpr const auto output{15}; - CHECK(output == leetcode_781::numRabbits(input)); + Solution solution; + CHECK(output == solution.numRabbits(input)); } TEST_CASE("3 [test_781]", "[test_781]") { const vector input{10, 10, 10}; static constexpr const auto output{11}; - CHECK(output == leetcode_781::numRabbits(input)); + Solution solution; + CHECK(output == solution.numRabbits(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_781_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_781_TEST_HPP diff --git a/algorithm/math/leetcode_883.cpp b/algorithm/math/leetcode_883.cpp index 8f768ae4..1dcd1f0d 100644 --- a/algorithm/math/leetcode_883.cpp +++ b/algorithm/math/leetcode_883.cpp @@ -1,32 +1,38 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_883_test.hpp" +#include +#include +#include namespace leetcode_883 { +using std::vector; +#endif -int32_t leetcode_883::projectionArea(const vector> &grid) { - const auto m{grid.size()}; - if (m == 0) { - return 0; - } - int willreturn{0}; - for (size_t i{0}; i < m; ++i) { - int max1{0}, max2{0}; - for (size_t j{0}; j < m; ++j) { - if (grid[i][j]) { - willreturn++; +class Solution { +public: + int32_t projectionArea(const vector> &grid) { + const auto m{grid.size()}; + if (m == 0) { + return 0; + } + int willreturn{0}; + for (size_t i{0}; i < m; ++i) { + int max1{0}, max2{0}; + for (size_t j{0}; j < m; ++j) { + if (grid[i][j]) { + willreturn++; + } + max1 = std::max(max1, grid[j][i]); + max2 = std::max(max2, grid[i][j]); } - max1 = std::max(max1, grid[j][i]); - max2 = std::max(max2, grid[i][j]); + willreturn += (max1 + max2); } - willreturn += (max1 + max2); + return willreturn; } - return willreturn; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_883_test.hpp b/algorithm/math/leetcode_883_test.cpp similarity index 55% rename from algorithm/math/leetcode_883_test.hpp rename to algorithm/math/leetcode_883_test.cpp index 6b462bd1..270441f6 100644 --- a/algorithm/math/leetcode_883_test.hpp +++ b/algorithm/math/leetcode_883_test.cpp @@ -1,47 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag Math //@Tag 数学 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_883_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_883_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_883_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_883_TEST_HPP #include #include #include #include +#include "leetcode_883.cpp" namespace leetcode_883 { using std::vector; - -struct leetcode_883 { - static int32_t projectionArea(const vector> &grid); -}; - using Catch::Matchers::Equals; TEST_CASE("1 [test_883]", "[test_883]") { const vector> input{{1, 2}, {3, 4}}; static constexpr const auto output{17}; - CHECK(output == leetcode_883::projectionArea(input)); + Solution solution; + CHECK(output == solution.projectionArea(input)); } TEST_CASE("2 [test_883]", "[test_883]") { const vector> input{{2}}; static constexpr const auto output{5}; - CHECK(output == leetcode_883::projectionArea(input)); + Solution solution; + CHECK(output == solution.projectionArea(input)); } TEST_CASE("3 [test_883]", "[test_883]") { const vector> input{{1, 0}, {0, 2}}; static constexpr const auto output{8}; - CHECK(output == leetcode_883::projectionArea(input)); + Solution solution; + CHECK(output == solution.projectionArea(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_883_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_883_TEST_HPP diff --git a/algorithm/math/leetcode_9.cpp b/algorithm/math/leetcode_9.cpp index 728ae810..12c0183b 100644 --- a/algorithm/math/leetcode_9.cpp +++ b/algorithm/math/leetcode_9.cpp @@ -1,30 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_9_test.hpp" +#include +#include +#include namespace leetcode_9 { +using std::vector; +#endif -bool leetcode_9::isPalindrome(int32_t x) { - vector nums; - if (x < 0) { - return false; - } - while (x > 0) { - nums.push_back(x % 10); - x /= 10; - } - const auto nums_size{nums.size()}; - const auto half_size{static_cast(nums_size / 2)}; - for (int32_t i{0}; i < half_size; i++) { - if (nums[i] != nums[nums_size - 1 - i]) { +class Solution { +public: + bool isPalindrome(int32_t x) { + vector nums; + if (x < 0) { return false; } + while (x > 0) { + nums.push_back(x % 10); + x /= 10; + } + const auto nums_size{nums.size()}; + const auto half_size{static_cast(nums_size / 2)}; + for (int32_t i{0}; i < half_size; i++) { + if (nums[i] != nums[nums_size - 1 - i]) { + return false; + } + } + return true; } - return true; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/leetcode_9_test.cpp b/algorithm/math/leetcode_9_test.cpp new file mode 100644 index 00000000..1e887c3a --- /dev/null +++ b/algorithm/math/leetcode_9_test.cpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 链表 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_9_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_9_TEST_HPP + +#include +#include "leetcode_9.cpp" + +namespace leetcode_9 { + +TEST_CASE("test case 1 [test_9]", "[test_9]") { + static constexpr const auto input{121}; + Solution solution; + CHECK(solution.isPalindrome(input)); +} + +TEST_CASE("test case 2 [test_9]", "[test_9]") { + static constexpr const auto input{-121}; + Solution solution; + CHECK_FALSE(solution.isPalindrome(input)); +} + +TEST_CASE("test case 3 [test_9]", "[test_9]") { + static constexpr const auto input{120}; + Solution solution; + CHECK_FALSE(solution.isPalindrome(input)); +} + +TEST_CASE("test case 4 [test_9]", "[test_9]") { + static constexpr const auto input{10}; + Solution solution; + CHECK_FALSE(solution.isPalindrome(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_9_TEST_HPP diff --git a/algorithm/math/leetcode_9_test.hpp b/algorithm/math/leetcode_9_test.hpp deleted file mode 100644 index 400ba2df..00000000 --- a/algorithm/math/leetcode_9_test.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 链表 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_9_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_9_TEST_HPP - -#include -#include -#include - -namespace leetcode_9 { -struct leetcode_9 { - static bool isPalindrome(int32_t x); -}; - - -TEST_CASE("test case 1 [test_9]", "[test_9]") { - static constexpr const auto input{121}; - CHECK(leetcode_9::isPalindrome(input)); -} - -TEST_CASE("test case 2 [test_9]", "[test_9]") { - static constexpr const auto input{-121}; - CHECK_FALSE(leetcode_9::isPalindrome(input)); -} - -TEST_CASE("test case 3 [test_9]", "[test_9]") { - static constexpr const auto input{120}; - CHECK_FALSE(leetcode_9::isPalindrome(input)); -} - -TEST_CASE("test case 4 [test_9]", "[test_9]") { - static constexpr const auto input{10}; - CHECK_FALSE(leetcode_9::isPalindrome(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_9_TEST_HPP diff --git a/algorithm/math/min_max_middle.cpp b/algorithm/math/min_max_middle.cpp index 47bc6e4b..5bdc34f2 100644 --- a/algorithm/math/min_max_middle.cpp +++ b/algorithm/math/min_max_middle.cpp @@ -1,85 +1,105 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "min_max_middle_test.hpp" +#include +#include +#include +#include +#include +#include +#include namespace leetcode_minmax { +using std::vector; +#endif -int32_t leetcode_minmax::minV(const vector &values) { - int32_t minV{std::numeric_limits::max()}; - for (const auto &value: values) { - minV = std::min(minV, value); - } - return minV; -} +struct minmax { + int32_t min, max; -int32_t leetcode_minmax::maxV(const vector &values) { - int32_t maxV{std::numeric_limits::min()}; - for (const auto &value: values) { - maxV = std::max(maxV, value); + bool operator==(const minmax &inAx) const { + return this->min == inAx.min && this->max == inAx.max; } - return maxV; -} +}; -minmax leetcode_minmax::minMaxV(const vector &values) { - int32_t minV{std::numeric_limits::max()}, maxV{std::numeric_limits::min()}; - const auto values_size{values.size()}, values_size_{(values_size / 2) * 2}; - if (values_size != values_size_) { - minV = values.back(); - maxV = values.back(); +class Solution { +public: + int32_t minV(const vector &values) { + int32_t minV{std::numeric_limits::max()}; + for (const auto &value: values) { + minV = std::min(minV, value); + } + return minV; } - for (size_t i{0}; i < values_size_; i += 2) { - if (values[i] < values[i + 1]) { - minV = std::min(minV, values[i]); - maxV = std::max(maxV, values[i + 1]); - } else { - minV = std::min(minV, values[i + 1]); - maxV = std::max(maxV, values[i]); + + int32_t maxV(const vector &values) { + int32_t maxV{std::numeric_limits::min()}; + for (const auto &value: values) { + maxV = std::max(maxV, value); } + return maxV; } - return {minV, maxV}; -} -int32_t leetcode_minmax::partition(vector &values, int32_t begin, int32_t end) { - const auto x{values[end]}; - auto i{begin - 1}; - for (int32_t j{begin}; j < end; ++j) { - if (values[j] <= x) { - i++; - std::swap(values[i], values[j]); + minmax minMaxV(const vector &values) { + int32_t minV{std::numeric_limits::max()}, maxV{std::numeric_limits::min()}; + const auto values_size{values.size()}, values_size_{(values_size / 2) * 2}; + if (values_size != values_size_) { + minV = values.back(); + maxV = values.back(); } + for (size_t i{0}; i < values_size_; i += 2) { + if (values[i] < values[i + 1]) { + minV = std::min(minV, values[i]); + maxV = std::max(maxV, values[i + 1]); + } else { + minV = std::min(minV, values[i + 1]); + maxV = std::max(maxV, values[i]); + } + } + return {minV, maxV}; } - std::swap(values[i + 1], values[end]); - return i + 1; -} -int32_t leetcode_minmax::random_partition(vector &values, int32_t begin, int32_t end) { - std::random_device rd; // non-deterministic generator - std::mt19937 gen{rd()}; // to seed mersenne twister. - std::uniform_int_distribution<> dist{begin, end}; // distribute results between 1 and 6 inclusive. - const auto i{dist(gen)}; - std::swap(values[end], values[i]); - return partition(values, begin, end); -} + int32_t partition(vector &values, int32_t begin, int32_t end) { + const auto x{values[end]}; + auto i{begin - 1}; + for (int32_t j{begin}; j < end; ++j) { + if (values[j] <= x) { + i++; + std::swap(values[i], values[j]); + } + } + std::swap(values[i + 1], values[end]); + return i + 1; + } -//O(n)复杂度获取 values中 [begin,end]上, (从零开始计数的) ith value -int32_t leetcode_minmax::middleV(vector &values, int32_t begin, int32_t end, int32_t ith) { - assert(0 <= begin && begin <= end); - assert(end < static_cast(values.size())); - if (begin == end) { - return values[begin]; + int32_t random_partition(vector &values, int32_t begin, int32_t end) { + std::random_device rd; // non-deterministic generator + std::mt19937 gen{rd()}; // to seed mersenne twister. + std::uniform_int_distribution<> dist{begin, end}; // distribute results between 1 and 6 inclusive. + const auto i{dist(gen)}; + std::swap(values[end], values[i]); + return partition(values, begin, end); } - const auto q = random_partition(values, begin, end); - const auto k{q - begin + 1}; - if (ith == k) { - return values[q]; - } else if (ith < k) { - return middleV(values, begin, q - 1, ith); + + //O(n)复杂度获取 values中 [begin,end]上, (从零开始计数的) ith value + int32_t middleV(vector &values, int32_t begin, int32_t end, int32_t ith) { + + assert(0 <= begin && begin <= end); + assert(end < static_cast(values.size())); + if (begin == end) { + return values[begin]; + } + const auto q = random_partition(values, begin, end); + const auto k{q - begin + 1}; + if (ith == k) { + return values[q]; + } else if (ith < k) { + return middleV(values, begin, q - 1, ith); + } + return middleV(values, q + 1, end, ith - k); } - return middleV(values, q + 1, end, ith - k); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/math/min_max_middle_test.cpp b/algorithm/math/min_max_middle_test.cpp new file mode 100644 index 00000000..523a1676 --- /dev/null +++ b/algorithm/math/min_max_middle_test.cpp @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag list +//@Tag 数学 +//@Description 最大值 +//@Description 最小值 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_MIN_MAX_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_MIN_MAX_HPP + +#include +#include "min_max_middle.cpp" + +namespace leetcode_minmax { + +TEST_CASE("basic test [test_minmax]", "[test_minmax]") { + const vector input{1, 2, 0}; + const static constexpr auto min{0}, max{2}; + Solution solution; + CHECK(min == solution.minV(input)); + CHECK(max == solution.maxV(input)); + CHECK(minmax{min, max} == solution.minMaxV(input)); +} + +TEST_CASE("basic test 2 [test_minmax]", "[test_minmax]") { + const vector input{3, 4, -1, 1}; + const static constexpr auto min{-1}, max{4}; + Solution solution; + CHECK(min == solution.minV(input)); + CHECK(max == solution.maxV(input)); + CHECK(minmax{min, max} == solution.minMaxV(input)); +} + +TEST_CASE("basic test 3 [test_minmax]", "[test_minmax]") { + const vector input{7, 8, 9, 11, 12}; + const static constexpr auto min{7}, max{12}; + Solution solution; + CHECK(min == solution.minV(input)); + CHECK(max == solution.maxV(input)); + CHECK(minmax{min, max} == solution.minMaxV(input)); +} + +TEST_CASE("basic test 4 [test_minmax]", "[test_minmax]") { + const vector input{1}; + const static constexpr auto min{1}, max{1}; + Solution solution; + CHECK(min == solution.minV(input)); + CHECK(max == solution.maxV(input)); + CHECK(minmax{min, max} == solution.minMaxV(input)); +} + +TEST_CASE("basic test 5 [test_minmax]", "[test_minmax]") { + const vector input{1, 2, 2, 1, 1, 3, 3, 4, 5}; + const static constexpr auto min{1}, max{5}; + Solution solution; + CHECK(min == solution.minV(input)); + CHECK(max == solution.maxV(input)); + CHECK(minmax{min, max} == solution.minMaxV(input)); +} + +TEST_CASE("basic test 6 [test_minmax]", "[test_minmax]") { + vector input{1, 1, 8, 1, 0, 4, 1, 9, 1, 9, 4, 1, 5}; + Solution solution; + CHECK(9 == solution.partition(input, 0, 12)); +} + +TEST_CASE("basic test 7 [test_minmax]", "[test_minmax]") { + vector input{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + Solution solution; + for (int32_t i{1}; i < 10; i++) { + CHECK(i == solution.middleV(input, 0, 9, i)); + } + for (int32_t i{1}; i < 9; i++) { + CHECK(i == solution.middleV(input, 0, 8, i)); + } +} + +TEST_CASE("basic test 8 [test_minmax]", "[test_minmax]") { + vector input{1, 4, 5, 7, 8, 9, 6, 2, 3, 10}; + Solution solution; + for (int32_t i{1}; i < 10; i++) { + CHECK(i == solution.middleV(input, 0, 9, i)); + } + for (int32_t i{1}; i < 9; i++) { + CHECK(i == solution.middleV(input, 0, 8, i)); + } +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_LIST_LEETCODE_MIN_MAX_HPP diff --git a/algorithm/math/min_max_middle_test.hpp b/algorithm/math/min_max_middle_test.hpp deleted file mode 100644 index 0bd931dc..00000000 --- a/algorithm/math/min_max_middle_test.hpp +++ /dev/null @@ -1,109 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag list -//@Tag 数学 -//@Description 最大值 -//@Description 最小值 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_MIN_MAX_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_MIN_MAX_HPP - -#include -#include -#include -#include - -namespace leetcode_minmax { -struct minmax final { - const int32_t min{}, max{}; - - bool operator==(const minmax &inAx) const { - return this->min == inAx.min && this->max == inAx.max; - } -}; - -struct leetcode_minmax { - static int32_t minV(const vector &values); - - static int32_t maxV(const vector &values); - - static minmax minMaxV(const vector &values); - - static int32_t random_partition(vector &values, int32_t begin, int32_t end); - - static int32_t partition(vector &values, int32_t begin, int32_t end); - - static int32_t middleV(vector &values, int32_t begin, int32_t end, int32_t ith); -}; - -TEST_CASE("basic test [test_minmax]", "[test_minmax]") { - const vector input{1, 2, 0}; - const static constexpr auto min{0}, max{2}; - CHECK(min == leetcode_minmax::minV(input)); - CHECK(max == leetcode_minmax::maxV(input)); - CHECK(minmax{min, max} == leetcode_minmax::minMaxV(input)); -} - -TEST_CASE("basic test 2 [test_minmax]", "[test_minmax]") { - const vector input{3, 4, -1, 1}; - const static constexpr auto min{-1}, max{4}; - CHECK(min == leetcode_minmax::minV(input)); - CHECK(max == leetcode_minmax::maxV(input)); - CHECK(minmax{min, max} == leetcode_minmax::minMaxV(input)); -} - -TEST_CASE("basic test 3 [test_minmax]", "[test_minmax]") { - const vector input{7, 8, 9, 11, 12}; - const static constexpr auto min{7}, max{12}; - CHECK(min == leetcode_minmax::minV(input)); - CHECK(max == leetcode_minmax::maxV(input)); - CHECK(minmax{min, max} == leetcode_minmax::minMaxV(input)); -} - -TEST_CASE("basic test 4 [test_minmax]", "[test_minmax]") { - const vector input{1}; - const static constexpr auto min{1}, max{1}; - CHECK(min == leetcode_minmax::minV(input)); - CHECK(max == leetcode_minmax::maxV(input)); - CHECK(minmax{min, max} == leetcode_minmax::minMaxV(input)); -} - -TEST_CASE("basic test 5 [test_minmax]", "[test_minmax]") { - const vector input{1, 2, 2, 1, 1, 3, 3, 4, 5}; - const static constexpr auto min{1}, max{5}; - CHECK(min == leetcode_minmax::minV(input)); - CHECK(max == leetcode_minmax::maxV(input)); - CHECK(minmax{min, max} == leetcode_minmax::minMaxV(input)); -} - -TEST_CASE("basic test 6 [test_minmax]", "[test_minmax]") { - vector input{1, 1, 8, 1, 0, 4, 1, 9, 1, 9, 4, 1, 5}; - CHECK(9 == leetcode_minmax::partition(input, 0, 12)); -} - -TEST_CASE("basic test 7 [test_minmax]", "[test_minmax]") { - vector input{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - for (int32_t i{1}; i < 10; i++) { - CHECK(i == leetcode_minmax::middleV(input, 0, 9, i)); - } - for (int32_t i{1}; i < 9; i++) { - CHECK(i == leetcode_minmax::middleV(input, 0, 8, i)); - } -} - -TEST_CASE("basic test 8 [test_minmax]", "[test_minmax]") { - vector input{1, 4, 5, 7, 8, 9, 6, 2, 3, 10}; - for (int32_t i{1}; i < 10; i++) { - CHECK(i == leetcode_minmax::middleV(input, 0, 9, i)); - } - for (int32_t i{1}; i < 9; i++) { - CHECK(i == leetcode_minmax::middleV(input, 0, 8, i)); - } -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_LIST_LEETCODE_MIN_MAX_HPP diff --git a/algorithm/matrix/CMakeLists.txt b/algorithm/matrix/CMakeLists.txt index d2a1af68..2f492a73 100644 --- a/algorithm/matrix/CMakeLists.txt +++ b/algorithm/matrix/CMakeLists.txt @@ -24,7 +24,7 @@ if (COMPILER_SUPPORTS_CXX20) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/matrix_test.cpp) target_link_libraries(${PROJECT_NAME}_test PUBLIC - CS203_DSAA_template_INCLUDE + algorithm_template_INCLUDE ) IF (OpenCV_FOUND) target_link_libraries(${PROJECT_NAME}_test diff --git a/algorithm/matrix/expression_template.hpp b/algorithm/matrix/expression_template.hpp index b7931746..9763b44c 100644 --- a/algorithm/matrix/expression_template.hpp +++ b/algorithm/matrix/expression_template.hpp @@ -1,10 +1,8 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_MATRIX_EXPRESSION_TEMPLATE_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_MATRIX_EXPRESSION_TEMPLATE_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_MATRIX_EXPRESSION_TEMPLATE_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_MATRIX_EXPRESSION_TEMPLATE_HPP #include "template_helper.hpp" @@ -119,4 +117,4 @@ max(const Expression &lhs, const Expression &rhs) { // no constructor and destructor to allocate and de-allocate memory } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_MATRIX_EXPRESSION_TEMPLATE_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_MATRIX_EXPRESSION_TEMPLATE_HPP diff --git a/algorithm/matrix/matrix.hpp b/algorithm/matrix/matrix.hpp index 6cf5659f..65819bda 100644 --- a/algorithm/matrix/matrix.hpp +++ b/algorithm/matrix/matrix.hpp @@ -1,10 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template +/* algorithm_template Copyright (C) 2020-2023 nanoseeds Wjia wuyuhao */ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_MATRIX_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_MATRIX_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_MATRIX_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_MATRIX_HPP #include #include @@ -486,46 +486,33 @@ struct number : public Expression> { // work function, computing this expression at position i, import for lazy computing - T value(size_t i, size_t j) const { return this->num; } + T value(size_t i, size_t j) const { return this->num;} + //before invoke, invoke the ~number // 感觉是优化错误 size_t rows() const { return 0x3f3f3f3f; } size_t cols() const { return 0x3f3f3f3f; } - }; +template +static number make_number(T t){ + return number(t); +} + template inline EXPRESSION::BinaryOp operator+(const Expression &lhs, const Expression &rhs) { return expToBinaryOp(lhs, rhs); } -template -inline EXPRESSION::BinaryOp> -operator+(const Expression &lhs, const T2 &rhs) { - return expToBinaryOp(lhs, number(rhs)); -} - -template -inline EXPRESSION::BinaryOp, T2> -operator+(const T1 &lhs, const Expression &rhs) { - return expToBinaryOp(rhs, lhs); -} - /** * matrix + matrix, must equal. * * input mat1,mat2 and will_return's type is same. * */ -template -inline EXPRESSION::BinaryOp, T2> -operator-(const T1 &lhs, const Expression &rhs) { - return expToBinaryOp(number(lhs * -1), rhs); -} - /** * matrix - matrix, must equal. * input mat1,mat2 and will_return's type is same. @@ -536,12 +523,6 @@ operator-(const Expression &lhs, const Expression &rhs) { return expToBinaryOp(lhs, rhs); } -template -inline EXPRESSION::BinaryOp> -operator-(const Expression &lhs, const T2 &rhs) { - return expToBinaryOp(lhs, number(rhs)); -} - /** * matrix * number, need T1 can * T2 @@ -1394,4 +1375,4 @@ Matrix Matrix::row_elimination(int32_t row, int32_t col, int32_t re } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_MATRIX_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_MATRIX_HPP diff --git a/algorithm/matrix/matrix_test.cpp b/algorithm/matrix/matrix_test.cpp index c75939de..6e538c2d 100644 --- a/algorithm/matrix/matrix_test.cpp +++ b/algorithm/matrix/matrix_test.cpp @@ -1,5 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template +/* algorithm_template Copyright (C) 2020-2023 nanoseeds Wjia wuyuhao */ #include @@ -379,8 +379,8 @@ TEST_CASE("operator plus", "[test_3]") { m25 = m2 + m5; Matrix m36{m3 + m6}; Matrix temp = m1 + m4 + m7; - Matrix temp2 = m1 + m4 + m7 + 2; - Matrix temp4 = m1 + m4 + 2 + m7; + Matrix temp2 = m1 + m4 + m7 + make_number(2); + Matrix temp4 = m1 + m4 + make_number(2) + m7; CHECK(Matrix::inside_equal(m1 + m4, m7)); CHECK(Matrix::inside_equal(m14, m7)); CHECK(Matrix::inside_equal(m2 + m5, m8)); diff --git a/algorithm/matrix/template_helper.hpp b/algorithm/matrix/template_helper.hpp index 05500c49..fadfe751 100644 --- a/algorithm/matrix/template_helper.hpp +++ b/algorithm/matrix/template_helper.hpp @@ -1,9 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS203_DSAA_template +/* algorithm_template Copyright (C) 2020-2023 nanoseeds Wjia wuyuhao */ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_TEMPLATE_HELPER_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_TEMPLATE_HELPER_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_TEMPLATE_HELPER_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_TEMPLATE_HELPER_HPP #include #include @@ -107,4 +107,4 @@ concept is_OPERATOR = requires(T f) { std::default_initializable; sizeof(T) == 1; }; -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_TEMPLATE_HELPER_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_CS205_PROJECT_2020S_SRC_TEMPLATE_HELPER_HPP diff --git a/algorithm/matrix/test_matrix_2.cpp b/algorithm/matrix/test_matrix_2.cpp index f630d029..74a1927d 100644 --- a/algorithm/matrix/test_matrix_2.cpp +++ b/algorithm/matrix/test_matrix_2.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2020-08-21 17:24:01 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include diff --git a/algorithm/moderncpp/CMakeLists.txt b/algorithm/moderncpp/CMakeLists.txt index 93d8a7d6..139047dd 100644 --- a/algorithm/moderncpp/CMakeLists.txt +++ b/algorithm/moderncpp/CMakeLists.txt @@ -10,7 +10,7 @@ set(dependencies 02 04 07) foreach (elementName IN LISTS dependencies) add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/chap${elementName}.cpp) - # target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) + # target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) target_link_libraries(${PROJECT_NAME}_${elementName} PUBLIC Threads::Threads) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) diff --git a/algorithm/moderncpp/chap02.cpp b/algorithm/moderncpp/chap02.cpp index e386ade6..9c1ad777 100644 --- a/algorithm/moderncpp/chap02.cpp +++ b/algorithm/moderncpp/chap02.cpp @@ -1,16 +1,11 @@ /** - * @Github: https://github.com/Certseeds/CS203_DSAA_template + * @Github: https://github.com/Certseeds/algorithm_template * @Author: nanos * @Date: 2021-06-13 19:38:35 * @LastEditors: nanos */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds // answer for Q1 // https://github.com/changkun/modern-cpp-tutorial/blob/master/book/zh-cn/02-usability.md #include diff --git a/algorithm/moderncpp/chap04.cpp b/algorithm/moderncpp/chap04.cpp index 6062dfcb..8b95b8c0 100644 --- a/algorithm/moderncpp/chap04.cpp +++ b/algorithm/moderncpp/chap04.cpp @@ -1,16 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanos - * @Date: 2021-08-14 17:38:35 - * @LastEditors: nanos - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include diff --git a/algorithm/moderncpp/chap07.cpp b/algorithm/moderncpp/chap07.cpp index 65fe9401..e00d5d55 100644 --- a/algorithm/moderncpp/chap07.cpp +++ b/algorithm/moderncpp/chap07.cpp @@ -1,16 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanos - * @Date: 2021-06-13 20:15:43 - * @LastEditors: nanos - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanos - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include diff --git a/algorithm/queue/CMakeLists.txt b/algorithm/queue/CMakeLists.txt index 08b84c9e..1f6a8509 100644 --- a/algorithm/queue/CMakeLists.txt +++ b/algorithm/queue/CMakeLists.txt @@ -9,16 +9,18 @@ set(dependencies) set(leetcode_order) LIST(APPEND leetcode_order so_09 933 1532) +LIST(APPEND leetcode_order ringbuffer_queue) + LIST(TRANSFORM leetcode_order PREPEND leetcode_) set(dependencies ${dependencies} ${leetcode_order}) unset(leetcode_order) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE CS203_DSAA_TEST_MACRO) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) endforeach () unset(dependencies) diff --git a/algorithm/queue/README.md b/algorithm/queue/README.md new file mode 100644 index 00000000..5cdc1f5b --- /dev/null +++ b/algorithm/queue/README.md @@ -0,0 +1,11 @@ +# queue + +DOING: using ring buffer to simulate a queue + +ring buffer应该有的接口 + +1. `bool isFull()`, push前先检查, 如果满了就不能push, 什么也不干. +2. `bool isEmpty()`, pop前先检查, 如果空了就不能pop, 什么也不干. +3. `void push(T value)` push对象, 满了什么也不干. +4. `void pop()`, 弹出第一个对象(对POD对象来说不清理), 如果空的话什么也不干. +5. `T front()`, 获取第一个对象, 空的话直接解引用head地址. \ No newline at end of file diff --git a/algorithm/queue/leetcode_1532.cpp b/algorithm/queue/leetcode_1532.cpp index a54eb09a..1d2f90e0 100644 --- a/algorithm/queue/leetcode_1532.cpp +++ b/algorithm/queue/leetcode_1532.cpp @@ -1,13 +1,26 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +#include +#include -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1532_test.hpp" +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1532 { +using std::vector; +#endif + +class ProductOfNumbers { +protected: + ProductOfNumbers() = default; + +public: + virtual void add(int32_t num) = 0; + + virtual int32_t getProduct(int32_t k) = 0; + + virtual ~ProductOfNumbers() = default; +}; class ProductOfNumbersNormal : public ProductOfNumbers { private: @@ -35,7 +48,13 @@ class ProductOfNumbersNormal : public ProductOfNumbers { } }; -ProductOfNumbers *leetcode_1532::pure() { - return new ProductOfNumbersNormal(); -} +class Solution { +public: + ProductOfNumbers *pure() { + return new ProductOfNumbersNormal(); + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/queue/leetcode_1532_test.hpp b/algorithm/queue/leetcode_1532_test.cpp similarity index 52% rename from algorithm/queue/leetcode_1532_test.hpp rename to algorithm/queue/leetcode_1532_test.cpp index 67f454a5..bba36489 100644 --- a/algorithm/queue/leetcode_1532_test.hpp +++ b/algorithm/queue/leetcode_1532_test.cpp @@ -1,42 +1,23 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2023-2025 nanoseeds //@Tag Queue //@Tag 队列 //@Tag 模拟 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_1532_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_1532_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_1532_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_1532_TEST_HPP #include #include #include #include +#include "leetcode_1532.cpp" namespace leetcode_1532 { using std::string; -class ProductOfNumbers { -protected: - ProductOfNumbers() = default; - -public: - virtual void add(int32_t num) = 0; - - virtual int32_t getProduct(int32_t k) = 0; - - virtual ~ProductOfNumbers() = default; -}; - -struct leetcode_1532 { - static ProductOfNumbers *pure(); -}; - TEST_CASE("test case pure-1 [test_1532]", "[test_1532]") { - const std::unique_ptr pointer = std::unique_ptr(leetcode_1532::pure()); + Solution solution; + const std::unique_ptr pointer = std::unique_ptr(solution.pure()); pointer->add(3); pointer->add(0); pointer->add(2); @@ -50,4 +31,4 @@ TEST_CASE("test case pure-1 [test_1532]", "[test_1532]") { } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_1532_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_1532_TEST_HPP diff --git a/algorithm/queue/leetcode_933.cpp b/algorithm/queue/leetcode_933.cpp index 9f536497..8bcd3f98 100644 --- a/algorithm/queue/leetcode_933.cpp +++ b/algorithm/queue/leetcode_933.cpp @@ -1,19 +1,26 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_933_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include +#ifdef ALGORITHM_TEST_MACRO + namespace leetcode_933 { using std::queue; +#endif + +class RecentCounter { +protected: + RecentCounter() = default; + +public: + virtual int ping(int t) = 0; + + virtual ~RecentCounter() = default; +}; class RecentCounterNormal : public RecentCounter { private: - queue que; + std::queue que; public: RecentCounterNormal() = default; @@ -26,7 +33,13 @@ class RecentCounterNormal : public RecentCounter { } }; -RecentCounter *leetcode_933::pure() { - return new RecentCounterNormal(); -} +class Solution { +public: + RecentCounter *pure() { + return new RecentCounterNormal(); + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/queue/leetcode_933_test.cpp b/algorithm/queue/leetcode_933_test.cpp new file mode 100644 index 00000000..58ca56b7 --- /dev/null +++ b/algorithm/queue/leetcode_933_test.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag Queue +//@Tag 队列 +//@Tag 模拟 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_933_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_933_TEST_HPP + +#include +#include +#include +#include +#include "leetcode_933.cpp" + +namespace leetcode_933 { +using std::string; + +TEST_CASE("test case pure-1 [test_933]", "[test_933]") { + Solution solution; + const std::unique_ptr pointer = std::unique_ptr(solution.pure()); + CHECK(1 == pointer->ping(1)); + CHECK(2 == pointer->ping(100)); + CHECK(3 == pointer->ping(3000)); + CHECK(3 == pointer->ping(3002)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_933_TEST_HPP diff --git a/algorithm/queue/leetcode_933_test.hpp b/algorithm/queue/leetcode_933_test.hpp deleted file mode 100644 index d2496ff7..00000000 --- a/algorithm/queue/leetcode_933_test.hpp +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag Queue -//@Tag 队列 -//@Tag 模拟 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_933_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_933_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_933 { -using std::string; - -class RecentCounter { -protected: - RecentCounter() = default; - -public: - virtual int ping(int t) = 0; - - virtual ~RecentCounter() = default; -}; - -struct leetcode_933 { - static RecentCounter *pure(); -}; - -TEST_CASE("test case pure-1 [test_933]", "[test_933]") { - const std::unique_ptr pointer = std::unique_ptr(leetcode_933::pure()); - CHECK(1 == pointer->ping(1)); - CHECK(2 == pointer->ping(100)); - CHECK(3 == pointer->ping(3000)); - CHECK(3 == pointer->ping(3002)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_933_TEST_HPP diff --git a/algorithm/queue/leetcode_ringbuffer_queue.cpp b/algorithm/queue/leetcode_ringbuffer_queue.cpp new file mode 100644 index 00000000..7f50927b --- /dev/null +++ b/algorithm/queue/leetcode_ringbuffer_queue.cpp @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2024-2025 nanoseeds + + +namespace rbqueue { +class ringbuffer_queue { +private: + std::vector vec; + size_t read{0}, write{0}; + size_t csize{}; +public: + explicit ringbuffer_queue(size_t size) : vec(vector(size, 0)) { + csize = size; + } + + bool isFull() const { + if (write - read == csize) { + return true; + } else if (read - write == csize) { + return true; + } + return false; + } + + bool isEmpty() const { + return read == write; // if read == write, it must be empty + } + + void push(int32_t value) { + if (isFull()) { + return; + } + vec[write % csize] = value; + write = (write + 1) % (csize << 1); + } + + void pop() { + if (isEmpty()) { + return; + } + read = (read + 1) % (csize << 1); + } + + int32_t front() { + return vec[read % csize]; + } +}; + +} diff --git a/algorithm/queue/leetcode_ringbuffer_queue_test.cpp b/algorithm/queue/leetcode_ringbuffer_queue_test.cpp new file mode 100644 index 00000000..63fb95cd --- /dev/null +++ b/algorithm/queue/leetcode_ringbuffer_queue_test.cpp @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2024-2025 nanoseeds + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_RINGBUFFER_QUEUE_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_RINGBUFFER_QUEUE_HPP + +#include +#include "leetcode_ringbuffer_queue.cpp" + +#include +#include + +namespace rbqueue { + +TEST_CASE("test case pure-1 [test_rbqueue_09]", "[test_rbqueue_09]") { + ringbuffer_queue rbq(3); + CHECK(rbq.isEmpty()); + rbq.push(1); + CHECK_FALSE(rbq.isEmpty()); + CHECK_FALSE(rbq.isFull()); + CHECK(rbq.front() == 1); + CHECK(rbq.front() == 1); + rbq.push(2); + CHECK_FALSE(rbq.isEmpty()); + CHECK_FALSE(rbq.isFull()); + CHECK(rbq.front() == 1); + rbq.push(3); + CHECK_FALSE(rbq.isEmpty()); + CHECK(rbq.isFull()); + CHECK(rbq.front() == 1); + rbq.pop(); + CHECK_FALSE(rbq.isEmpty()); + CHECK_FALSE(rbq.isFull()); + CHECK(rbq.front() == 2); + rbq.pop(); + CHECK_FALSE(rbq.isEmpty()); + CHECK_FALSE(rbq.isFull()); + CHECK(rbq.front() == 3); + rbq.pop(); + + CHECK(rbq.isEmpty()); + CHECK_FALSE(rbq.isFull()); + rbq.push(4); + CHECK_FALSE(rbq.isEmpty()); + CHECK_FALSE(rbq.isFull()); + CHECK(rbq.front() == 4); + rbq.pop(); + CHECK(rbq.isEmpty()); + CHECK_FALSE(rbq.isFull()); + CHECK(rbq.front() == 2); + rbq.push(6); + CHECK_FALSE(rbq.isEmpty()); + CHECK_FALSE(rbq.isFull()); + rbq.pop(); + CHECK(rbq.isEmpty()); + CHECK_FALSE(rbq.isFull()); + CHECK(rbq.front() == 3); + rbq.pop(); + CHECK(rbq.isEmpty()); + CHECK_FALSE(rbq.isFull()); + CHECK(rbq.front() == 3); + rbq.pop(); + CHECK(rbq.isEmpty()); + CHECK_FALSE(rbq.isFull()); + CHECK(rbq.front() == 3); +} +} + +#endif //ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_RINGBUFFER_QUEUE_HPP diff --git a/algorithm/queue/leetcode_so_09.cpp b/algorithm/queue/leetcode_so_09.cpp index 59c33a28..008cd32a 100644 --- a/algorithm/queue/leetcode_so_09.cpp +++ b/algorithm/queue/leetcode_so_09.cpp @@ -1,15 +1,23 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_so_09_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include +#include + +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_so_09 { using std::stack; +#endif + +struct CQueue { + CQueue() = default; + + virtual void appendTail(int32_t value) = 0; + + virtual int deleteHead() = 0; + + virtual ~CQueue() = default; +}; struct StackQueue : CQueue { private: @@ -70,12 +78,17 @@ struct StackQueue2 : CQueue { } }; -CQueue *leetcode_so_09::pure() { - return new StackQueue(); -} +class Solution { +public: + CQueue *pure() { + return new StackQueue(); + } -CQueue *leetcode_so_09::effective() { - return new StackQueue2(); -} + CQueue *effective() { + return new StackQueue2(); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/queue/leetcode_so_09_test.hpp b/algorithm/queue/leetcode_so_09_test.cpp similarity index 57% rename from algorithm/queue/leetcode_so_09_test.hpp rename to algorithm/queue/leetcode_so_09_test.cpp index 9ad16d43..d070aa2b 100644 --- a/algorithm/queue/leetcode_so_09_test.hpp +++ b/algorithm/queue/leetcode_so_09_test.cpp @@ -1,47 +1,28 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag Queue //@Tag 队列 //@Tag 模拟 //@Plan 剑指OfferII-I Day01 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_09_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_09_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_09_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_09_TEST_HPP #include #include #include #include +#include "leetcode_so_09.cpp" namespace leetcode_so_09 { using std::string; -struct CQueue { - CQueue() = default; - - virtual void appendTail(int32_t value) = 0; - - virtual int deleteHead() = 0; - - virtual ~CQueue() = default; -}; - -struct leetcode_so_09 { - static CQueue *pure(); - - static CQueue *effective(); -}; - TEST_CASE("test case pure-1 [test_sw_09]", "[test_sw_09]") { std::function lambda; + Solution solution; SECTION("pure") { - lambda = leetcode_so_09::pure; + lambda = [&solution]() { return solution.pure(); }; }SECTION("effective") { - lambda = leetcode_so_09::effective; + lambda = [&solution]() { return solution.effective(); }; } const auto ptr = std::unique_ptr(lambda()); ptr->appendTail(3); @@ -51,10 +32,11 @@ TEST_CASE("test case pure-1 [test_sw_09]", "[test_sw_09]") { TEST_CASE("test case pure-2 [test_sw_09]", "[test_sw_09]") { std::function lambda; + Solution solution; SECTION("pure") { - lambda = leetcode_so_09::pure; + lambda = [&solution]() { return solution.pure(); }; }SECTION("effective") { - lambda = leetcode_so_09::effective; + lambda = [&solution]() { return solution.effective(); }; } const auto ptr = std::unique_ptr(lambda()); CHECK(-1 == ptr->deleteHead()); @@ -64,4 +46,4 @@ TEST_CASE("test case pure-2 [test_sw_09]", "[test_sw_09]") { CHECK(2 == ptr->deleteHead()); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_09_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_09_TEST_HPP diff --git a/algorithm/sort/CMakeLists.txt b/algorithm/sort/CMakeLists.txt index 35b51a0d..7e8f52fc 100644 --- a/algorithm/sort/CMakeLists.txt +++ b/algorithm/sort/CMakeLists.txt @@ -11,8 +11,8 @@ foreach (elementName IN LISTS dependencies) add_library(${PROJECT_NAME}_${elementName} ${LIB_WAY} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_sort.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_${elementName}_test ${CMAKE_CURRENT_SOURCE_DIR}/sort_test.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName}_test CS203_DSAA_template_INCLUDE ${PROJECT_NAME}_${elementName}) - target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE CS203_DSAA_TEST_MACRO) + target_link_libraries(${PROJECT_NAME}_${elementName}_test algorithm_template_INCLUDE ${PROJECT_NAME}_${elementName}) + target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE ALGORITHM_TEST_MACRO) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_sort.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/algorithm/sort/bubble_sort.cpp b/algorithm/sort/bubble_sort.cpp index a477d9d9..24a4cf4d 100644 --- a/algorithm/sort/bubble_sort.cpp +++ b/algorithm/sort/bubble_sort.cpp @@ -1,16 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanoseeds - * @Date: 2020-07-22 22:51:11 - * @LastEditors: nanoseeds - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include "sort_wrapper.hpp" using std::vector; diff --git a/algorithm/sort/heap_sort.cpp b/algorithm/sort/heap_sort.cpp index ec4a72fe..c0b0ccca 100644 --- a/algorithm/sort/heap_sort.cpp +++ b/algorithm/sort/heap_sort.cpp @@ -1,15 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanoseeds - * @Date: 2020-07-22 23:13:02 - * @LastEditors: nanoseeds - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include "sort_wrapper.hpp" using std::vector; diff --git a/algorithm/sort/insert_sort.cpp b/algorithm/sort/insert_sort.cpp index 7b115ff8..c64d4c73 100644 --- a/algorithm/sort/insert_sort.cpp +++ b/algorithm/sort/insert_sort.cpp @@ -1,16 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanoseeds - * @Date: 2020-07-22 22:26:04 - * @LastEditors: nanoseeds - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include "sort_wrapper.hpp" using std::vector; diff --git a/algorithm/sort/merge_sort.cpp b/algorithm/sort/merge_sort.cpp index bf081444..a2a8c81f 100644 --- a/algorithm/sort/merge_sort.cpp +++ b/algorithm/sort/merge_sort.cpp @@ -1,16 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanoseeds - * @Date: 2020-07-22 22:57:16 - * @LastEditors: nanoseeds - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include "sort_wrapper.hpp" diff --git a/algorithm/sort/quick_sort.cpp b/algorithm/sort/quick_sort.cpp index 1da9db6f..050e5535 100644 --- a/algorithm/sort/quick_sort.cpp +++ b/algorithm/sort/quick_sort.cpp @@ -1,17 +1,5 @@ -/* - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanoseeds - * @Date: 2020-07-18 21:00:45 - * @LastEditors: nanoseeds - * @LastEditTime: 2020-07-18 21:03:33 - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include "sort_wrapper.hpp" diff --git a/algorithm/sort/selection_sort.cpp b/algorithm/sort/selection_sort.cpp index 5eab3993..019b7f5a 100644 --- a/algorithm/sort/selection_sort.cpp +++ b/algorithm/sort/selection_sort.cpp @@ -1,16 +1,5 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanoseeds - * @Date: 2020-07-22 22:54:21 - * @LastEditors: nanoseeds - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include "sort_wrapper.hpp" using std::vector; diff --git a/algorithm/sort/sort_test.cpp b/algorithm/sort/sort_test.cpp index ee2646b1..92754833 100644 --- a/algorithm/sort/sort_test.cpp +++ b/algorithm/sort/sort_test.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include "sort_wrapper.hpp" diff --git a/algorithm/sort/sort_wrapper.hpp b/algorithm/sort/sort_wrapper.hpp index d941cddf..4739e330 100644 --- a/algorithm/sort/sort_wrapper.hpp +++ b/algorithm/sort/sort_wrapper.hpp @@ -1,22 +1,11 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanoseeds - * @Date: 2020-07-22 22:33:32 - * @LastEditors: nanoseeds - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_SORT_SORT_WRAPPER_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_SORT_SORT_WRAPPER_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_SORT_SORT_WRAPPER_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_SORT_SORT_WRAPPER_HPP #include #include void sort_warpper(std::vector &nums); -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_SORT_SORT_WRAPPER_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_SORT_SORT_WRAPPER_HPP diff --git a/algorithm/stack/CMakeLists.txt b/algorithm/stack/CMakeLists.txt index 1a1f8947..b7625948 100644 --- a/algorithm/stack/CMakeLists.txt +++ b/algorithm/stack/CMakeLists.txt @@ -17,9 +17,9 @@ set(dependencies ${dependencies} ${leetcode_order}) unset(leetcode_order) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE CS203_DSAA_TEST_MACRO) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) endforeach () diff --git a/algorithm/stack/leetcode_1021.cpp b/algorithm/stack/leetcode_1021.cpp index 46801c13..cb1e02b2 100644 --- a/algorithm/stack/leetcode_1021.cpp +++ b/algorithm/stack/leetcode_1021.cpp @@ -1,34 +1,39 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag stack //@Tag 栈 //@Tag 输入保证合法 -#include "leetcode_1021_test.hpp" +#ifdef ALGORITHM_TEST_MACRO + +#include +#include namespace leetcode_1021 { +using std::string; +#endif -string leetcode_1021::removeOuterParentheses(const string &str) { - std::string will_return{}; - const auto str_size{str.size()}; - for (size_t i{0}; i < str_size; ++i) { - for (size_t depth{1}; depth != 0;) { - ++i; - if (str[i] == '(') { - ++depth; - } else { - --depth; - } - if (depth != 0) [[likely]] { - will_return += str[i]; +class Solution { +public: + string removeOuterParentheses(const string &str) { + std::string will_return{}; + const auto str_size{str.size()}; + for (size_t i{0}; i < str_size; ++i) { + for (size_t depth{1}; depth != 0;) { + ++i; + if (str[i] == '(') { + ++depth; + } else { + --depth; + } + if (depth != 0) [[likely]] { + will_return += str[i]; + } } } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_1021_test.hpp b/algorithm/stack/leetcode_1021_test.cpp similarity index 50% rename from algorithm/stack/leetcode_1021_test.hpp rename to algorithm/stack/leetcode_1021_test.cpp index ed80009f..2aa856e1 100644 --- a/algorithm/stack/leetcode_1021_test.hpp +++ b/algorithm/stack/leetcode_1021_test.cpp @@ -1,39 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_1021_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_1021_TEST_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_1021_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_1021_TEST_HPP +#include "leetcode_1021.cpp" #include -#include namespace leetcode_1021 { -using std::string; - -struct leetcode_1021 { - static string removeOuterParentheses(const string &str); -}; TEST_CASE("1 [test_1021]", "[test_1021]") { static constexpr const char *const input{"(()())(())"}; static constexpr const char *const result{"()()()"}; - CHECK(result == leetcode_1021::removeOuterParentheses(input)); + Solution solution; + CHECK(result == solution.removeOuterParentheses(input)); } TEST_CASE("2 [test_1021]", "[test_1021]") { static constexpr const char *const input{"(())(()()())((()))"}; static constexpr const char *const result{"()()()()(())"}; - CHECK(result == leetcode_1021::removeOuterParentheses(input)); + Solution solution; + CHECK(result == solution.removeOuterParentheses(input)); } TEST_CASE("3 [test_1021]", "[test_1021]") { static constexpr const char *const input{"()()"}; static constexpr const char *const result{""}; - CHECK(result == leetcode_1021::removeOuterParentheses(input)); + Solution solution; + CHECK(result == solution.removeOuterParentheses(input)); } + } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_1021_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_1021_TEST_HPP diff --git a/algorithm/stack/leetcode_1047.cpp b/algorithm/stack/leetcode_1047.cpp index 4e3205a8..7a41d6d9 100644 --- a/algorithm/stack/leetcode_1047.cpp +++ b/algorithm/stack/leetcode_1047.cpp @@ -1,38 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag stack //@Tag 栈 //@Tag 输入保证合法 -#include "leetcode_1047_test.hpp" +#ifdef ALGORITHM_TEST_MACRO + #include +#include +#include namespace leetcode_1047 { using std::stack; +using std::string; +#endif -string leetcode_1047::removeDuplicates(const string &s) { - stack sta; - for (const auto ch: s) { - if (sta.empty()) { - sta.push(ch); - } else { - const auto top{sta.top()}; - if (top == ch) { - sta.pop(); - } else { +class Solution { +public: + string removeDuplicates(const string &s) { + stack sta; + for (const auto ch: s) { + if (sta.empty()) { sta.push(ch); + } else { + const auto top{sta.top()}; + if (top == ch) { + sta.pop(); + } else { + sta.push(ch); + } } } + std::vector cache(sta.size()); + for (auto iter = cache.begin(); iter != cache.end(); ++iter, sta.pop()) { + (*iter) = sta.top(); + } + return {cache.crbegin(), cache.crend()}; } - std::vector cache(sta.size()); - for (auto iter = cache.begin(); iter != cache.end(); ++iter, sta.pop()) { - (*iter) = sta.top(); - } - return {cache.crbegin(), cache.crend()}; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_1047_test.hpp b/algorithm/stack/leetcode_1047_test.cpp similarity index 50% rename from algorithm/stack/leetcode_1047_test.hpp rename to algorithm/stack/leetcode_1047_test.cpp index 921a0c94..8265ebd1 100644 --- a/algorithm/stack/leetcode_1047_test.hpp +++ b/algorithm/stack/leetcode_1047_test.cpp @@ -1,39 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_1047_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_1047_TEST_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_1047_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_1047_TEST_HPP +#include "leetcode_1047.cpp" #include -#include namespace leetcode_1047 { -using std::string; - -struct leetcode_1047 { - static string removeDuplicates(const string &s); -}; TEST_CASE("1 [test_1047]", "[test_1047]") { static constexpr const char *const input{"abbaca"}; static constexpr const char *const result{"ca"}; - CHECK(result == leetcode_1047::removeDuplicates(input)); + Solution solution; + CHECK(result == solution.removeDuplicates(input)); } TEST_CASE("2 [test_1047]", "[test_1047]") { static constexpr const char *const input{"114514"}; static constexpr const char *const result{"4514"}; - CHECK(result == leetcode_1047::removeDuplicates(input)); + Solution solution; + CHECK(result == solution.removeDuplicates(input)); } TEST_CASE("3 [test_1047]", "[test_1047]") { static constexpr const char *const input{"1919810"}; static constexpr const char *const result{"1919810"}; - CHECK(result == leetcode_1047::removeDuplicates(input)); + Solution solution; + CHECK(result == solution.removeDuplicates(input)); } + } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_1047_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_1047_TEST_HPP diff --git a/algorithm/stack/leetcode_1614.cpp b/algorithm/stack/leetcode_1614.cpp index 98b703d4..a5b1e06d 100644 --- a/algorithm/stack/leetcode_1614.cpp +++ b/algorithm/stack/leetcode_1614.cpp @@ -1,42 +1,49 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag stack //@Tag 栈 //@Tag 输入保证合法 -#include "leetcode_1614_test.hpp" +#ifdef ALGORITHM_TEST_MACRO + #include #include #include +#include +#include +#include namespace leetcode_1614 { using std::array; using std::stack; +using std::string; +#endif -int leetcode_1614::maxDepth(const string &s) { - static const auto arr = [] { - static auto arr = std::array::max() + 1>{0}; - arr['('] = '('; - arr[')'] = '('; - return arr; - }(); - stack sta{}; - int32_t will_return{0}, temp{0}; - for (auto &&ch: s) { - if (arr[ch] == ch) { - sta.push(ch); - } else if (!sta.empty() && arr[ch] == sta.top()) { - will_return = std::max(will_return, static_cast(sta.size())); - sta.pop(); - } else { - will_return = std::max(will_return, static_cast(sta.size())); +class Solution { +public: + int maxDepth(const string &s) { + static const auto arr = [] { + static auto arr = std::array::max() + 1>{0}; + arr['('] = '('; + arr[')'] = '('; + return arr; + }(); + stack sta{}; + int32_t will_return{0}, temp{0}; + for (auto &&ch: s) { + if (arr[ch] == ch) { + sta.push(ch); + } else if (!sta.empty() && arr[ch] == sta.top()) { + will_return = std::max(will_return, static_cast(sta.size())); + sta.pop(); + } else { + will_return = std::max(will_return, static_cast(sta.size())); + } + temp++; } - temp++; + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_1614_test.cpp b/algorithm/stack/leetcode_1614_test.cpp new file mode 100644 index 00000000..db4e9e5e --- /dev/null +++ b/algorithm/stack/leetcode_1614_test.cpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_1614_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_1614_TEST_HPP + +#include "leetcode_1614.cpp" +#include + +namespace leetcode_1614 { + +TEST_CASE("1 [test_1614]", "[test_1614]") { + Solution solution; + CHECK(1 == solution.maxDepth("()")); + CHECK(1 == solution.maxDepth("(*)")); + CHECK(2 == solution.maxDepth("((*))")); +} + +TEST_CASE("2 [test_1614]", "[test_1614]") { + Solution solution; + CHECK(3 == solution.maxDepth("(1+(2*3)+((8)/4))+1")); + CHECK(3 == solution.maxDepth("(1)+((2))+(((3)))")); + CHECK(1 == solution.maxDepth("1+(2*3)/(2-1)")); + CHECK(0 == solution.maxDepth("1")); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_1614_TEST_HPP diff --git a/algorithm/stack/leetcode_1614_test.hpp b/algorithm/stack/leetcode_1614_test.hpp deleted file mode 100644 index 496007c7..00000000 --- a/algorithm/stack/leetcode_1614_test.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_1614_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_1614_TEST_HPP - -#include -#include - -namespace leetcode_1614 { -using std::string; - -struct leetcode_1614 { - static int maxDepth(const string &s); -}; - -TEST_CASE("1 [test_1614]", "[test_1614]") { - CHECK(1 == leetcode_1614::maxDepth("()")); - CHECK(1 == leetcode_1614::maxDepth("(*)")); - CHECK(2 == leetcode_1614::maxDepth("((*))")); -} - -TEST_CASE("2 [test_1614]", "[test_1614]") { - CHECK(3 == leetcode_1614::maxDepth("(1+(2*3)+((8)/4))+1")); - CHECK(3 == leetcode_1614::maxDepth("(1)+((2))+(((3)))")); - CHECK(1 == leetcode_1614::maxDepth("1+(2*3)/(2-1)")); - CHECK(0 == leetcode_1614::maxDepth("1")); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_1614_TEST_HPP diff --git a/algorithm/stack/leetcode_20.cpp b/algorithm/stack/leetcode_20.cpp index f63a3bd8..c3de5984 100644 --- a/algorithm/stack/leetcode_20.cpp +++ b/algorithm/stack/leetcode_20.cpp @@ -1,33 +1,38 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_20_test.hpp" #include #include +#include +#include namespace leetcode_20 { using std::array; using std::stack; +using std::string; +#endif -bool leetcode_20::isValid(const string &s) { - std::stack stk{{'?'}}; - std::array umap{}; - umap['('] = ')'; - umap['['] = ']'; - umap['{'] = '}'; - for (const auto i: s) { - if (umap[stk.top()] == i) { - stk.pop(); - } else { - stk.push(i); +class Solution { +public: + bool isValid(const string &s) { + std::stack stk{{'?'}}; + std::array umap{}; + umap['('] = ')'; + umap['['] = ']'; + umap['{'] = '}'; + for (const auto i: s) { + if (umap[stk.top()] == i) { + stk.pop(); + } else { + stk.push(i); + } } + stk.pop(); + return stk.empty(); } - stk.pop(); - return stk.empty(); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_20_test.cpp b/algorithm/stack/leetcode_20_test.cpp new file mode 100644 index 00000000..678d58cb --- /dev/null +++ b/algorithm/stack/leetcode_20_test.cpp @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag stack +//@Tag 栈 +//@Plan 数据结构入门 Day9 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_20_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_20_TEST_HPP + +#include "leetcode_20.cpp" +#include + +namespace leetcode_20 { + +TEST_CASE("test case 1 [test_20]", "[test_20]") { + Solution solution; + CHECK(solution.isValid("()")); + CHECK(solution.isValid("()[]{}")); + CHECK(solution.isValid("(()[]{})[()[]{}]{()[]{}}")); + CHECK(solution.isValid("(((()[]{})[()[]{}]{()[]{}})[]{})[()[]{}]{()[]{}}")); +} + +TEST_CASE("test case 0 [test_20]", "[test_20]") { + Solution solution; + CHECK_FALSE(solution.isValid("(]")); + CHECK_FALSE(solution.isValid("(}")); + CHECK_FALSE(solution.isValid("[}")); + CHECK_FALSE(solution.isValid("[)")); + CHECK_FALSE(solution.isValid("{)")); + CHECK_FALSE(solution.isValid("{]")); + CHECK_FALSE(solution.isValid("([)]")); + CHECK_FALSE(solution.isValid("(((()[]{})[()[]{}]{()[]{}})[]{))[()[]{}]{()[]{}}")); +} + +TEST_CASE("test case 2-2 [test_20]", "[test_20]") { + Solution solution; + CHECK_FALSE(solution.isValid("([)]")); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_20_TEST_HPP diff --git a/algorithm/stack/leetcode_20_test.hpp b/algorithm/stack/leetcode_20_test.hpp deleted file mode 100644 index 22ab013b..00000000 --- a/algorithm/stack/leetcode_20_test.hpp +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag stack -//@Tag 栈 -//@Plan 数据结构入门 Day9 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_20_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_20_TEST_HPP - -#include -#include - -namespace leetcode_20 { -using std::string; - -struct leetcode_20 { - static bool isValid(const string &s); -}; - -TEST_CASE("test case 1 [test_20]", "[test_20]") { - CHECK(leetcode_20::isValid("()")); - CHECK(leetcode_20::isValid("()[]{}")); - CHECK(leetcode_20::isValid("(()[]{})[()[]{}]{()[]{}}")); - CHECK(leetcode_20::isValid("(((()[]{})[()[]{}]{()[]{}})[]{})[()[]{}]{()[]{}}")); -} - -TEST_CASE("test case 0 [test_20]", "[test_20]") { - CHECK_FALSE(leetcode_20::isValid("(]")); - CHECK_FALSE(leetcode_20::isValid("(}")); - CHECK_FALSE(leetcode_20::isValid("[}")); - CHECK_FALSE(leetcode_20::isValid("[)")); - CHECK_FALSE(leetcode_20::isValid("{)")); - CHECK_FALSE(leetcode_20::isValid("{]")); - CHECK_FALSE(leetcode_20::isValid("([)]")); - CHECK_FALSE(leetcode_20::isValid("(((()[]{})[()[]{}]{()[]{}})[]{))[()[]{}]{()[]{}}")); -} - -TEST_CASE("test case 2-2 [test_20]", "[test_20]") { - CHECK_FALSE(leetcode_20::isValid("([)]")); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_20_TEST_HPP diff --git a/algorithm/stack/leetcode_232.cpp b/algorithm/stack/leetcode_232.cpp index a48e9fdc..6ada2e67 100644 --- a/algorithm/stack/leetcode_232.cpp +++ b/algorithm/stack/leetcode_232.cpp @@ -1,52 +1,70 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag stack //@Tag 栈 //@Tag 单调栈 -#include "leetcode_232_test.hpp" +#ifdef ALGORITHM_TEST_MACRO + #include +#include namespace leetcode_232 { using std::stack; +#endif -class Queue : public leetcode_232::MyQueue { -private: - stack sta1{}, sta2{}; +class MyQueue { public: - Queue() = default; + MyQueue() = default; - void push(int x) override { - sta1.push(x); - } + virtual void push(int x) = 0; - int pop() override { - const auto head = this->peek(); - sta2.pop(); - return head; - } + virtual int pop() = 0; - int peek() override { - if (sta2.empty()) { - while (!sta1.empty()) { - sta2.push(sta1.top()); - sta1.pop(); - } - } - return sta2.top(); - } + virtual int peek() = 0; - bool empty() const override { return sta1.empty() && sta2.empty(); } + virtual bool empty() const = 0; + + virtual ~MyQueue() = default; }; -leetcode_232::MyQueue *leetcode_232::pure() { - return new Queue(); -} +class Solution { +private: + class Queue : public MyQueue { + private: + stack sta1{}, sta2{}; + public: + Queue() = default; + void push(int x) override { + sta1.push(x); + } + + int pop() override { + const auto head = this->peek(); + sta2.pop(); + return head; + } + + int peek() override { + if (sta2.empty()) { + while (!sta1.empty()) { + sta2.push(sta1.top()); + sta1.pop(); + } + } + return sta2.top(); + } + + bool empty() const override { return sta1.empty() && sta2.empty(); } + }; + +public: + MyQueue *pure() { + return new Queue(); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_232_test.cpp b/algorithm/stack/leetcode_232_test.cpp new file mode 100644 index 00000000..76452e9a --- /dev/null +++ b/algorithm/stack/leetcode_232_test.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Plan 数据结构入门 Day9 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_232_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_232_TEST_HPP + +#include "leetcode_232.cpp" +#include +#include + +namespace leetcode_232 { + +TEST_CASE("1 [test_232]", "[test_232]") { + Solution solution; + const auto pointer = std::unique_ptr(solution.pure()); + CHECK(pointer->empty()); + pointer->push(1); + pointer->push(2); + CHECK(1 == pointer->peek()); + CHECK(1 == pointer->pop()); + CHECK_FALSE(pointer->empty()); + CHECK(2 == pointer->peek()); + CHECK(2 == pointer->pop()); + CHECK(pointer->empty()); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_232_TEST_HPP diff --git a/algorithm/stack/leetcode_232_test.hpp b/algorithm/stack/leetcode_232_test.hpp deleted file mode 100644 index ba4fc5a7..00000000 --- a/algorithm/stack/leetcode_232_test.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Plan 数据结构入门 Day9 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_232_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_232_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_232 { - -struct leetcode_232 { - class MyQueue { - public: - MyQueue() = default; - - virtual void push(int x) = 0; - - virtual int pop() = 0; - - virtual int peek() = 0; - - virtual bool empty() const = 0; - - virtual ~MyQueue() = default; - }; - - static MyQueue *pure(); -}; - -TEST_CASE("1 [test_232]", "[test_232]") { - const auto pointer = std::unique_ptr(leetcode_232::pure()); - CHECK(pointer->empty()); - pointer->push(1); - pointer->push(2); - CHECK(1 == pointer->peek()); - CHECK(1 == pointer->pop()); - CHECK_FALSE(pointer->empty()); - CHECK(2 == pointer->peek()); - CHECK(2 == pointer->pop()); - CHECK(pointer->empty()); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_232_TEST_HPP diff --git a/algorithm/stack/leetcode_316.cpp b/algorithm/stack/leetcode_316.cpp index 8c6a44d5..b238b4d1 100644 --- a/algorithm/stack/leetcode_316.cpp +++ b/algorithm/stack/leetcode_316.cpp @@ -1,56 +1,67 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag stack //@Tag 栈 //@Tag 单调栈 -#include "leetcode_316_test.hpp" +#ifdef ALGORITHM_TEST_MACRO + #include +#include +#include +#include +#include +#include +#include namespace leetcode_316 { using std::stack; +using std::string; +using std::string_view; +using std::vector; +#endif -string leetcode_316::removeDuplicateLetters(string_view str) { - if (str.size() <= 1) { - return string{str}; - } - // 这个最重要的一点在于从"找到" - // -> 每次删除一个char,删掉哪一个可以得到阶段性最小值? - // 删掉从左向右数,第一个大于右边char的char - // 再基于此得到一次性单调栈模型, 最后产出多次单调栈模型 - std::array uset{0}, stackSize{0}; - for (const auto ch: str) { - uset[ch]++; - } - stack sta; - for (size_t i{0}; i < str.size(); i++) { - const auto ch = str[i]; - if (stackSize[ch] == 0) { - while (!sta.empty() && ch < str[sta.top()]) { - const auto topCH{str[sta.top()]}; - if (uset[topCH] > 0) { - stackSize[topCH] = 0; - sta.pop(); - } else { - break; +class Solution { +public: + string removeDuplicateLetters(string_view str) { + if (str.size() <= 1) { + return string{str}; + } + // 这个最重要的一点在于从"找到" + // -> 每次删除一个char,删掉哪一个可以得到阶段性最小值? + // 删掉从左向右数,第一个大于右边char的char + // 再基于此得到一次性单调栈模型, 最后产出多次单调栈模型 + std::array uset{0}, stackSize{0}; + for (const auto ch: str) { + uset[ch]++; + } + stack sta; + for (size_t i{0}; i < str.size(); i++) { + const auto ch = str[i]; + if (stackSize[ch] == 0) { + while (!sta.empty() && ch < str[sta.top()]) { + const auto topCH{str[sta.top()]}; + if (uset[topCH] > 0) { + stackSize[topCH] = 0; + sta.pop(); + } else { + break; + } } + stackSize[ch] = 1; + sta.push(i); } - stackSize[ch] = 1; - sta.push(i); + uset[ch]--; } - uset[ch]--; - } - vector will_return{}; - while (!sta.empty()) { - will_return.push_back(str[sta.top()]); - sta.pop(); + vector will_return{}; + while (!sta.empty()) { + will_return.push_back(str[sta.top()]); + sta.pop(); + } + return {will_return.crbegin(), will_return.crend()}; } - return {will_return.crbegin(), will_return.crend()}; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_316_test.hpp b/algorithm/stack/leetcode_316_test.cpp similarity index 51% rename from algorithm/stack/leetcode_316_test.hpp rename to algorithm/stack/leetcode_316_test.cpp index ab6431fa..869753a5 100644 --- a/algorithm/stack/leetcode_316_test.hpp +++ b/algorithm/stack/leetcode_316_test.cpp @@ -1,54 +1,49 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_316_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_316_TEST_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_316_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_316_TEST_HPP #include -#include +#include "leetcode_316.cpp" namespace leetcode_316 { -using std::string; -using std::string_view; - -struct leetcode_316 { - static string removeDuplicateLetters(string_view s); -}; using Catch::Matchers::Equals; TEST_CASE("2 [test_316]", "[test_316]") { static constexpr const char *const input{"cbacdcbc"}, *const output{"acdb"}; - CHECK_THAT(output, Equals(leetcode_316::removeDuplicateLetters(input))); + Solution solution; + CHECK_THAT(output, Equals(solution.removeDuplicateLetters(input))); } TEST_CASE("1 [test_316]", "[test_316]") { static constexpr const char *const input{"bcabc"}, *const output{"abc"}; - CHECK_THAT(output, Equals(leetcode_316::removeDuplicateLetters(input))); + Solution solution; + CHECK_THAT(output, Equals(solution.removeDuplicateLetters(input))); } TEST_CASE("3 [test_316]", "[test_316]") { static constexpr const char *const input{"cdadabcc"}, *const output{"adbc"}; - CHECK_THAT(output, Equals(leetcode_316::removeDuplicateLetters(input))); + Solution solution; + CHECK_THAT(output, Equals(solution.removeDuplicateLetters(input))); } TEST_CASE("4 [test_316]", "[test_316]") { static constexpr const char *const input{"abcd"}, *const output{"abcd"}; - CHECK_THAT(output, Equals(leetcode_316::removeDuplicateLetters(input))); + Solution solution; + CHECK_THAT(output, Equals(solution.removeDuplicateLetters(input))); } TEST_CASE("5 [test_316]", "[test_316]") { static constexpr const char *const input{"bddbccd"}, *const output{"bcd"}; - CHECK_THAT(output, Equals(leetcode_316::removeDuplicateLetters(input))); + Solution solution; + CHECK_THAT(output, Equals(solution.removeDuplicateLetters(input))); } TEST_CASE("6 [test_316]", "[test_316]") { static constexpr const char *const input{"thesqtitxyetpxloeevdeqifkz"}; - leetcode_316::removeDuplicateLetters(input); + Solution solution; + solution.removeDuplicateLetters(input); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_316_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_316_TEST_HPP diff --git a/algorithm/stack/leetcode_32.cpp b/algorithm/stack/leetcode_32.cpp index bcece174..630c6b42 100644 --- a/algorithm/stack/leetcode_32.cpp +++ b/algorithm/stack/leetcode_32.cpp @@ -1,41 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_32_test.hpp" #include #include +#include +#include +#include namespace leetcode_32 { using std::stack; using std::vector; +using std::string; +#endif -int32_t leetcode_32::longestValidParentheses(const string &s) { - const auto s_size{s.size()}; - if (s_size <= 1) { - return 0; - } - vector DP(s_size, 0); - for (std::remove_const::type i{1}; i < s_size; i++) { - if (s[i] == ')') { - if (s[i - 1] == '(') { - DP[i] = 2; - if (i >= 2) { - DP[i] += DP[i - 2]; - } - } else if (i - DP[i - 1] > 0 && s[i - DP[i - 1] - 1] == '(') { - DP[i] = DP[i - 1] + 2; - if (static_cast(i) >= DP[i - 1] + 2) { - DP[i] += DP[i - DP[i - 1] - 2]; +class Solution { +public: + int32_t longestValidParentheses(const string &s) { + const auto s_size{s.size()}; + if (s_size <= 1) { + return 0; + } + vector DP(s_size, 0); + for (std::remove_const::type i{1}; i < s_size; i++) { + if (s[i] == ')') { + if (s[i - 1] == '(') { + DP[i] = 2; + if (i >= 2) { + DP[i] += DP[i - 2]; + } + } else if (i - DP[i - 1] > 0 && s[i - DP[i - 1] - 1] == '(') { + DP[i] = DP[i - 1] + 2; + if (static_cast(i) >= DP[i - 1] + 2) { + DP[i] += DP[i - DP[i - 1] - 2]; + } } } } + // dp[0] is always 0 + return *std::max_element(DP.cbegin() + 1, DP.cend()); } - // dp[0] is always 0 - return *std::max_element(DP.cbegin() + 1, DP.cend()); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_321.cpp b/algorithm/stack/leetcode_321.cpp index 2a5d48bc..6c6f8c61 100644 --- a/algorithm/stack/leetcode_321.cpp +++ b/algorithm/stack/leetcode_321.cpp @@ -1,100 +1,109 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ - -#include "leetcode_321_test.hpp" #include +#include +#include +#include +#include +#include namespace leetcode_321 { using std::stack; +using std::vector; +#endif -int32_t compare(const vector &fst, size_t fst_size, const vector &snd, size_t snd_size) { - if (fst.size() < snd.size()) { - return -1; - } else if (fst.size() > snd.size()) { - return 1; - } else { - if (fst_size == fst.size()) { - // 这个情况说明两者size相同并且全部相同,那就直接给1,-1都可以了 - return 1; - } else if (fst[fst_size] > snd[snd_size]) { - return 1; - } else if (fst[fst_size] < snd[snd_size]) { +class Solution { +private: + int32_t compare(const vector &fst, size_t fst_size, const vector &snd, size_t snd_size) { + if (fst.size() < snd.size()) { return -1; + } else if (fst.size() > snd.size()) { + return 1; } else { - return compare(fst, fst_size + 1, snd, snd_size + 1); + if (fst_size == fst.size()) { + // 这个情况说明两者size相同并且全部相同,那就直接给1,-1都可以了 + return 1; + } else if (fst[fst_size] > snd[snd_size]) { + return 1; + } else if (fst[fst_size] < snd[snd_size]) { + return -1; + } else { + return compare(fst, fst_size + 1, snd, snd_size + 1); + } } } -} -vector leetcode_321::maxNumber(const vector &nums1, const vector &nums2, size_t k) { - const auto nums1_size{nums1.size()}, nums2_size{nums2.size()}; - vector backup{}; - for (size_t x = k > nums2_size ? k - nums2_size : 0, maxV{std::min(k, nums1_size)}; x <= maxV; x++) { - const auto x_size{x}, y_size{k - x}; - // 这里得注意, 先保证序列整体大小优先, - // 再考虑保证整体单调栈特性 - const auto order = [](const vector &num, size_t needSize) { - size_t remainSize = num.size() - needSize; - stack sta; - for (const auto ch: num) { - while (remainSize > 0 && !sta.empty() && ch > sta.top()) { +public: + vector maxNumber(const vector &nums1, const vector &nums2, size_t k) { + const auto nums1_size{nums1.size()}, nums2_size{nums2.size()}; + vector backup{}; + for (size_t x = k > nums2_size ? k - nums2_size : 0, maxV{std::min(k, nums1_size)}; x <= maxV; x++) { + const auto x_size{x}, y_size{k - x}; + // 这里得注意, 先保证序列整体大小优先, + // 再考虑保证整体单调栈特性 + const auto order = [](const vector &num, size_t needSize) { + size_t remainSize = num.size() - needSize; + stack sta; + for (const auto ch: num) { + while (remainSize > 0 && !sta.empty() && ch > sta.top()) { + sta.pop(); + remainSize--; + } + sta.push(ch); + } + vector reserve{}, will_return{}; + while (!sta.empty()) { + reserve.push_back(sta.top()); sta.pop(); - remainSize--; } - sta.push(ch); + will_return.resize(reserve.size()); + std::copy(reserve.crbegin(), reserve.crend(), will_return.begin()); + return will_return; + }; + const auto max1 = order(nums1, x_size); + const auto max2 = order(nums2, y_size); + if (x_size > max1.size() || y_size > max2.size()) { + // 考虑了序列整体大小还是无法满足条件的情况 + continue; } - vector reserve{}, will_return{}; - while (!sta.empty()) { - reserve.push_back(sta.top()); - sta.pop(); - } - will_return.resize(reserve.size()); - std::copy(reserve.crbegin(), reserve.crend(), will_return.begin()); - return will_return; - }; - const auto max1 = order(nums1, x_size); - const auto max2 = order(nums2, y_size); - if (x_size > max1.size() || y_size > max2.size()) { - // 考虑了序列整体大小还是无法满足条件的情况 - continue; - } - const std::function comp = [&max1, &max2, &comp, x_size, y_size] - (size_t fst, size_t snd) { - if (fst == x_size) { - // 分别讨论有顺序作用 - return -1; - } else if (snd == y_size) { - // 分别讨论有顺序作用,不能合并 - return 1; - } else if (max1[fst] > max2[snd]) { - return 1; - } else if (max1[fst] < max2[snd]) { - return -1; - } else { - return comp(fst + 1, snd + 1); + const std::function comp = [&max1, &max2, &comp, x_size, y_size] + (size_t fst, size_t snd) { + if (fst == x_size) { + // 分别讨论有顺序作用 + return -1; + } else if (snd == y_size) { + // 分别讨论有顺序作用,不能合并 + return 1; + } else if (max1[fst] > max2[snd]) { + return 1; + } else if (max1[fst] < max2[snd]) { + return -1; + } else { + return comp(fst + 1, snd + 1); + } + }; + vector will_return{}; + for (size_t fst{0}, snd{0}, fst_size{x_size}, snd_size{y_size}; fst < fst_size || snd < snd_size;) { + const auto choice = comp(fst, snd); + if (choice == 1) { + will_return.push_back(max1[fst]); + fst++; + } else if (choice == -1) { + will_return.push_back(max2[snd]); + snd++; + } } - }; - vector will_return{}; - for (size_t fst{0}, snd{0}, fst_size{x_size}, snd_size{y_size}; fst < fst_size || snd < snd_size;) { - const auto choice = comp(fst, snd); - if (choice == 1) { - will_return.push_back(max1[fst]); - fst++; - } else if (choice == -1) { - will_return.push_back(max2[snd]); - snd++; + if (compare(backup, 0, will_return, 0) < 0) { + std::swap(backup, will_return); } } - if (compare(backup, 0, will_return, 0) < 0) { - std::swap(backup, will_return); - } + return backup; } - return backup; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_321_test.hpp b/algorithm/stack/leetcode_321_test.cpp similarity index 55% rename from algorithm/stack/leetcode_321_test.hpp rename to algorithm/stack/leetcode_321_test.cpp index 84a56c33..6f5082a9 100644 --- a/algorithm/stack/leetcode_321_test.hpp +++ b/algorithm/stack/leetcode_321_test.cpp @@ -1,36 +1,25 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag stack //@Tag 栈 //@Tag 单调栈 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_321_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_321_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_321_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_321_TEST_HPP #include -#include -#include -#include +#include "leetcode_321.cpp" -namespace leetcode_321 { using std::vector; - -struct leetcode_321 { - static vector maxNumber(const vector &nums1, const vector &nums2, size_t k); -}; - using Catch::Matchers::Equals; +namespace leetcode_321 { TEST_CASE("2 [test_321]", "[test_321]") { const vector nums1{6, 7}; const vector nums2{6, 0, 7}; static constexpr const auto k{5}; const vector number{6, 7, 6, 0, 7}; - CHECK_THAT(number, Equals(leetcode_321::maxNumber(nums1, nums2, k))); + Solution solution; + CHECK_THAT(number, Equals(solution.maxNumber(nums1, nums2, k))); } TEST_CASE("3 [test_321]", "[test_321]") { @@ -38,7 +27,8 @@ TEST_CASE("3 [test_321]", "[test_321]") { const vector nums2{8, 9}; static constexpr const auto k{3}; const vector number{9, 8, 9}; - CHECK_THAT(number, Equals(leetcode_321::maxNumber(nums1, nums2, k))); + Solution solution; + CHECK_THAT(number, Equals(solution.maxNumber(nums1, nums2, k))); } TEST_CASE("1 [test_321]", "[test_321]") { @@ -46,9 +36,8 @@ TEST_CASE("1 [test_321]", "[test_321]") { const vector nums2{9, 1, 2, 5, 8, 3}; static constexpr const auto k{5}; const vector number{9, 8, 6, 5, 3}; - CHECK_THAT(number, Equals(leetcode_321::maxNumber(nums1, nums2, k))); + Solution solution; + CHECK_THAT(number, Equals(solution.maxNumber(nums1, nums2, k))); } - - } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_321_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_321_TEST_HPP diff --git a/algorithm/stack/leetcode_32_test.cpp b/algorithm/stack/leetcode_32_test.cpp new file mode 100644 index 00000000..16a4dcce --- /dev/null +++ b/algorithm/stack/leetcode_32_test.cpp @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag stack +//@Tag 栈 +//@Tag 动态规划 +//@Tag DP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_32_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_32_TEST_HPP + +#include +#include "leetcode_32.cpp" + +namespace leetcode_32 { + +TEST_CASE("test case 1 [test_32]", "[test_32]") { + Solution solution; + CHECK(0 == solution.longestValidParentheses("")); + CHECK(2 == solution.longestValidParentheses("(()")); + CHECK(2 == solution.longestValidParentheses("())")); + CHECK(4 == solution.longestValidParentheses(")()())")); + CHECK(6 == solution.longestValidParentheses("()(())")); + CHECK(2 == solution.longestValidParentheses("()(()")); + CHECK(6 == solution.longestValidParentheses("(()())")); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_32_TEST_HPP diff --git a/algorithm/stack/leetcode_32_test.hpp b/algorithm/stack/leetcode_32_test.hpp deleted file mode 100644 index 81f7e6e4..00000000 --- a/algorithm/stack/leetcode_32_test.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag stack -//@Tag 栈 -//@Tag 动态规划 -//@Tag DP -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_32_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_32_TEST_HPP - -#include -#include - -namespace leetcode_32 { -using std::string; - -struct leetcode_32 { - static int32_t longestValidParentheses(const string &s); -}; - -TEST_CASE("test case 1 [test_32]", "[test_32]") { - CHECK(0 == leetcode_32::longestValidParentheses("")); - CHECK(2 == leetcode_32::longestValidParentheses("(()")); - CHECK(2 == leetcode_32::longestValidParentheses("())")); - CHECK(4 == leetcode_32::longestValidParentheses(")()())")); - CHECK(6 == leetcode_32::longestValidParentheses("()(())")); - CHECK(2 == leetcode_32::longestValidParentheses("()(()")); - CHECK(6 == leetcode_32::longestValidParentheses("(()())")); -} - - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_32_TEST_HPP diff --git a/algorithm/stack/leetcode_42.cpp b/algorithm/stack/leetcode_42.cpp index b6d165a3..07317459 100644 --- a/algorithm/stack/leetcode_42.cpp +++ b/algorithm/stack/leetcode_42.cpp @@ -1,93 +1,103 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_42_test.hpp" #include +#include +#include +#include +#include namespace leetcode_42 { using std::stack; +using std::vector; +#endif -int32_t leetcode_42::trap(const vector &height) { - int32_t will_return{0}; - stack sta; - const auto height_size{height.size()}; - for (size_t i{0}; i < height_size; i++) { - // 取得其左侧, 小于等于当前高度 的坐标 - // 单调栈,形象地说,水位是 一层一层 向上加的 - while (!sta.empty() && height[i] > height[sta.top()]) { - const auto top{sta.top()}; - sta.pop(); - if (sta.empty()) { - break; +class Solution { +public: + int32_t trap(const vector &height) { + int32_t will_return{0}; + stack sta; + const auto height_size{height.size()}; + for (size_t i{0}; i < height_size; i++) { + // 取得其左侧, 小于等于当前高度 的坐标 + // 单调栈,形象地说,水位是 一层一层 向上加的 + while (!sta.empty() && height[i] > height[sta.top()]) { + const auto top{sta.top()}; + sta.pop(); + if (sta.empty()) { + break; + } + const auto left{sta.top()}; + const auto width{i - left - 1}; + const auto h{std::min(height.at(left), height.at(i)) - height.at(top)}; + will_return += static_cast(h * width); } - const auto left{sta.top()}; - const auto width{i - left - 1}; - const auto h{std::min(height.at(left), height.at(i)) - height.at(top)}; - will_return += static_cast(h * width); + sta.push(i); } - sta.push(i); + return will_return; } - return will_return; -} -int32_t leetcode_42::trapDPLoca(const vector &height) { + int32_t trapDPLoca(const vector &height) { - // 水位为其 min(左侧最高值,水位最高值) - 本身的值 - const auto height_size{height.size()}; - vector left(height_size + 1, 0), right(height_size + 1, 0); - // 对左侧来说,其左侧为无限低, so do 右侧 - left[0] = 0; - right[height_size] = height_size - 1; - for (size_t i{1}; i < height_size; i++) { - if (height[i] <= height[left[i - 1]]) { - left[i] = left[i - 1]; - } else { - left[i] = i; + // 水位为其 min(左侧最高值,水位最高值) - 本身的值 + const auto height_size{height.size()}; + vector left(height_size + 1, 0), right(height_size + 1, 0); + // 对左侧来说,其左侧为无限低, so do 右侧 + left[0] = 0; + right[height_size] = height_size - 1; + for (size_t i{1}; i < height_size; i++) { + if (height[i] <= height[left[i - 1]]) { + left[i] = left[i - 1]; + } else { + left[i] = i; + } } - } - for (size_t i{height_size - 1}; i > 0; i--) { - if (height[i] <= height[right[i + 1]]) { - right[i] = right[i + 1]; - } else { - right[i] = i; + for (size_t i{height_size - 1}; i > 0; i--) { + if (height[i] <= height[right[i + 1]]) { + right[i] = right[i + 1]; + } else { + right[i] = i; + } } + int32_t will_return{0}; + for (size_t i{0}; i < height_size; i++) { + will_return += std::max(0, std::min(height[left[i]], height[right[i + 1]]) - height[i]); + } + return will_return; } - int32_t will_return{0}; - for (size_t i{0}; i < height_size; i++) { - will_return += std::max(0, std::min(height[left[i]], height[right[i + 1]]) - height[i]); - } - return will_return; -} -int32_t leetcode_42::trapDPHeight(const vector &height) { - // 水位为其 min(左侧最高值,水位最高值) - 本身的值 - const auto height_size{height.size()}; - vector left(height_size + 1, 0), right(height_size + 1, 0); - // 对左侧来说,其左侧为无限低, so do 右侧 - left[0] = height[0]; - right[height_size] = height[height_size - 1]; - for (size_t i{1}; i < height_size; i++) { - if (height[i] <= left[i - 1]) { - left[i] = left[i - 1]; - } else { - left[i] = height[i]; + int32_t trapDPHeight(const vector &height) { + // 水位为其 min(左侧最高值,水位最高值) - 本身的值 + const auto height_size{height.size()}; + vector left(height_size + 1, 0), right(height_size + 1, 0); + // 对左侧来说,其左侧为无限低, so do 右侧 + left[0] = height[0]; + right[height_size] = height[height_size - 1]; + for (size_t i{1}; i < height_size; i++) { + if (height[i] <= left[i - 1]) { + left[i] = left[i - 1]; + } else { + left[i] = height[i]; + } } - } - for (size_t i{height_size - 1}; i > 0; i--) { - if (height[i] <= right[i + 1]) { - right[i] = right[i + 1]; - } else { - right[i] = height[i]; + for (size_t i{height_size - 1}; i > 0; i--) { + if (height[i] <= right[i + 1]) { + right[i] = right[i + 1]; + } else { + right[i] = height[i]; + } } + int32_t will_return{0}; + for (size_t i{0}; i < height_size; i++) { + will_return += std::max(0, std::min(left[i], right[i + 1]) - height[i]); + } + return will_return; } - int32_t will_return{0}; - for (size_t i{0}; i < height_size; i++) { - will_return += std::max(0, std::min(left[i], right[i + 1]) - height[i]); - } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_42_test.cpp b/algorithm/stack/leetcode_42_test.cpp new file mode 100644 index 00000000..ffa200cb --- /dev/null +++ b/algorithm/stack/leetcode_42_test.cpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag stack +//@Tag 栈 +//@Tag 单调栈 +//@Tag DP +//@Tag 动态规划 +//@Plan 动态规划入门 Day9 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_42_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_42_TEST_HPP + +#include +#include "leetcode_42.cpp" + +namespace leetcode_42 { + +using std::vector; + +TEST_CASE("test case 2 [test _42]", "[test _42]") { + const vector input{4, 2, 0, 3, 2, 5}; + static constexpr const auto result{9}; + Solution solution; + CHECK(result == solution.trap(input)); + CHECK(result == solution.trapDPLoca(input)); + CHECK(result == solution.trapDPHeight(input)); +} + +TEST_CASE("test case 1 [test _42]", "[test _42]") { + const vector input{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; + static constexpr const auto result{6}; + Solution solution; + CHECK(result == solution.trap(input)); + CHECK(result == solution.trapDPLoca(input)); + CHECK(result == solution.trapDPHeight(input)); +} + +TEST_CASE("test case 3 [test _42]", "[test _42]") { + const vector input{0, 1, 0, 3, 1, 0, 1, 3, 2, 1, 2, 1}; + static constexpr const auto result{9}; + Solution solution; + CHECK(result == solution.trap(input)); + CHECK(result == solution.trapDPLoca(input)); + CHECK(result == solution.trapDPHeight(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_42_TEST_HPP diff --git a/algorithm/stack/leetcode_42_test.hpp b/algorithm/stack/leetcode_42_test.hpp deleted file mode 100644 index b629ca39..00000000 --- a/algorithm/stack/leetcode_42_test.hpp +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag stack -//@Tag 栈 -//@Tag 单调栈 -//@Tag DP -//@Tag 动态规划 -//@Plan 动态规划入门 Day9 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_42_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_42_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_42 { -using std::vector; - -struct leetcode_42 { - static int32_t trap(const vector &height); - - static int32_t trapDPLoca(const vector &height); - - static int32_t trapDPHeight(const vector &height); -}; - -TEST_CASE("test case 2 [test _42]", "[test _42]") { - const vector input{4, 2, 0, 3, 2, 5}; - static constexpr const auto result{9}; - CHECK(result == leetcode_42::trap(input)); - CHECK(result == leetcode_42::trapDPLoca(input)); - CHECK(result == leetcode_42::trapDPHeight(input)); -} - -TEST_CASE("test case 1 [test _42]", "[test _42]") { - const vector input{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; - static constexpr const auto result{6}; - CHECK(result == leetcode_42::trap(input)); - CHECK(result == leetcode_42::trapDPLoca(input)); - CHECK(result == leetcode_42::trapDPHeight(input)); -} - -TEST_CASE("test case 3 [test _42]", "[test _42]") { - const vector input{0, 1, 0, 3, 1, 0, 1, 3, 2, 1, 2, 1}; - static constexpr const auto result{9}; - CHECK(result == leetcode_42::trap(input)); - CHECK(result == leetcode_42::trapDPLoca(input)); - CHECK(result == leetcode_42::trapDPHeight(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_42_TEST_HPP diff --git a/algorithm/stack/leetcode_678.cpp b/algorithm/stack/leetcode_678.cpp index d53975d1..eeec2a60 100644 --- a/algorithm/stack/leetcode_678.cpp +++ b/algorithm/stack/leetcode_678.cpp @@ -1,71 +1,78 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag stack //@Tag 栈 //@Tag 贪心 -#include "leetcode_678_test.hpp" +#ifdef ALGORITHM_TEST_MACRO + #include +#include +#include +#include namespace leetcode_678 { using std::stack; +using std::string; +#endif -bool leetcode_678::checkValidString(const string &s) { - int32_t order{0}; - stack s1{}, s2{}; - for (auto &&ch: s) { - if (ch == '(') { - s1.push(order); - } else if (ch == '*') { - s2.push(order); - } else { - if (!s1.empty()) { - s1.pop(); - } else if (!s2.empty()) { - s2.pop(); +class Solution { +public: + bool checkValidString(const string &s) { + int32_t order{0}; + stack s1{}, s2{}; + for (auto &&ch: s) { + if (ch == '(') { + s1.push(order); + } else if (ch == '*') { + s2.push(order); } else { - return false; + if (!s1.empty()) { + s1.pop(); + } else if (!s2.empty()) { + s2.pop(); + } else { + return false; + } } + order++; } - order++; - } - if (s1.size() > s2.size()) { - return false; - } - while (!s1.empty() && !s2.empty()) { - if (s1.top() > s2.top()) { + if (s1.size() > s2.size()) { return false; } - s1.pop(); - s2.pop(); - } - return true; -} - -bool leetcode_678::checkValidString2(const string &s) { - int32_t low{0}, high{0}; - for (auto &&ch: s) { - if (ch == '(') { - low++; - high++; - } else if (ch == '*') { - low = std::max(0, low - 1); // mayBe match a ) - high++; - } else { - high--; - low = std::max(0, low - 1); - if (high < 0) { + while (!s1.empty() && !s2.empty()) { + if (s1.top() > s2.top()) { return false; } + s1.pop(); + s2.pop(); } - } - if (low == 0) { return true; } - return false; -} + + bool checkValidString2(const string &s) { + int32_t low{0}, high{0}; + for (auto &&ch: s) { + if (ch == '(') { + low++; + high++; + } else if (ch == '*') { + low = std::max(0, low - 1); // mayBe match a ) + high++; + } else { + high--; + low = std::max(0, low - 1); + if (high < 0) { + return false; + } + } + } + if (low == 0) { + return true; + } + return false; + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_678_test.cpp b/algorithm/stack/leetcode_678_test.cpp new file mode 100644 index 00000000..12217063 --- /dev/null +++ b/algorithm/stack/leetcode_678_test.cpp @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_678_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_678_TEST_HPP + +#include +#include "leetcode_678.cpp" + +namespace leetcode_678 { + +TEST_CASE("1 [test_678]", "[test_678]") { + Solution solution; + CHECK(solution.checkValidString("()")); + CHECK(solution.checkValidString("(*)")); + CHECK(solution.checkValidString("(*))")); +} + +TEST_CASE("2 [test_678]", "[test_678]") { + Solution solution; + CHECK_FALSE(solution.checkValidString( + "(((((*(((((*((**(((*)*((((**))*)*)))))))))((*(((((**(**)")); + CHECK_FALSE(solution.checkValidString( + "(((((*(()((((*((**(((()()*)()()()*((((**)())*)*)))))))(())(()))())((*()()(((()((()*(())*(()**)()(())")); +} + +TEST_CASE("2-1 [test_678]", "[test_678]") { + Solution solution; + CHECK(solution.checkValidString2("()")); + CHECK(solution.checkValidString2("(*)")); + CHECK(solution.checkValidString2("(*))")); +} + +TEST_CASE("2-2 [test_678]", "[test_678]") { + Solution solution; + CHECK_FALSE(solution.checkValidString2( + "(((((*(((((*((**(((*)*((((**))*)*)))))))))((*(((((**(**)")); + CHECK_FALSE(solution.checkValidString2( + "(((((*(()((((*((**(((()()*)()()()*((((**)())*)*)))))))(())(()))())((*()()(((()((()*(())*(()**)()(())")); + +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_678_TEST_HPP diff --git a/algorithm/stack/leetcode_678_test.hpp b/algorithm/stack/leetcode_678_test.hpp deleted file mode 100644 index 3cff1224..00000000 --- a/algorithm/stack/leetcode_678_test.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_678_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_678_TEST_HPP - -#include -#include - -namespace leetcode_678 { -using std::string; - -struct leetcode_678 { - static bool checkValidString(const string &s); - - static bool checkValidString2(const string &s); -}; - -TEST_CASE("1 [test_678]", "[test_678]") { - CHECK(leetcode_678::checkValidString("()")); - CHECK(leetcode_678::checkValidString("(*)")); - CHECK(leetcode_678::checkValidString("(*))")); -} - -TEST_CASE("2 [test_678]", "[test_678]") { - CHECK_FALSE(leetcode_678::checkValidString( - "(((((*(((((*((**(((*)*((((**))*)*)))))))))((*(((((**(**)")); - CHECK_FALSE(leetcode_678::checkValidString( - "(((((*(()((((*((**(((()()*)()()()*((((**)())*)*)))))))(())(()))())((*()()(((()((()*(())*(()**)()(())")); -} - -TEST_CASE("2-1 [test_678]", "[test_678]") { - CHECK(leetcode_678::checkValidString2("()")); - CHECK(leetcode_678::checkValidString2("(*)")); - CHECK(leetcode_678::checkValidString2("(*))")); -} - -TEST_CASE("2-2 [test_678]", "[test_678]") { - CHECK_FALSE(leetcode_678::checkValidString2( - "(((((*(((((*((**(((*)*((((**))*)*)))))))))((*(((((**(**)")); - CHECK_FALSE(leetcode_678::checkValidString2( - "(((((*(()((((*((**(((()()*)()()()*((((**)())*)*)))))))(())(()))())((*()()(((()((()*(())*(()**)()(())")); - -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_678_TEST_HPP diff --git a/algorithm/stack/leetcode_84_85.cpp b/algorithm/stack/leetcode_84_85.cpp index 9ee9332c..e3c43d1c 100644 --- a/algorithm/stack/leetcode_84_85.cpp +++ b/algorithm/stack/leetcode_84_85.cpp @@ -1,67 +1,72 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_84_85_test.hpp" #include +#include +#include +#include +#include namespace leetcode_84 { using std::stack; +using std::vector; +#endif -int32_t leetcode_84::largestRectangleArea(const vector &heights) { - const auto height_size{static_cast(heights.size())}; - // 我们要找到 左侧最近的 小于当前高度的 坐标 - // 极限模型: 一个从左到右单调增的序列,全部都是 i-1 - // 因此使用递增栈 - stack staL; - vector left(height_size); - for (int32_t i{0}; i < height_size; i++) { - while (!staL.empty() && heights[i] <= heights[staL.top()]) { - staL.pop(); +class Solution { +public: + int32_t largestRectangleArea(const vector &heights) { + const auto height_size{static_cast(heights.size())}; + // 我们要找到 左侧最近的 小于当前高度的 坐标 + // 极限模型: 一个从左到右单调增的序列,全部都是 i-1 + // 因此使用递增栈 + stack staL; + vector left(height_size); + for (int32_t i{0}; i < height_size; i++) { + while (!staL.empty() && heights[i] <= heights[staL.top()]) { + staL.pop(); + } + left[i] = staL.empty() ? -1 : staL.top(); + staL.push(i); } - left[i] = staL.empty() ? -1 : staL.top(); - staL.push(i); - } - stack staR; - vector right(height_size); - for (int32_t i{height_size - 1}; i >= 0; i--) { - while (!staR.empty() && heights[i] <= heights[staR.top()]) { - staR.pop(); + stack staR; + vector right(height_size); + for (int32_t i{height_size - 1}; i >= 0; i--) { + while (!staR.empty() && heights[i] <= heights[staR.top()]) { + staR.pop(); + } + right[i] = staR.empty() ? height_size : staR.top(); + staR.push(i); } - right[i] = staR.empty() ? height_size : staR.top(); - staR.push(i); - } - int32_t will_return{-1}; - for (int32_t i{0}; i < height_size; i++) { - will_return = std::max(will_return, (right[i] - left[i] - 1) * heights[i]); + int32_t will_return{-1}; + for (int32_t i{0}; i < height_size; i++) { + will_return = std::max(will_return, (right[i] - left[i] - 1) * heights[i]); + } + return will_return; } - return will_return; -} -} -namespace leetcode_85 { -using std::stack; -int32_t leetcode_85::maximalRectangle(const vector> &matrix) { - if (matrix.empty() || matrix.front().empty()) { - return 0; - } - const auto col_size{matrix.size()}, row_size{matrix.front().size()}; - vector> heights(col_size, vector(row_size, 0)); - for (size_t j{0}; j < row_size; ++j) { - heights[0][j] = matrix[0][j] - '0'; - } - int32_t will_return{leetcode_84::leetcode_84::largestRectangleArea({heights[0].cbegin(), heights[0].cend()})}; - for (size_t i{1}; i < col_size; ++i) { + int32_t maximalRectangle(const vector> &matrix) { + if (matrix.empty() || matrix.front().empty()) { + return 0; + } + const auto col_size{matrix.size()}, row_size{matrix.front().size()}; + vector> heights(col_size, vector(row_size, 0)); for (size_t j{0}; j < row_size; ++j) { - const auto now{(matrix[i][j] - '0')}; - heights[i][j] = now ? (now + heights[i - 1][j]) : 0; + heights[0][j] = matrix[0][j] - '0'; } - will_return = std::max(will_return, leetcode_84::leetcode_84::largestRectangleArea( - {heights[i].cbegin(), heights[i].cend()})); + int32_t will_return{largestRectangleArea({heights[0].cbegin(), heights[0].cend()})}; + for (size_t i{1}; i < col_size; ++i) { + for (size_t j{0}; j < row_size; ++j) { + const auto now{(matrix[i][j] - '0')}; + heights[i][j] = now ? (now + heights[i - 1][j]) : 0; + } + will_return = std::max(will_return, largestRectangleArea( + {heights[i].cbegin(), heights[i].cend()})); + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_84_85_test.hpp b/algorithm/stack/leetcode_84_85_test.cpp similarity index 61% rename from algorithm/stack/leetcode_84_85_test.hpp rename to algorithm/stack/leetcode_84_85_test.cpp index 5e2991be..f88b2a31 100644 --- a/algorithm/stack/leetcode_84_85_test.hpp +++ b/algorithm/stack/leetcode_84_85_test.cpp @@ -1,52 +1,41 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag stack //@Tag 栈 //@Tag 单调栈 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_84_85_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_84_85_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_84_85_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_84_85_TEST_HPP #include #include #include #include #include +#include "leetcode_84_85.cpp" -namespace leetcode_84 { using std::vector; - -struct leetcode_84 { - static int32_t largestRectangleArea(const vector &heights); -}; +namespace leetcode_84 { TEST_CASE("test case 1 [test_84]", "[test_84]") { const vector input{2, 1, 5, 6, 2, 3}; static constexpr const auto result{10}; - CHECK(result == leetcode_84::largestRectangleArea(input)); + Solution solution; + CHECK(result == solution.largestRectangleArea(input)); } TEST_CASE("test case 2 [test_84]", "[test_84]") { const vector input{4, 2, 0, 3, 2, 5}; static constexpr const auto result{6}; - CHECK(result == leetcode_84::largestRectangleArea(input)); + Solution solution; + CHECK(result == solution.largestRectangleArea(input)); } TEST_CASE("test case 3 [test_84]", "[test_84]") { const vector input{0, 1, 0, 3, 1, 0, 1, 3, 2, 1, 2, 1}; static constexpr const auto result{6}; - CHECK(result == leetcode_84::largestRectangleArea(input)); -} + Solution solution; + CHECK(result == solution.largestRectangleArea(input)); } -namespace leetcode_85 { - -struct leetcode_85 { - static int32_t maximalRectangle(const vector> &matrix); -}; TEST_CASE("test case 1 [test_85]", "[test_85]") { const vector> input{ @@ -56,13 +45,15 @@ TEST_CASE("test case 1 [test_85]", "[test_85]") { {'1', '0', '0', '1', '1'}, }; static constexpr const auto result{6}; - CHECK(result == leetcode_85::maximalRectangle(input)); + Solution solution; + CHECK(result == solution.maximalRectangle(input)); } TEST_CASE("test case 2 [test_85]", "[test_85]") { const vector> input{}; static constexpr const auto result{0}; - CHECK(result == leetcode_85::maximalRectangle(input)); + Solution solution; + CHECK(result == solution.maximalRectangle(input)); } TEST_CASE("test case 3 [test_85]", "[test_85]") { @@ -70,7 +61,8 @@ TEST_CASE("test case 3 [test_85]", "[test_85]") { {'1'} }; static constexpr const auto result{1}; - CHECK(result == leetcode_85::maximalRectangle(input)); + Solution solution; + CHECK(result == solution.maximalRectangle(input)); } TEST_CASE("test case 4 [test_85]", "[test_85]") { @@ -78,7 +70,8 @@ TEST_CASE("test case 4 [test_85]", "[test_85]") { {'0', '0'} }; static constexpr const auto result{0}; - CHECK(result == leetcode_85::maximalRectangle(input)); + Solution solution; + CHECK(result == solution.maximalRectangle(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STACK_LEETCODE_84_85_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STACK_LEETCODE_84_85_TEST_HPP diff --git a/algorithm/stack/leetcode_so_30.cpp b/algorithm/stack/leetcode_so_30.cpp index 6ad566d7..f42ea3ad 100644 --- a/algorithm/stack/leetcode_so_30.cpp +++ b/algorithm/stack/leetcode_so_30.cpp @@ -1,89 +1,109 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_so_30_test.hpp" #include +#include +#include namespace leetcode_so_30 { using std::stack; +#endif -struct MinStackPure : MinStack { -private: - stack sta1, sta2; +class MinStack { public: - MinStackPure() : MinStack() {}; - - void push(int x) override final { - sta1.push(x); - if (sta2.empty()) { - sta2.push(x); - } else { - const auto minV = std::min(x, sta2.top()); - sta2.push(minV); - } - } + MinStack() = default; - void pop() override final { - sta1.pop(); - sta2.pop(); - } + virtual void push(int x) = 0; - int top() override final { - return sta1.top(); - } + virtual void pop() = 0; - int min() override final { - return sta2.top(); - } + virtual int top() = 0; + + virtual int min() = 0; + + virtual ~MinStack() = default; }; -struct MinStackEffective : MinStack { +class Solution { private: - stack sta1, sta2; -public: - MinStackEffective() : MinStack() {}; + struct MinStackPure : MinStack { + private: + stack sta1, sta2; + public: + MinStackPure() : MinStack() {}; + + void push(int x) override final { + sta1.push(x); + if (sta2.empty()) { + sta2.push(x); + } else { + const auto minV = std::min(x, sta2.top()); + sta2.push(minV); + } + } + + void pop() override final { + sta1.pop(); + sta2.pop(); + } + + int top() override final { + return sta1.top(); + } + + int min() override final { + return sta2.top(); + } + }; - void push(int x) final { - if (sta2.empty()) { - sta2.push(x); - } else { - if (sta2.top() >= x) { + struct MinStackEffective : MinStack { + private: + stack sta1, sta2; + public: + MinStackEffective() : MinStack() {}; + + void push(int x) final { + if (sta2.empty()) { sta2.push(x); + } else { + if (sta2.top() >= x) { + sta2.push(x); + } } + sta1.push(x); } - sta1.push(x); - } - void pop() final { - if (sta1.empty()) { - return; + void pop() final { + if (sta1.empty()) { + return; + } + const auto top = this->top(); + sta1.pop(); + if (!sta2.empty() && top == this->min()) { + sta2.pop(); + } } - const auto top = this->top(); - sta1.pop(); - if (!sta2.empty() && top == this->min()) { - sta2.pop(); + + int top() final { + return sta1.top(); } - } - int top() final { - return sta1.top(); + int min() final { + return sta2.top(); + } + }; + +public: + MinStack *pure() { + return new MinStackPure(); } - int min() final { - return sta2.top(); + MinStack *effective() { + return new MinStackEffective(); } }; -MinStack *leetcode_so_30::pure() { - return new MinStackPure(); -} - -MinStack *leetcode_so_30::effective() { - return new MinStackEffective(); -} - +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/stack/leetcode_so_30_test.hpp b/algorithm/stack/leetcode_so_30_test.cpp similarity index 56% rename from algorithm/stack/leetcode_so_30_test.hpp rename to algorithm/stack/leetcode_so_30_test.cpp index 1f2b0013..75b40d5a 100644 --- a/algorithm/stack/leetcode_so_30_test.hpp +++ b/algorithm/stack/leetcode_so_30_test.cpp @@ -1,47 +1,24 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag stack //@Tag 栈 //@Plan 剑指OfferII-I Day01 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_30_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_30_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_30_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_30_TEST_HPP +#include "leetcode_so_30.cpp" #include #include namespace leetcode_so_30 { -struct MinStack { - MinStack() = default;; - - virtual void push(int x) = 0; - - virtual void pop() = 0; - - virtual int top() = 0; - - virtual int min() = 0; - - virtual ~MinStack() = default; -}; - -struct leetcode_so_30 { - static MinStack *pure(); - - static MinStack *effective(); -}; - TEST_CASE("test case pure-1 [test_sw_30]", "[test_sw_30]") { std::function lambda; + Solution solution; SECTION("pure") { - lambda = leetcode_so_30::pure; + lambda = [&solution]() { return solution.pure(); }; }SECTION("effective") { - lambda = leetcode_so_30::effective; + lambda = [&solution]() { return solution.effective(); }; } const auto ptr = std::unique_ptr(lambda()); ptr->push(0); @@ -54,10 +31,11 @@ TEST_CASE("test case pure-1 [test_sw_30]", "[test_sw_30]") { TEST_CASE("test case pure-2 [test_sw_30]", "[test_sw_30]") { std::function lambda; + Solution solution; SECTION("pure") { - lambda = leetcode_so_30::pure; + lambda = [&solution]() { return solution.pure(); }; }SECTION("effective") { - lambda = leetcode_so_30::effective; + lambda = [&solution]() { return solution.effective(); }; } const auto ptr = std::unique_ptr(lambda()); ptr->push(-2); @@ -69,5 +47,6 @@ TEST_CASE("test case pure-2 [test_sw_30]", "[test_sw_30]") { CHECK(-2 == ptr->min()); CHECK(0 == ptr->top()); } + } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_30_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_QUEUE_LEETCODE_SO_30_TEST_HPP diff --git a/algorithm/string/CMakeLists.txt b/algorithm/string/CMakeLists.txt index 3a131362..a5bd4693 100644 --- a/algorithm/string/CMakeLists.txt +++ b/algorithm/string/CMakeLists.txt @@ -15,10 +15,10 @@ LIST(APPEND dependencies 1392 1408) LIST(TRANSFORM dependencies PREPEND leetcode_) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) - target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE CS203_DSAA_TEST_MACRO) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) unset(elementName) endforeach () diff --git a/algorithm/string/leetcode_12.cpp b/algorithm/string/leetcode_12.cpp index da1bb0da..dddaae88 100644 --- a/algorithm/string/leetcode_12.cpp +++ b/algorithm/string/leetcode_12.cpp @@ -1,47 +1,57 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include +#include +namespace leetcode_12 { +using std::string; +using std::array; +using std::vector; +#endif -*/ -#include "leetcode_12_test.hpp" +class Solution { +public: + string intToRoman_2(int num) { + if (num > 1000) { + return "M" + intToRoman(num - 1000); + } else if (num > 100) { + static const array hundres = { + "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "M"}; + return hundres[num / 100] + intToRoman(num % 100); + } else if (num > 10) { + static const array tens = { + "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "C"}; + return tens[num / 10] + intToRoman(num % 10); + } else if (num <= 10) { + static const array ones = { + "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"}; + return ones[num]; + } + return "should reach there"; + } -namespace leetcode_12 { -string leetcode_12::intToRoman_2(int num) { - if (num > 1000) { - return "M" + intToRoman(num - 1000); - } else if (num > 100) { - static const array hundres = { - "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "M"}; - return hundres[num / 100] + intToRoman(num % 100); - } else if (num > 10) { - static const array tens = { - "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "C"}; - return tens[num / 10] + intToRoman(num % 10); - } else if (num <= 10) { - static const array ones = { - "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"}; - return ones[num]; + string intToRoman(int num) { + static const array hundres = + {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "M"}; + static const array tens = + {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "C"}; + static const array ones = + {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"}; + string will_return = string((num / 1000), 'M'); + will_return.reserve(sizeof(char) * 16); + num = num % 1000; + will_return += hundres[num / 100]; + num = num % 100; + will_return += tens[num / 10]; + num = num % 10; + will_return += ones[num]; + return will_return; } - return "should reach there"; -} +}; -string leetcode_12::intToRoman(int num) { - static const array hundres = - {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "M"}; - static const array tens = - {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "C"}; - static const array ones = - {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"}; - string will_return = string((num / 1000), 'M'); - will_return.reserve(sizeof(char) * 16); - num = num % 1000; - will_return += hundres[num / 100]; - num = num % 100; - will_return += tens[num / 10]; - num = num % 10; - will_return += ones[num]; - return will_return; -} +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_12_test.hpp b/algorithm/string/leetcode_12_test.cpp similarity index 53% rename from algorithm/string/leetcode_12_test.hpp rename to algorithm/string/leetcode_12_test.cpp index bb5d5962..e81154a3 100644 --- a/algorithm/string/leetcode_12_test.hpp +++ b/algorithm/string/leetcode_12_test.cpp @@ -1,16 +1,12 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag string //@Tag 字符串 //@Tag 模拟 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_12_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_12_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_12_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_12_TEST_HPP +#include "leetcode_12.cpp" #include #include #include @@ -22,56 +18,56 @@ using std::array; using std::string; using std::vector; -struct leetcode_12 { - static string intToRoman(int num); - - static string intToRoman_2(int num); -}; - using Catch::Matchers::Equals; TEST_CASE("test case 1 [test_12]", "[test_12]") { + Solution solution; static constexpr const auto input{3}; static constexpr const char *const result{"III"}; - CHECK_THAT(result, Equals(leetcode_12::intToRoman(input))); - CHECK_THAT(result, Equals(leetcode_12::intToRoman_2(input))); + CHECK_THAT(result, Equals(solution.intToRoman(input))); + CHECK_THAT(result, Equals(solution.intToRoman_2(input))); } TEST_CASE("test case 2 [test_12]", "[test_12]") { + Solution solution; static constexpr const auto input{4}; static constexpr const char *const result{"IV"}; - CHECK_THAT(result, Equals(leetcode_12::intToRoman(input))); - CHECK_THAT(result, Equals(leetcode_12::intToRoman_2(input))); + CHECK_THAT(result, Equals(solution.intToRoman(input))); + CHECK_THAT(result, Equals(solution.intToRoman_2(input))); } TEST_CASE("test case 3 [test_12]", "[test_12]") { + Solution solution; static constexpr const auto input{9}; static constexpr const char *const result{"IX"}; - CHECK_THAT(result, Equals(leetcode_12::intToRoman(input))); - CHECK_THAT(result, Equals(leetcode_12::intToRoman_2(input))); + CHECK_THAT(result, Equals(solution.intToRoman(input))); + CHECK_THAT(result, Equals(solution.intToRoman_2(input))); } TEST_CASE("test case 4 [test_12]", "[test_12]") { + Solution solution; static constexpr const auto input{58}; static constexpr const char *const result{"LVIII"}; - CHECK_THAT(result, Equals(leetcode_12::intToRoman(input))); - CHECK_THAT(result, Equals(leetcode_12::intToRoman_2(input))); + CHECK_THAT(result, Equals(solution.intToRoman(input))); + CHECK_THAT(result, Equals(solution.intToRoman_2(input))); } TEST_CASE("test case 5 [test_12]", "[test_12]") { + Solution solution; static constexpr const auto input{1994}; static constexpr const char *const result{"MCMXCIV"}; - CHECK_THAT(result, Equals(leetcode_12::intToRoman(input))); - CHECK_THAT(result, Equals(leetcode_12::intToRoman_2(input))); + CHECK_THAT(result, Equals(solution.intToRoman(input))); + CHECK_THAT(result, Equals(solution.intToRoman_2(input))); } TEST_CASE("test case 6 [test_12]", "[test_12]") { + Solution solution; static constexpr const auto input{114514}; static constexpr const char *const result{ "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMDXIV"}; - CHECK_THAT(result, Equals(leetcode_12::intToRoman(input))); - CHECK_THAT(result, Equals(leetcode_12::intToRoman_2(input))); + CHECK_THAT(result, Equals(solution.intToRoman(input))); + CHECK_THAT(result, Equals(solution.intToRoman_2(input))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_12_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_12_TEST_HPP diff --git a/algorithm/string/leetcode_13.cpp b/algorithm/string/leetcode_13.cpp index fc9b041d..7d03cc7b 100644 --- a/algorithm/string/leetcode_13.cpp +++ b/algorithm/string/leetcode_13.cpp @@ -1,41 +1,49 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_13_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include #include #include - +#include +#include +#include +#include namespace leetcode_13 { +using std::string; using std::array; +using std::vector; +#endif -int32_t leetcode_13::romanToInt(const string &s) { - constexpr const static array, 3> vas{ - {{"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, - {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, - {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}} - }; - int32_t will_return{0}; - size_t begin{0}; - int32_t added{1000}; - while (s[begin] == 'M') { - will_return += added; - begin++; - } - for (const auto &i: vas) { - added /= 10; - for (auto j{i.crbegin()}; j != i.crend(); j++) { - const auto jsize{strlen(*j)}; - if (!s.compare(begin, jsize, *j, 0, jsize)) { - will_return += std::distance(j, i.crend() - 1 + 1) * added; - begin += jsize; - break; +class Solution { +public: + int32_t romanToInt(const string &s) { + constexpr const static array, 3> vas{ + {{"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, + {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, + {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}} + }; + int32_t will_return{0}; + size_t begin{0}; + int32_t added{1000}; + while (s[begin] == 'M') { + will_return += added; + begin++; + } + for (const auto &i: vas) { + added /= 10; + for (auto j{i.crbegin()}; j != i.crend(); j++) { + const auto jsize{strlen(*j)}; + if (!s.compare(begin, jsize, *j, 0, jsize)) { + will_return += std::distance(j, i.crend() - 1 + 1) * added; + begin += jsize; + break; + } } } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_1324.cpp b/algorithm/string/leetcode_1324.cpp index a6a0d9bc..8992e9fb 100644 --- a/algorithm/string/leetcode_1324.cpp +++ b/algorithm/string/leetcode_1324.cpp @@ -1,57 +1,64 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_1324_test.hpp" -#include - +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include +#include +#include namespace leetcode_1324 { -//整体复杂度O(N) -vector leetcode_1324::printVertically(const string &S) { - vector> views{}; - // step1, get the start of each elements - // 使用raw pointer 避免内存分配 - int32_t max_length{0}; - for (auto iter{S.cbegin()}, last{S.cend()}; iter != last;) { - const char *const pointer = iter.base(); - int32_t length{0}; - for (; iter != last && *iter != ' '; ++iter) { - ++length; - } - max_length = std::max(max_length, length); - views.emplace_back(pointer, length); - if (iter != last) { - ++iter; - } - } - // step2, step for each pointer to get char - const auto views_length{views.size()}; - vector will_return{}; - will_return.reserve(max_length); // 预分配内存 - for (int32_t iter{0}; iter < max_length; ++iter) { - auto back_iter = views_length; - for (; back_iter != 0; --back_iter) { - const auto [str, length] = views[back_iter - 1]; - if (length != 0) { - break; +using std::vector; +using std::string; +#endif + +class Solution { +public: + vector printVertically(const string &S) { + vector> views{}; + // step1, get the start of each elements + // 使用raw pointer 避免内存分配 + int32_t max_length{0}; + for (auto iter{S.cbegin()}, last{S.cend()}; iter != last;) { + const char *const pointer = iter.base(); + int32_t length{0}; + for (; iter != last && *iter != ' '; ++iter) { + ++length; } - }// 采用反向迭代,高效去除后缀空字符 - std::string str(back_iter, ' '); // 预分配内存 - for (; back_iter != 0; --back_iter) { // 反向迭代, 使用length辅助判断 - const auto [element, length] = views[back_iter - 1]; - if (length > 0) { - str[back_iter - 1] = *element; - views[back_iter - 1] = std::make_tuple(element + 1, length - 1); - } else { - str[back_iter - 1] = ' '; + max_length = std::max(max_length, length); + views.emplace_back(pointer, length); + if (iter != last) { + ++iter; } } - will_return.push_back(str); + // step2, step for each pointer to get char + const auto views_length{views.size()}; + vector will_return{}; + will_return.reserve(max_length); // 预分配内存 + for (int32_t iter{0}; iter < max_length; ++iter) { + auto back_iter = views_length; + for (; back_iter != 0; --back_iter) { + const auto [str, length] = views[back_iter - 1]; + if (length != 0) { + break; + } + }// 采用反向迭代,高效去除后缀空字符 + std::string str(back_iter, ' '); // 预分配内存 + for (; back_iter != 0; --back_iter) { // 反向迭代, 使用length辅助判断 + const auto [element, length] = views[back_iter - 1]; + if (length > 0) { + str[back_iter - 1] = *element; + views[back_iter - 1] = std::make_tuple(element + 1, length - 1); + } else { + str[back_iter - 1] = ' '; + } + } + will_return.push_back(str); + } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_1324_test.hpp b/algorithm/string/leetcode_1324_test.cpp similarity index 67% rename from algorithm/string/leetcode_1324_test.hpp rename to algorithm/string/leetcode_1324_test.cpp index 65fe20e5..2c50a6f2 100644 --- a/algorithm/string/leetcode_1324_test.hpp +++ b/algorithm/string/leetcode_1324_test.cpp @@ -1,31 +1,25 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag string //@Tag 字符串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1324_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1324_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1324_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1324_TEST_CPP #include +#include "leetcode_1324.cpp" #include #include #include +#include +#include namespace leetcode_1324 { -using std::string; - -namespace leetcode_1324 { -vector printVertically(const string &S); -} using Catch::Matchers::Equals; TEST_CASE("1 [test_1324]", "[test_1324]") { + Solution solution; constexpr const char *const input{"HOW ARE YOU INDIAN MI FANS"}; constexpr const std::array arr{"HAYIMF", "ORONIA", @@ -34,15 +28,16 @@ TEST_CASE("1 [test_1324]", "[test_1324]") { " A", " N"}; const vector output{arr.cbegin(), arr.cend()}; - CHECK_THAT(output, Equals(leetcode_1324::printVertically(input))); + CHECK_THAT(output, Equals(solution.printVertically(input))); } TEST_CASE("2 [test_1324]", "[test_1324]") { + Solution solution; constexpr const char *const input{"3z4"}; constexpr const std::array arr{"3", "z", "4"}; const vector output{arr.cbegin(), arr.cend()}; - CHECK_THAT(output, Equals(leetcode_1324::printVertically(input))); + CHECK_THAT(output, Equals(solution.printVertically(input))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1324_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1324_TEST_CPP diff --git a/algorithm/string/leetcode_1328.cpp b/algorithm/string/leetcode_1328.cpp index 9e8ac645..f6b6b30a 100644 --- a/algorithm/string/leetcode_1328.cpp +++ b/algorithm/string/leetcode_1328.cpp @@ -1,48 +1,53 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_1328_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1328 { +using std::string; +#endif -string leetcode_1328::breakPalindrome(const string &palindrome) { - if (palindrome.size() == 1) { - return ""; - } - string will_return{palindrome}; - const auto length{palindrome.size()}; - const auto mid{length / 2}; - const auto addition = (length % 2 == 0 ? 0 : 1); - for (size_t iter{0}; iter < mid; ++iter) { - if (will_return[iter] > 'a') { - will_return[iter] = 'a'; - return will_return; +class Solution { +public: + string breakPalindrome(const string &palindrome) { + if (palindrome.size() == 1) { + return ""; } - } - for (size_t iter{mid + addition}; iter < length; ++iter) { - if (will_return[iter] > 'a') { - will_return[iter] = 'a'; - return will_return; + string will_return{palindrome}; + const auto length{palindrome.size()}; + const auto mid{length / 2}; + const auto addition = (length % 2 == 0 ? 0 : 1); + for (size_t iter{0}; iter < mid; ++iter) { + if (will_return[iter] > 'a') { + will_return[iter] = 'a'; + return will_return; + } } - } - for (size_t iter{length}; iter > mid + addition; --iter) { - if (will_return[iter - 1] == 'a') { - will_return[iter - 1] = 'b'; - return will_return; + for (size_t iter{mid + addition}; iter < length; ++iter) { + if (will_return[iter] > 'a') { + will_return[iter] = 'a'; + return will_return; + } } - } - for (size_t iter{mid}; iter > 0; --iter) { - if (will_return[iter - 1] == 'a') { - will_return[iter - 1] = 'b'; - return will_return; + for (size_t iter{length}; iter > mid + addition; --iter) { + if (will_return[iter - 1] == 'a') { + will_return[iter - 1] = 'b'; + return will_return; + } + } + for (size_t iter{mid}; iter > 0; --iter) { + if (will_return[iter - 1] == 'a') { + will_return[iter - 1] = 'b'; + return will_return; + } } + // will_return[length - 1]='b'; + // return will_return; + return ""; } - // will_return[length - 1]='b'; - // return will_return; - return ""; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_1328_test.hpp b/algorithm/string/leetcode_1328_test.cpp similarity index 58% rename from algorithm/string/leetcode_1328_test.hpp rename to algorithm/string/leetcode_1328_test.cpp index 7bd844db..2721e6dd 100644 --- a/algorithm/string/leetcode_1328_test.hpp +++ b/algorithm/string/leetcode_1328_test.cpp @@ -1,55 +1,50 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag string //@Tag 字符串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1328_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1328_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1328_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1328_TEST_HPP #include +#include "leetcode_1328.cpp" #include #include #include namespace leetcode_1328 { -using std::string; - -namespace leetcode_1328 { -string breakPalindrome(const string &palindrome); -} TEST_CASE("1 [test_1328]", "[test_1328]") { + Solution solution; constexpr const char *const input{"abccba"}; constexpr const char *const result{"aaccba"}; - const auto output = leetcode_1328::breakPalindrome(input); + const auto output = solution.breakPalindrome(input); CHECK(result == output); } TEST_CASE("2 [test_1328]", "[test_1328]") { + Solution solution; constexpr const char *const input{"aa"}; constexpr const char *const result{"ab"}; - const auto output = leetcode_1328::breakPalindrome(input); + const auto output = solution.breakPalindrome(input); CHECK(result == output); } TEST_CASE("3 [test_1328]", "[test_1328]") { + Solution solution; constexpr const char *const input{"aba"}; constexpr const char *const result{"abb"}; - const auto output = leetcode_1328::breakPalindrome(input); + const auto output = solution.breakPalindrome(input); CHECK(result == output); } TEST_CASE("4 [test_1328]", "[test_1328]") { + Solution solution; constexpr const char *const input{"aabaa"}; constexpr const char *const result{"aabab"}; - const auto output = leetcode_1328::breakPalindrome(input); + const auto output = solution.breakPalindrome(input); CHECK(result == output); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1328_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1328_TEST_HPP diff --git a/algorithm/string/leetcode_1358.cpp b/algorithm/string/leetcode_1358.cpp index 3bbd677f..1312e311 100644 --- a/algorithm/string/leetcode_1358.cpp +++ b/algorithm/string/leetcode_1358.cpp @@ -1,33 +1,38 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_1358_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1358 { +using std::string; +#endif -int32_t leetcode_1358::numberOfSubstrings(const string &s) { - int32_t count{0}; - const auto s_size{s.size()}; - for (size_t left{0}, right{0}, a{0}, b{0}, c{0}; right < s_size;) { - const auto ch1 = s[right]; - if (ch1 == 'a') { a += 1; } - if (ch1 == 'b') { b += 1; } - if (ch1 == 'c') { c += 1; } - right += 1; - while (a >= 1 && b >= 1 && c >= 1) { - count += s_size - right + 1; - const auto ch2 = s[left]; - if (ch2 == 'a') { a -= 1; } - if (ch2 == 'b') { b -= 1; } - if (ch2 == 'c') { c -= 1; } - left += 1; +class Solution { +public: + int32_t numberOfSubstrings(const string &s) { + int32_t count{0}; + const auto s_size{s.size()}; + for (size_t left{0}, right{0}, a{0}, b{0}, c{0}; right < s_size;) { + const auto ch1 = s[right]; + if (ch1 == 'a') { a += 1; } + if (ch1 == 'b') { b += 1; } + if (ch1 == 'c') { c += 1; } + right += 1; + while (a >= 1 && b >= 1 && c >= 1) { + count += s_size - right + 1; + const auto ch2 = s[left]; + if (ch2 == 'a') { a -= 1; } + if (ch2 == 'b') { b -= 1; } + if (ch2 == 'c') { c -= 1; } + left += 1; + } } + return count; } - return count; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_1358_test.hpp b/algorithm/string/leetcode_1358_test.cpp similarity index 51% rename from algorithm/string/leetcode_1358_test.hpp rename to algorithm/string/leetcode_1358_test.cpp index 696229e0..6975454a 100644 --- a/algorithm/string/leetcode_1358_test.hpp +++ b/algorithm/string/leetcode_1358_test.cpp @@ -1,45 +1,39 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag string //@Tag 字符串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1358_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1358_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1358_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1358_TEST_HPP #include +#include "leetcode_1358.cpp" #include #include #include namespace leetcode_1358 { -using std::string; - -namespace leetcode_1358 { -int32_t numberOfSubstrings(const string &s); -} TEST_CASE("1 [test_1358]", "[test_1358]") { + Solution solution; constexpr const char *const input{"abcabc"}; constexpr const auto result{10}; - CHECK(result == leetcode_1358::numberOfSubstrings(input)); + CHECK(result == solution.numberOfSubstrings(input)); } TEST_CASE("2 [test_1358]", "[test_1358]") { + Solution solution; constexpr const char *const input{"aaacb"}; constexpr const auto result{3}; - CHECK(result == leetcode_1358::numberOfSubstrings(input)); + CHECK(result == solution.numberOfSubstrings(input)); } TEST_CASE("3 [test_1358]", "[test_1358]") { + Solution solution; constexpr const char *const input{"abc"}; constexpr const auto result{1}; - CHECK(result == leetcode_1358::numberOfSubstrings(input)); + CHECK(result == solution.numberOfSubstrings(input)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1358_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1358_TEST_HPP diff --git a/algorithm/string/leetcode_1366.cpp b/algorithm/string/leetcode_1366.cpp index ec93c315..8f26bd38 100644 --- a/algorithm/string/leetcode_1366.cpp +++ b/algorithm/string/leetcode_1366.cpp @@ -1,54 +1,62 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ -#include "leetcode_1366_test.hpp" +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +#include +#include +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1366 { +using std::string; +using std::vector; +#endif -string leetcode_1366::rankTeams(const vector &votes) { - if (votes.empty() || votes.front().empty()) { - return {}; - } - struct sorted { - std::vector vec_votes{}; - char ch{'A'}; - int16_t count{0}; - }; - const auto votes_size{votes.size()}; - const auto vote_of_each{votes.front().size()}; - constexpr const auto groups{26}; - vector voted_array(groups); - for (size_t i{0}; i < groups; ++i) { - voted_array[i].ch += i; - voted_array[i].vec_votes.resize(vote_of_each); - } - for (size_t i{0}; i < vote_of_each; ++i) { - for (size_t j{0}; j < votes_size; ++j) { - const auto ch{votes[j][i] - 'A'}; - voted_array[ch].vec_votes[i] += 1; - voted_array[ch].count += 1; +class Solution { +public: + string rankTeams(const vector &votes) { + if (votes.empty() || votes.front().empty()) { + return {}; + } + struct sorted { + std::vector vec_votes{}; + char ch{'A'}; + int16_t count{0}; + }; + const auto votes_size{votes.size()}; + const auto vote_of_each{votes.front().size()}; + constexpr const auto groups{26}; + vector voted_array(groups); + for (size_t i{0}; i < groups; ++i) { + voted_array[i].ch += i; + voted_array[i].vec_votes.resize(vote_of_each); } - } - // or can filter count = 0 in there - std::sort(voted_array.begin(), voted_array.end(), [vote_of_each](auto obj1, auto obj2) { for (size_t i{0}; i < vote_of_each; ++i) { - if (obj1.vec_votes[i] != obj2.vec_votes[i]) { - return obj1.vec_votes[i] > obj2.vec_votes[i]; + for (size_t j{0}; j < votes_size; ++j) { + const auto ch{votes[j][i] - 'A'}; + voted_array[ch].vec_votes[i] += 1; + voted_array[ch].count += 1; } } - return obj1.ch < obj2.ch; - }); - string will_return{}; - for (const auto &voted: voted_array) { - if (voted.count != 0) { - will_return += voted.ch; + // or can filter count = 0 in there + std::sort(voted_array.begin(), voted_array.end(), [vote_of_each](auto obj1, auto obj2) { + for (size_t i{0}; i < vote_of_each; ++i) { + if (obj1.vec_votes[i] != obj2.vec_votes[i]) { + return obj1.vec_votes[i] > obj2.vec_votes[i]; + } + } + return obj1.ch < obj2.ch; + }); + string will_return{}; + for (const auto &voted: voted_array) { + if (voted.count != 0) { + will_return += voted.ch; + } } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_1366_test.cpp b/algorithm/string/leetcode_1366_test.cpp new file mode 100644 index 00000000..6a0821c4 --- /dev/null +++ b/algorithm/string/leetcode_1366_test.cpp @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +//@Tag string +//@Tag 字符串 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1366_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1366_TEST_HPP + +#include +#include "leetcode_1366.cpp" +#include +#include +#include +#include + +namespace leetcode_1366 { + +TEST_CASE("1 [test_1366]", "[test_1366]") { + Solution solution; + const vector input{"ABC", "ACB", "ABC", "ACB", "ACB"}; + const char *const result{"ACB"}; + CHECK(result == solution.rankTeams(input)); +} + +TEST_CASE("2 [test_1366]", "[test_1366]") { + Solution solution; + const vector input{"WXYZ", "XYZW"}; + const char *const result{"XWYZ"}; + CHECK(result == solution.rankTeams(input)); +} + + +TEST_CASE("3 [test_1366]", "[test_1366]") { + Solution solution; + const vector input{"ZMNAGUEDSJYLBOPHRQICWFXTVK"}; + const char *const result{"ZMNAGUEDSJYLBOPHRQICWFXTVK"}; + CHECK(result == solution.rankTeams(input)); +} + + +TEST_CASE("4 [test_1366]", "[test_1366]") { + Solution solution; + const vector input{"BCA", "CAB", "CBA", "ABC", "ACB", "BAC"}; + const char *const result{"ABC"}; + CHECK(result == solution.rankTeams(input)); +} + + +TEST_CASE("5 [test_1366]", "[test_1366]") { + Solution solution; + const vector input{"M", "M", "M", "M"}; + const char *const result{"M"}; + CHECK(result == solution.rankTeams(input)); +} + +TEST_CASE("6 [test_1366]", "[test_1366]") { + Solution solution; + const vector input{"FVSHJIEMNGYPTQOURLWCZKAX", + "AITFQORCEHPVJMXGKSLNZWUY", + "OTERVXFZUMHNIYSCQAWGPKJL", + "VMSERIJYLZNWCPQTOKFUHAXG", + "VNHOZWKQCEFYPSGLAMXJIUTR", + "ANPHQIJMXCWOSKTYGULFVERZ", + "RFYUXJEWCKQOMGATHZVILNSP", + "SCPYUMQJTVEXKRNLIOWGHAFZ", + "VIKTSJCEYQGLOMPZWAHFXURN", + "SVJICLXKHQZTFWNPYRGMEUAO", + "JRCTHYKIGSXPOZLUQAVNEWFM", + "NGMSWJITREHFZVQCUKXYAPOL", + "WUXJOQKGNSYLHEZAFIPMRCVT", + "PKYQIOLXFCRGHZNAMJVUTWES", + "FERSGNMJVZXWAYLIKCPUQHTO", + "HPLRIUQMTSGYJVAXWNOCZEKF", + "JUVWPTEGCOFYSKXNRMHQALIZ", + "MWPIAZCNSLEYRTHFKQXUOVGJ", + "EZXLUNFVCMORSIWKTYHJAQPG", + "HRQNLTKJFIEGMCSXAZPYOVUW", + "LOHXVYGWRIJMCPSQENUAKTZF", + "XKUTWPRGHOAQFLVYMJSNEIZC", + "WTCRQMVKPHOSLGAXZUEFYNJI"}; + const char *const result{"VWFHSJARNPEMOXLTUKICZGYQ"}; + CHECK(result == solution.rankTeams(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1366_TEST_HPP diff --git a/algorithm/string/leetcode_1366_test.hpp b/algorithm/string/leetcode_1366_test.hpp deleted file mode 100644 index a7d91d62..00000000 --- a/algorithm/string/leetcode_1366_test.hpp +++ /dev/null @@ -1,92 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1366_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1366_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_1366 { -using std::string; - -namespace leetcode_1366 { -string rankTeams(const vector &votes); - -} - -TEST_CASE("1 [test_1366]", "[test_1366]") { - const vector input{"ABC", "ACB", "ABC", "ACB", "ACB"}; - const char *const result{"ACB"}; - CHECK(result == leetcode_1366::rankTeams(input)); -} - -TEST_CASE("2 [test_1366]", "[test_1366]") { - const vector input{"WXYZ", "XYZW"}; - const char *const result{"XWYZ"}; - CHECK(result == leetcode_1366::rankTeams(input)); -} - - -TEST_CASE("3 [test_1366]", "[test_1366]") { - const vector input{"ZMNAGUEDSJYLBOPHRQICWFXTVK"}; - const char *const result{"ZMNAGUEDSJYLBOPHRQICWFXTVK"}; - CHECK(result == leetcode_1366::rankTeams(input)); -} - - -TEST_CASE("4 [test_1366]", "[test_1366]") { - const vector input{"BCA", "CAB", "CBA", "ABC", "ACB", "BAC"}; - const char *const result{"ABC"}; - CHECK(result == leetcode_1366::rankTeams(input)); -} - - -TEST_CASE("5 [test_1366]", "[test_1366]") { - const vector input{"M", "M", "M", "M"}; - const char *const result{"M"}; - CHECK(result == leetcode_1366::rankTeams(input)); -} - -TEST_CASE("6 [test_1366]", "[test_1366]") { - const vector input{ "FVSHJIEMNGYPTQOURLWCZKAX", - "AITFQORCEHPVJMXGKSLNZWUY", - "OTERVXFZUMHNIYSCQAWGPKJL", - "VMSERIJYLZNWCPQTOKFUHAXG", - "VNHOZWKQCEFYPSGLAMXJIUTR", - "ANPHQIJMXCWOSKTYGULFVERZ", - "RFYUXJEWCKQOMGATHZVILNSP", - "SCPYUMQJTVEXKRNLIOWGHAFZ", - "VIKTSJCEYQGLOMPZWAHFXURN", - "SVJICLXKHQZTFWNPYRGMEUAO", - "JRCTHYKIGSXPOZLUQAVNEWFM", - "NGMSWJITREHFZVQCUKXYAPOL", - "WUXJOQKGNSYLHEZAFIPMRCVT", - "PKYQIOLXFCRGHZNAMJVUTWES", - "FERSGNMJVZXWAYLIKCPUQHTO", - "HPLRIUQMTSGYJVAXWNOCZEKF", - "JUVWPTEGCOFYSKXNRMHQALIZ", - "MWPIAZCNSLEYRTHFKQXUOVGJ", - "EZXLUNFVCMORSIWKTYHJAQPG", - "HRQNLTKJFIEGMCSXAZPYOVUW", - "LOHXVYGWRIJMCPSQENUAKTZF", - "XKUTWPRGHOAQFLVYMJSNEIZC", - "WTCRQMVKPHOSLGAXZUEFYNJI"}; - const char *const result{"VWFHSJARNPEMOXLTUKICZGYQ"}; - CHECK(result == leetcode_1366::rankTeams(input)); -} - - - - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1366_TEST_HPP diff --git a/algorithm/string/leetcode_1370.cpp b/algorithm/string/leetcode_1370.cpp index 22005648..2ecc189a 100644 --- a/algorithm/string/leetcode_1370.cpp +++ b/algorithm/string/leetcode_1370.cpp @@ -1,41 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ -#include "leetcode_1370_test.hpp" +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +#include +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1370 { +using std::string; +#endif -string leetcode_1370::sortString(const string &s) { - constexpr const auto chnum{'Z' - 'A' + 1}; - std::array count{0,}; - const auto length{s.size()}; - for (const auto ch: s) { - count[ch - 'a'] += 1; - } - string will_return{}; - will_return.reserve(length); - for (size_t remains{length}; remains > 0;) { - for (size_t i{0}; i < chnum; ++i) { - if (count[i] != 0) { - will_return.push_back(static_cast(i + 'a')); - count[i] -= 1; - remains -= 1; - } +class Solution { +public: + string sortString(const string &s) { + constexpr const auto chnum{'Z' - 'A' + 1}; + std::array count{0,}; + const auto length{s.size()}; + for (const auto ch: s) { + count[ch - 'a'] += 1; } - for (size_t i{0}; i < chnum; ++i) { - const auto i2 = chnum - 1 - i; - if (count[i2] != 0) { - will_return.push_back(static_cast(i2 + 'a')); - count[i2] -= 1; - remains -= 1; + string will_return{}; + will_return.reserve(length); + for (size_t remains{length}; remains > 0;) { + for (size_t i{0}; i < chnum; ++i) { + if (count[i] != 0) { + will_return.push_back(static_cast(i + 'a')); + count[i] -= 1; + remains -= 1; + } + } + for (size_t i{0}; i < chnum; ++i) { + const auto i2 = chnum - 1 - i; + if (count[i2] != 0) { + will_return.push_back(static_cast(i2 + 'a')); + count[i2] -= 1; + remains -= 1; + } } } + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_1370_test.hpp b/algorithm/string/leetcode_1370_test.cpp similarity index 53% rename from algorithm/string/leetcode_1370_test.hpp rename to algorithm/string/leetcode_1370_test.cpp index e58d67bf..342ad3d4 100644 --- a/algorithm/string/leetcode_1370_test.hpp +++ b/algorithm/string/leetcode_1370_test.cpp @@ -1,40 +1,31 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2023-2025 nanoseeds //@Tag string //@Tag 字符串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1370_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1370_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1370_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1370_TEST_HPP #include +#include "leetcode_1370.cpp" #include #include #include namespace leetcode_1370 { -using std::string; - -namespace leetcode_1370 { -string sortString(const string &s); -} TEST_CASE("1 [test_1370]", "[test_1370]") { + Solution solution; constexpr const char *const input{"aaaabbbbcccc"}; constexpr const char *const result{"abccbaabccba"}; - CHECK(result == leetcode_1370::sortString(input)); + CHECK(result == solution.sortString(input)); } TEST_CASE("2 [test_1370]", "[test_1370]") { + Solution solution; constexpr const char *const input{"youknowtherulesandsodoi"}; constexpr const char *const result{"adehiklnorstuwyusonedoo"}; - CHECK(result == leetcode_1370::sortString(input)); + CHECK(result == solution.sortString(input)); } - - } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1370_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1370_TEST_HPP diff --git a/algorithm/string/leetcode_1392.cpp b/algorithm/string/leetcode_1392.cpp index 1d56b27b..f57cbc8a 100644 --- a/algorithm/string/leetcode_1392.cpp +++ b/algorithm/string/leetcode_1392.cpp @@ -1,54 +1,56 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ -#include "leetcode_1392_test.hpp" +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +#include +#include #include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1392 { -namespace leetcode_1392 { - -namespace naive { - -string longestPrefix(const string &s) { - int32_t count{0}; - for (int32_t i{0}; i < s.size() - 1; i++) { - if (0 == std::memcmp(&s[0], &s[s.size() - 1 - i], (i + 1))) { - count = i + 1; +#endif + +using std::string; +using std::vector; + +class Solution { +private: + string longestPrefix_naive(const string &s) { + int32_t count{0}; + for (int32_t i{0}; i < s.size() - 1; i++) { + if (0 == std::memcmp(&s[0], &s[s.size() - 1 - i], (i + 1))) { + count = i + 1; + } } + return s.substr(0, count); } - return s.substr(0, count); -} -} -namespace hash { -string longestPrefix(const string &s) { - size_t count{0}; - constexpr const auto prime{1000'000'007},prime2{1000'000'009}; - size_t hashPrefix{0}, hashPostfix{0}, hashMultiply{1}; - size_t hashPrefix2{0}, hashPostfix2{0}, hashMultiply2{1}; - for (size_t i{0}; i < s.size() - 1; i++) { - hashPrefix = (hashPrefix * 26 + s[i]) % prime; - hashPrefix2 = (hashPrefix2 * 26 + s[i]) % prime2; - hashPostfix = (hashPostfix + (s[s.size() - 1 - i]) * hashMultiply) % prime; - hashPostfix2 = (hashPostfix2 + (s[s.size() - 1 - i]) * hashMultiply2) % prime2; - hashMultiply = (hashMultiply * 26) % prime; - hashMultiply2 = (hashMultiply2 * 26) % prime2; - if (hashPrefix == hashPostfix && hashPrefix2 == hashPostfix2) { // 双哈希 - count = i + 1; + string longestPrefix_hash(const string &s) { + size_t count{0}; + constexpr const auto prime{1000'000'007}, prime2{1000'000'009}; + size_t hashPrefix{0}, hashPostfix{0}, hashMultiply{1}; + size_t hashPrefix2{0}, hashPostfix2{0}, hashMultiply2{1}; + for (size_t i{0}; i < s.size() - 1; i++) { + hashPrefix = (hashPrefix * 26 + s[i]) % prime; + hashPrefix2 = (hashPrefix2 * 26 + s[i]) % prime2; + hashPostfix = (hashPostfix + (s[s.size() - 1 - i]) * hashMultiply) % prime; + hashPostfix2 = (hashPostfix2 + (s[s.size() - 1 - i]) * hashMultiply2) % prime2; + hashMultiply = (hashMultiply * 26) % prime; + hashMultiply2 = (hashMultiply2 * 26) % prime2; + if (hashPrefix == hashPostfix && hashPrefix2 == hashPostfix2) { // 双哈希 + count = i + 1; + } } + return s.substr(0, count); } - return s.substr(0, count); -} -} -string longestPrefix(const string &s) { - return hash::longestPrefix(s); -} +public: + string longestPrefix(const string &s) { + return longestPrefix_hash(s); + } +}; +#ifdef ALGORITHM_TEST_MACRO } -} +#endif diff --git a/algorithm/string/leetcode_1392_test.cpp b/algorithm/string/leetcode_1392_test.cpp new file mode 100644 index 00000000..ff98f90f --- /dev/null +++ b/algorithm/string/leetcode_1392_test.cpp @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +//@Tag string +//@Tag 字符串 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1392_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1392_TEST_HPP + +#include +#include "leetcode_1392.cpp" +#include +#include +#include + +namespace leetcode_1392 { + +TEST_CASE("1 [test_1392]", "[test_1392]") { + Solution solution; + constexpr const char *const input{"abababab"}; + constexpr const char *const result{"ababab"}; + CHECK(result == solution.longestPrefix(input)); +} + +TEST_CASE("2 [test_1392]", "[test_1392]") { + Solution solution; + constexpr const char *const input{"longestPrefix"}; + constexpr const char *const result{""}; + CHECK(result == solution.longestPrefix(input)); +} + +TEST_CASE("3 [test_1392]", "[test_1392]") { + Solution solution; + const string input(98001, 'a'); + const string result(98000, 'a'); + CHECK(result == solution.longestPrefix(input)); +} + +TEST_CASE("4 [test_1392]", "[test_1392]") { + Solution solution; + constexpr const char *const input{ + "vwantmbocxcwrqtvgzuvgrmdltfiglltaxkjfajxthcppcatddcunpkqsgpnjjgqanrwabgrtwuqbrfl"}; + constexpr const char *const result{""}; + CHECK(result == solution.longestPrefix(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1392_TEST_HPP diff --git a/algorithm/string/leetcode_1392_test.hpp b/algorithm/string/leetcode_1392_test.hpp deleted file mode 100644 index 1ab175cb..00000000 --- a/algorithm/string/leetcode_1392_test.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1392_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1392_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_1392 { -using std::string; - -namespace leetcode_1392 { -string longestPrefix(const string &s); -} - -TEST_CASE("1 [test_1392]", "[test_1392]") { - constexpr const char *const input{"abababab"}; - constexpr const char *const result{"ababab"}; - CHECK(result == leetcode_1392::longestPrefix(input)); -} - -TEST_CASE("2 [test_1392]", "[test_1392]") { - constexpr const char *const input{"longestPrefix"}; - constexpr const char *const result{""}; - CHECK(result == leetcode_1392::longestPrefix(input)); -} - -TEST_CASE("3 [test_1392]", "[test_1392]") { - const string input(98001, 'a'); - const string result(98000, 'a'); - CHECK(result == leetcode_1392::longestPrefix(input)); -} -TEST_CASE("4 [test_1392]", "[test_1392]") { - constexpr const char *const input{"vwantmbocxcwrqtvgzuvgrmdltfiglltaxkjfajxthcppcatddcunpkqsgpnjjgqanrwabgrtwuqbrfl"}; - constexpr const char *const result{""}; - CHECK(result == leetcode_1392::longestPrefix(input)); -} - - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1392_TEST_HPP diff --git a/algorithm/string/leetcode_13_test.cpp b/algorithm/string/leetcode_13_test.cpp new file mode 100644 index 00000000..ca364b8b --- /dev/null +++ b/algorithm/string/leetcode_13_test.cpp @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag string +//@Tag 字符串 +//@Tag 模拟 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_13_TEST_CPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_13_TEST_CPP + +#include +#include "leetcode_13.cpp" +#include +#include +#include +#include + +namespace leetcode_13 { + +TEST_CASE("test case 1 [test_13]", "[test_13]") { + Solution solution; + CHECK(solution.romanToInt("III") == 3); +} + +TEST_CASE("test case 2 [test_13]", "[test_13]") { + Solution solution; + CHECK(solution.romanToInt("IV") == 4); +} + +TEST_CASE("test case 3 [test_13]", "[test_13]") { + Solution solution; + CHECK(solution.romanToInt("IX") == 9); +} + +TEST_CASE("test case 4 [test_13]", "[test_13]") { + Solution solution; + CHECK(solution.romanToInt("LVIII") == 58); +} + +TEST_CASE("test case 5 [test_13]", "[test_13]") { + Solution solution; + CHECK(solution.romanToInt("MCMXCIV") == 1994); +} + +TEST_CASE("test case 6 [test_13]", "[test_13]") { + Solution solution; + CHECK(solution.romanToInt( + "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMDXIV") == + 114514); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_13_TEST_CPP diff --git a/algorithm/string/leetcode_13_test.hpp b/algorithm/string/leetcode_13_test.hpp deleted file mode 100644 index 40e93e9e..00000000 --- a/algorithm/string/leetcode_13_test.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -//@Tag 模拟 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_13_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_13_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_13 { - -using std::string; - -struct leetcode_13 { - static int32_t romanToInt(const string &str); -}; - -TEST_CASE("test case 1 [test_13]", "[test_13]") { - CHECK(leetcode_13::romanToInt("III") == 3); -} - -TEST_CASE("test case 2 [test_13]", "[test_13]") { - CHECK(leetcode_13::romanToInt("IV") == 4); -} - -TEST_CASE("test case 3 [test_13]", "[test_13]") { - CHECK(leetcode_13::romanToInt("IX") == 9); -} - -TEST_CASE("test case 4 [test_13]", "[test_13]") { - CHECK(leetcode_13::romanToInt("LVIII") == 58); -} - -TEST_CASE("test case 5 [test_13]", "[test_13]") { - CHECK(leetcode_13::romanToInt("MCMXCIV") == 1994); -} - -TEST_CASE("test case 6 [test_13]", "[test_13]") { - CHECK(leetcode_13::romanToInt( - "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMDXIV") == - 114514); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_13_TEST_HPP diff --git a/algorithm/string/leetcode_14.cpp b/algorithm/string/leetcode_14.cpp index f888c132..53ccf180 100644 --- a/algorithm/string/leetcode_14.cpp +++ b/algorithm/string/leetcode_14.cpp @@ -1,33 +1,40 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_14_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_14 { -string leetcode_14::longestCommonPrefix(const vector &strs) { - if (strs.empty()) { - return ""; - } - auto length = std::min_element(std::begin(strs), std::end(strs), - [](const string &s1, const string &s2) { - return s1.size() < s2.size(); - })->size(); - string will_return = ""; - will_return.reserve(10000); - for (size_t i = 0; i < length; i++) { - char judge = strs[0][i]; - for (const auto &item: strs) { - if (item[i] != judge) { - return will_return; +using std::string; +using std::vector; +#endif + +class Solution { +public: + string longestCommonPrefix(const vector &strs) { + if (strs.empty()) { + return ""; + } + auto length = std::min_element(std::begin(strs), std::end(strs), + [](const string &s1, const string &s2) { + return s1.size() < s2.size(); + })->size(); + string will_return = ""; + will_return.reserve(10000); + for (size_t i = 0; i < length; i++) { + char judge = strs[0][i]; + for (const auto &item: strs) { + if (item[i] != judge) { + return will_return; + } } + will_return += judge; } - will_return += judge; + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_1408.cpp b/algorithm/string/leetcode_1408.cpp index 638b4043..6ce597e9 100644 --- a/algorithm/string/leetcode_1408.cpp +++ b/algorithm/string/leetcode_1408.cpp @@ -1,86 +1,95 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ -#include "leetcode_1408_test.hpp" +// SPDX-FileCopyrightText: 2023-2025 nanoseeds +#include +#include +#include #include +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_1408 { +using std::string; +using std::vector; +#endif -vector leetcode_1408::stringMatching(const vector &words) { - vector strs{words}; - std::sort(strs.begin(), strs.end(), [](const string &s1, const string &s2) { return s1.length() < s2.length(); }); - union hashunion { - struct { - int32_t hash1{0}; - int32_t hash2{0}; - } twohash; - int64_t hashnum{}; - }; - std::unordered_set uset{}; - std::unordered_set will_return{}; - std::unordered_map tohash{}; - std::unordered_map fromhash{}; - constexpr const auto hash1{1000'000'007}, hash2{1000'000'009}; - for (const auto &str: strs) { - hashunion str_hash{}; - for (const auto ch: str) { - const int64_t one{str_hash.twohash.hash1}, two{str_hash.twohash.hash2}; - str_hash.twohash.hash1 = static_cast((one * 26 + (ch - 'a' + 1)) % hash1); - str_hash.twohash.hash2 = static_cast((two * 27 + (ch - 'a' + 1)) % hash2); - } - const auto &hashnum = str_hash.hashnum; - tohash[str] = hashnum; - fromhash[hashnum] = str; - if (uset.empty()) { - uset.insert(str.length()); - continue; - } - for (const auto &len: uset) { - if (len == str.length()) { - continue; - } - hashunion part_hash{}; - int64_t multi1{1}, multi2{1}; - for (size_t i{0}; i < len; i++) { - const int64_t one{part_hash.twohash.hash1}, two{part_hash.twohash.hash2}; - part_hash.twohash.hash1 = static_cast((one * 26 + (str[i] - 'a' + 1)) % hash1); - part_hash.twohash.hash2 = static_cast((two * 27 + (str[i] - 'a' + 1)) % hash2); - multi1 = (multi1 * 26) % hash1; - multi2 = (multi2 * 27) % hash2; +class Solution { +public: + vector stringMatching(const vector &words) { + vector strs{words}; + std::sort(strs.begin(), strs.end(), [](const string &s1, const string &s2) { return s1.length() < s2.length(); }); + union hashunion { + struct { + int32_t hash1{0}; + int32_t hash2{0}; + } twohash; + int64_t hashnum{}; + }; + std::unordered_set uset{}; + std::unordered_set will_return{}; + std::unordered_map tohash{}; + std::unordered_map fromhash{}; + constexpr const auto hash1{1000'000'007}, hash2{1000'000'009}; + for (const auto &str: strs) { + hashunion str_hash{}; + for (const auto ch: str) { + const int64_t one{str_hash.twohash.hash1}, two{str_hash.twohash.hash2}; + str_hash.twohash.hash1 = static_cast((one * 26 + (ch - 'a' + 1)) % hash1); + str_hash.twohash.hash2 = static_cast((two * 27 + (ch - 'a' + 1)) % hash2); } - if (fromhash.count(part_hash.hashnum) != 0) { - will_return.insert(fromhash[part_hash.hashnum]); + const auto &hashnum = str_hash.hashnum; + tohash[str] = hashnum; + fromhash[hashnum] = str; + if (uset.empty()) { + uset.insert(str.length()); + continue; } - for (size_t i{len}; i < str.length(); i++) { - const int64_t one{part_hash.twohash.hash1}, two{part_hash.twohash.hash2}; - part_hash.twohash.hash1 = - static_cast(((one * 26 + (str[i] - 'a' + 1)) % hash1 - - ((str[i - len] - 'a' + 1) * multi1) % hash1) % hash1); - if (part_hash.twohash.hash1 < 0) { - part_hash.twohash.hash1 += hash1; + for (const auto &len: uset) { + if (len == str.length()) { + continue; } - part_hash.twohash.hash2 = - static_cast(((two * 27 + (str[i] - 'a' + 1)) % hash2 - - ((str[i - len] - 'a' + 1) * multi2) % hash2) % hash2); - if (part_hash.twohash.hash2 < 0) { - part_hash.twohash.hash2 += hash2; + hashunion part_hash{}; + int64_t multi1{1}, multi2{1}; + for (size_t i{0}; i < len; i++) { + const int64_t one{part_hash.twohash.hash1}, two{part_hash.twohash.hash2}; + part_hash.twohash.hash1 = static_cast((one * 26 + (str[i] - 'a' + 1)) % hash1); + part_hash.twohash.hash2 = static_cast((two * 27 + (str[i] - 'a' + 1)) % hash2); + multi1 = (multi1 * 26) % hash1; + multi2 = (multi2 * 27) % hash2; } if (fromhash.count(part_hash.hashnum) != 0) { will_return.insert(fromhash[part_hash.hashnum]); - if (fromhash[part_hash.hashnum] == "auze") { - const auto x = 1; + } + for (size_t i{len}; i < str.length(); i++) { + const int64_t one{part_hash.twohash.hash1}, two{part_hash.twohash.hash2}; + part_hash.twohash.hash1 = + static_cast(((one * 26 + (str[i] - 'a' + 1)) % hash1 - + ((str[i - len] - 'a' + 1) * multi1) % hash1) % hash1); + if (part_hash.twohash.hash1 < 0) { + part_hash.twohash.hash1 += hash1; + } + part_hash.twohash.hash2 = + static_cast(((two * 27 + (str[i] - 'a' + 1)) % hash2 - + ((str[i - len] - 'a' + 1) * multi2) % hash2) % hash2); + if (part_hash.twohash.hash2 < 0) { + part_hash.twohash.hash2 += hash2; + } + if (fromhash.count(part_hash.hashnum) != 0) { + will_return.insert(fromhash[part_hash.hashnum]); + if (fromhash[part_hash.hashnum] == "auze") { + const auto x = 1; + } } } } + uset.insert(str.length()); } - uset.insert(str.length()); + return {will_return.begin(), will_return.end()}; } - return {will_return.begin(), will_return.end()}; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_1408_test.hpp b/algorithm/string/leetcode_1408_test.cpp similarity index 60% rename from algorithm/string/leetcode_1408_test.hpp rename to algorithm/string/leetcode_1408_test.cpp index df01d662..061f686a 100644 --- a/algorithm/string/leetcode_1408_test.hpp +++ b/algorithm/string/leetcode_1408_test.cpp @@ -1,70 +1,70 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2023-2025 nanoseeds //@Tag string //@Tag 字符串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1408_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1408_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1408_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1408_TEST_HPP #include +#include "leetcode_1408.cpp" #include #include #include +#include namespace leetcode_1408 { -using std::string; -namespace leetcode_1408 { -vector stringMatching(const vector &words); -} using Catch::Matchers::UnorderedEquals; TEST_CASE("0 [test_1408]", "[test_1408]") { + Solution solution; const vector inputs{"evl", "evlat", "kes", "lwkesz", "ckk", "eylwkesz", "efuw", "ickkw", "xnc", "evlon", "qsmd", "nmlwkeszk", "uyh", "xncme", "auze", "ixncmeqc"}; const vector output{"evl", "kes", "lwkesz", "ckk", "xnc", "xncme"}; - CHECK_THAT(output, UnorderedEquals(leetcode_1408::stringMatching(inputs))); + CHECK_THAT(output, UnorderedEquals(solution.stringMatching(inputs))); } TEST_CASE("1 [test_1408]", "[test_1408]") { + Solution solution; const vector inputs{"business", "bus", "assassin", "ass", "we", "can"}; const vector output{"bus", "ass"}; - CHECK_THAT(output, UnorderedEquals(leetcode_1408::stringMatching(inputs))); + CHECK_THAT(output, UnorderedEquals(solution.stringMatching(inputs))); } TEST_CASE("2 [test_1408]", "[test_1408]") { + Solution solution; const vector inputs{"tprefix", "prefix", "fix"}; const vector output{"prefix", "fix"}; - CHECK_THAT(output, UnorderedEquals(leetcode_1408::stringMatching(inputs))); + CHECK_THAT(output, UnorderedEquals(solution.stringMatching(inputs))); } TEST_CASE("3 [test_1408]", "[test_1408]") { + Solution solution; const vector inputs{"what", "the", "hell"}; const vector output{}; - CHECK_THAT(output, UnorderedEquals(leetcode_1408::stringMatching(inputs))); + CHECK_THAT(output, UnorderedEquals(solution.stringMatching(inputs))); } TEST_CASE("4 [test_1408]", "[test_1408]") { + Solution solution; const vector inputs{"mass", "as", "hero", "superhero"}; const vector output{"hero", "as"}; - CHECK_THAT(output, UnorderedEquals(leetcode_1408::stringMatching(inputs))); + CHECK_THAT(output, UnorderedEquals(solution.stringMatching(inputs))); } TEST_CASE("5 [test_1408]", "[test_1408]") { + Solution solution; const vector inputs{"leetcode", "et", "code"}; const vector output{"et", "code"}; - CHECK_THAT(output, UnorderedEquals(leetcode_1408::stringMatching(inputs))); + CHECK_THAT(output, UnorderedEquals(solution.stringMatching(inputs))); } TEST_CASE("6 [test_1408]", "[test_1408]") { + Solution solution; const vector inputs{"blue", "green", "bu"}; const vector output{}; - CHECK_THAT(output, UnorderedEquals(leetcode_1408::stringMatching(inputs))); + CHECK_THAT(output, UnorderedEquals(solution.stringMatching(inputs))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_1408_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_1408_TEST_HPP diff --git a/algorithm/string/leetcode_14_test.hpp b/algorithm/string/leetcode_14_test.cpp similarity index 51% rename from algorithm/string/leetcode_14_test.hpp rename to algorithm/string/leetcode_14_test.cpp index 539baec1..7bea6c36 100644 --- a/algorithm/string/leetcode_14_test.hpp +++ b/algorithm/string/leetcode_14_test.cpp @@ -1,47 +1,40 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag string //@Tag 字符串 //@Tag 模拟 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_14_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_14_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_14_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_14_TEST_HPP #include +#include "leetcode_14.cpp" #include #include #include #include namespace leetcode_14 { -using std::string; -using std::vector; - -struct leetcode_14 { - static string longestCommonPrefix(const vector &strs); -}; using Catch::Matchers::Equals; TEST_CASE("test case 1 [test_14]", "[test_14]") { + Solution solution; const vector strs{"flower", "flow", "flight"}; static constexpr const char *const result{"fl"}; - CHECK_THAT(result, Equals(leetcode_14::longestCommonPrefix(strs))); + CHECK_THAT(result, Equals(solution.longestCommonPrefix(strs))); } TEST_CASE("test case 2 [test_14]", "[test_14]") { + Solution solution; const vector strs{"dog", "racecar", "car"}; - CHECK(leetcode_14::longestCommonPrefix(strs).empty()); + CHECK(solution.longestCommonPrefix(strs).empty()); } TEST_CASE("test case 3 [test_14]", "[test_14]") { + Solution solution; const vector strs{}; - CHECK(leetcode_14::longestCommonPrefix(strs).empty()); + CHECK(solution.longestCommonPrefix(strs).empty()); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_14_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_14_TEST_HPP diff --git a/algorithm/string/leetcode_22.cpp b/algorithm/string/leetcode_22.cpp index 775e205a..30ffbb6a 100644 --- a/algorithm/string/leetcode_22.cpp +++ b/algorithm/string/leetcode_22.cpp @@ -1,30 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_22_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +#include #include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_22 { +using std::vector; +using std::string; using std::unordered_set; +#endif -vector leetcode_22::generateParenthesis(int n) { - if (n == 1) { - return vector{"()"}; - } - vector will_return{generateParenthesis(n - 1)}; - unordered_set uset{}; - for (const auto &i: will_return) { - for (int32_t j{0}; j < n; j++) { - uset.insert(string(i).insert(j, "()")); +class Solution { +public: + vector generateParenthesis(int n) { + if (n == 1) { + return vector{"()"}; } + vector will_return{generateParenthesis(n - 1)}; + unordered_set uset{}; + for (const auto &i: will_return) { + for (int32_t j{0}; j < n; j++) { + uset.insert(string(i).insert(j, "()")); + } + } + will_return.clear(); + will_return.reserve(uset.size()); + will_return.insert(will_return.end(), uset.begin(), uset.end()); + return will_return; } - will_return.clear(); - will_return.reserve(uset.size()); - will_return.insert(will_return.end(), uset.begin(), uset.end()); - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_22_test.cpp b/algorithm/string/leetcode_22_test.cpp new file mode 100644 index 00000000..3f63376c --- /dev/null +++ b/algorithm/string/leetcode_22_test.cpp @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag string +//@Tag 字符串 +//@Tag DP +//@Tag 回溯 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_22_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_22_TEST_HPP + +#include +#include "leetcode_22.cpp" +#include +#include +#include +#include + +namespace leetcode_22 { + +static const vector gene5{ + "((()))", + "(()())", + "(())()", + "()(())", + "()()()" +}; +using Catch::Matchers::UnorderedEquals; + +TEST_CASE("1 [test_22]", "[test_22]") { + Solution solution; + CHECK(solution.generateParenthesis(1).size() == 1); + CHECK(solution.generateParenthesis(2).size() == 2); + CHECK(solution.generateParenthesis(3).size() == 5); + CHECK(solution.generateParenthesis(4).size() == 14); + CHECK_THAT(solution.generateParenthesis(3), UnorderedEquals(gene5)); +} + +TEST_CASE("2 [test_22]", "[test_22]") { + Solution solution; + for (int32_t i{1}; i < 5; i++) { + CHECK_THAT(solution.generateParenthesis(i), UnorderedEquals(solution.generateParenthesis(i))); + } +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_22_TEST_HPP diff --git a/algorithm/string/leetcode_22_test.hpp b/algorithm/string/leetcode_22_test.hpp deleted file mode 100644 index bd359b2b..00000000 --- a/algorithm/string/leetcode_22_test.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -//@Tag DP -//@Tag 回溯 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_22_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_22_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_22 { - -using std::string; -using std::vector; - -struct leetcode_22 { - static vector generateParenthesis(int32_t n); -}; - -static const vector gene5{ - "((()))", - "(()())", - "(())()", - "()(())", - "()()()" -}; -using Catch::Matchers::UnorderedEquals; - -TEST_CASE("1 [test_22]", "[test_22]") { - CHECK(leetcode_22::generateParenthesis(1).size() == 1); - CHECK(leetcode_22::generateParenthesis(2).size() == 2); - CHECK(leetcode_22::generateParenthesis(3).size() == 5); - CHECK(leetcode_22::generateParenthesis(4).size() == 14); - CHECK_THAT(leetcode_22::generateParenthesis(3), UnorderedEquals(gene5)); -} - -TEST_CASE("2 [test_22]", "[test_22]") { - for (int32_t i{1}; i < 5; i++) { - CHECK_THAT(leetcode_22::generateParenthesis(i), UnorderedEquals(leetcode_22::generateParenthesis(i))); - } -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_22_TEST_HPP diff --git a/algorithm/string/leetcode_242.cpp b/algorithm/string/leetcode_242.cpp index ce777ebd..d0a53c9d 100644 --- a/algorithm/string/leetcode_242.cpp +++ b/algorithm/string/leetcode_242.cpp @@ -1,21 +1,26 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_242_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include #include #include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_242 { +using std::string; using std::array; +#endif -bool leetcode_242::isAnagram(const string &s, const string &t) { - std::array::max() + 1> arr{0}; - for (const auto ch: s) { ++arr[ch]; } - for (const auto ch: t) { --arr[ch]; } - return std::all_of(arr.cbegin(), arr.cend(), [](const auto ele) { return ele == 0; }); -} +class Solution { +public: + bool isAnagram(const string &s, const string &t) { + std::array::max() + 1> arr{0}; + for (const auto ch: s) { ++arr[ch]; } + for (const auto ch: t) { --arr[ch]; } + return std::all_of(arr.cbegin(), arr.cend(), [](const auto ele) { return ele == 0; }); + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_242_test.cpp b/algorithm/string/leetcode_242_test.cpp new file mode 100644 index 00000000..36710d61 --- /dev/null +++ b/algorithm/string/leetcode_242_test.cpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag string +//@Tag 字符串 +//@Plan 数据结构入门 Day6 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_242_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_242_TEST_HPP + +#include +#include "leetcode_242.cpp" +#include +#include +#include + +namespace leetcode_242 { + +TEST_CASE("1 [test_242]", "[test_242]") { + Solution solution; + static constexpr const char *const s{"anagram"}, *const t{"nagaram"}; + CHECK(solution.isAnagram(s, t)); +} + +TEST_CASE("2 [test_242]", "[test_242]") { + Solution solution; + static constexpr const char *const s{"rat"}, *const t{"cat"}; + CHECK_FALSE(solution.isAnagram(s, t)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_242_TEST_HPP diff --git a/algorithm/string/leetcode_242_test.hpp b/algorithm/string/leetcode_242_test.hpp deleted file mode 100644 index a84c9bd3..00000000 --- a/algorithm/string/leetcode_242_test.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -//@Plan 数据结构入门 Day6 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_242_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_242_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_242 { - -using std::string; - -struct leetcode_242 { - static bool isAnagram(const string &s, const string &t); -}; - -TEST_CASE("1 [test_242]", "[test_242]") { - static constexpr const char *const s{"anagram"}, *const t{"nagaram"}; - CHECK(leetcode_242::isAnagram(s, t)); -} - -TEST_CASE("2 [test_242]", "[test_242]") { - static constexpr const char *const s{"rat"}, *const t{"cat"}; - CHECK_FALSE(leetcode_242::isAnagram(s, t)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_242_TEST_HPP diff --git a/algorithm/string/leetcode_3.cpp b/algorithm/string/leetcode_3.cpp index 97fba817..0a63a3cc 100644 --- a/algorithm/string/leetcode_3.cpp +++ b/algorithm/string/leetcode_3.cpp @@ -1,80 +1,85 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_3_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +#include #include #include -/* -Given a string, -find the length of the longest substring without repeating characters. -greedy to get the max-length,if meet a repeat character,then throw the last one. -*/ +#include +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_3 { +using std::string; +using std::vector; using std::array; using std::bitset; +#endif -int32_t leetcode_3::lengthOfLongestSubstring(const string &s) { - const auto s_size{s.size()}; - size_t fst{0}; - int32_t maxLength{0}; - std::bitset<256> uarray{false}; - // std::array uarray{false}; - for (size_t i{0}; i < s_size; i++) { - if (!uarray[s[i]]) { - uarray[s[i]] = true; - maxLength = std::max(static_cast(1 + i - fst), maxLength); - } else { - for (size_t j{static_cast(fst)}; j < i; j++) { - fst++; - if (s[j] == s[i]) { - break; +class Solution { +public: + int32_t lengthOfLongestSubstring(const string &s) { + const auto s_size{s.size()}; + size_t fst{0}; + int32_t maxLength{0}; + std::bitset<256> uarray{false}; + // std::array uarray{false}; + for (size_t i{0}; i < s_size; i++) { + if (!uarray[s[i]]) { + uarray[s[i]] = true; + maxLength = std::max(static_cast(1 + i - fst), maxLength); + } else { + for (size_t j{static_cast(fst)}; j < i; j++) { + fst++; + if (s[j] == s[i]) { + break; + } + uarray[s[j]] = false; } - uarray[s[j]] = false; } } + return maxLength; } - return maxLength; -} -int32_t leetcode_3::lengthOfLongestSubstring2(const string &s) { - int32_t maxv{std::numeric_limits::min()}, len{0}, begin{0}; - const auto s_size = static_cast(s.size()); - std::array umap{0}; - for (int32_t i{0}; i < s_size; i++) { - len++; - if (umap[s[i]] != 0 && umap[s[i]] > begin) { - len += (begin - umap[s[i]]); - begin = umap[s[i]]; + int32_t lengthOfLongestSubstring2(const string &s) { + int32_t maxv{std::numeric_limits::min()}, len{0}, begin{0}; + const auto s_size = static_cast(s.size()); + std::array umap{0}; + for (int32_t i{0}; i < s_size; i++) { + len++; + if (umap[s[i]] != 0 && umap[s[i]] > begin) { + len += (begin - umap[s[i]]); + begin = umap[s[i]]; + } + maxv = std::max(len, maxv); + umap[s[i]] = i + 1; } - maxv = std::max(len, maxv); - umap[s[i]] = i + 1; + return std::max(len, maxv); } - return std::max(len, maxv); -} -int32_t leetcode_3::lengthOfLongestSubstring3(const string &s) { - const auto s_size = static_cast(s.size()); - if (s_size <= 1) { - return s_size; - } - std::array uarray = {false}; - int32_t left{0}, right{1}, diff{0}; - uarray[s[left]] = 1; - while (right < s_size) { - if (!uarray[s[right]]) { - uarray[s[right]] = true; - right++; - } else { - uarray[s[left]] = false; - left++; + int32_t lengthOfLongestSubstring3(const string &s) { + const auto s_size = static_cast(s.size()); + if (s_size <= 1) { + return s_size; + } + std::array uarray = {false}; + int32_t left{0}, right{1}, diff{0}; + uarray[s[left]] = 1; + while (right < s_size) { + if (!uarray[s[right]]) { + uarray[s[right]] = true; + right++; + } else { + uarray[s[left]] = false; + left++; + } + diff = std::max(diff, right - left); } - diff = std::max(diff, right - left); + return diff; } - return diff; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_344.cpp b/algorithm/string/leetcode_344.cpp index 7f4904a4..88b8e4a5 100644 --- a/algorithm/string/leetcode_344.cpp +++ b/algorithm/string/leetcode_344.cpp @@ -1,17 +1,23 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_344_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_344 { +using std::vector; +#endif -void leetcode_344::reverseString(vector &s) { - for (size_t left{0}, right{s.size() - 1}; left < right; left++, right--) { - std::swap(s[left], s[right]); +class Solution { +public: + void reverseString(vector &s) { + for (size_t left{0}, right{s.size() - 1}; left < right; left++, right--) { + std::swap(s[left], s[right]); + } } +}; + +#ifdef ALGORITHM_TEST_MACRO } -} +#endif diff --git a/algorithm/string/leetcode_344_test.hpp b/algorithm/string/leetcode_344_test.cpp similarity index 62% rename from algorithm/string/leetcode_344_test.hpp rename to algorithm/string/leetcode_344_test.cpp index 95663615..796d07d6 100644 --- a/algorithm/string/leetcode_344_test.hpp +++ b/algorithm/string/leetcode_344_test.cpp @@ -1,41 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag string //@Tag 字符串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_344_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_344_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_344_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_344_TEST_HPP #include +#include "leetcode_344.cpp" #include +#include namespace leetcode_344 { -using std::string; - -struct leetcode_344 { - static void reverseString(vector &s); -}; using Catch::Matchers::Equals; TEST_CASE("1 [test_344]", "[test_344]") { + Solution solution; static constexpr const char input[]{"hello"}; vector vInput{std::cbegin(input), std::cend(input)}; const vector result{std::crbegin(input), std::crend(input)}; - leetcode_344::reverseString(vInput); + solution.reverseString(vInput); CHECK_THAT(result, Equals(vInput)); } TEST_CASE("2 [test_344]", "[test_344]") { + Solution solution; static constexpr const char input[]{"hannah"}; vector vInput{std::cbegin(input), std::cend(input)}; const vector result{std::crbegin(input), std::crend(input)}; - leetcode_344::reverseString(vInput); + solution.reverseString(vInput); CHECK_THAT(result, Equals(vInput)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_344_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_344_TEST_HPP diff --git a/algorithm/string/leetcode_38.cpp b/algorithm/string/leetcode_38.cpp index c42efe72..b2ddad5d 100644 --- a/algorithm/string/leetcode_38.cpp +++ b/algorithm/string/leetcode_38.cpp @@ -1,29 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_38_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_38 { -string leetcode_38::countAndSay(int n) { - if (n == 1) { - return "1"; - } - string str1{countAndSay(n - 1)}; - string will_return{}; - const auto str1_size{str1.size()}; - for (size_t i{0}; i < str1_size;) { - int32_t length{0}; - while (str1[i + length] == str1[i]) { - length++; +using std::string; +#endif + +class Solution { +public: + string countAndSay(int n) { + if (n == 1) { + return "1"; } - will_return.append(1, length + '0'); - will_return.append(1, str1[i]); - i += length; + string str1{countAndSay(n - 1)}; + string will_return{}; + const auto str1_size{str1.size()}; + for (size_t i{0}; i < str1_size;) { + int32_t length{0}; + while (str1[i + length] == str1[i]) { + length++; + } + will_return.append(1, length + '0'); + will_return.append(1, str1[i]); + i += length; + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_383.cpp b/algorithm/string/leetcode_383.cpp index 5f6cfd1f..f5356b8e 100644 --- a/algorithm/string/leetcode_383.cpp +++ b/algorithm/string/leetcode_383.cpp @@ -1,30 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_383_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#include #include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_383 { +using std::string; using std::array; +#endif -bool leetcode_383::canConstruct(const string &ransomNote, const string &magazine) { - if (ransomNote.size() > magazine.size()) { - return false; - } - std::array::max() + 1> base{0}; - for (const auto ch: magazine) { - ++base[ch]; - } - for (const auto ch: ransomNote) { - --base[ch]; - if (base[ch] < 0) { +class Solution { +public: + bool canConstruct(const string &ransomNote, const string &magazine) { + if (ransomNote.size() > magazine.size()) { return false; } + std::array::max() + 1> base{0}; + for (const auto ch: magazine) { + ++base[ch]; + } + for (const auto ch: ransomNote) { + --base[ch]; + if (base[ch] < 0) { + return false; + } + } + return true; } - return true; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_383_test.cpp b/algorithm/string/leetcode_383_test.cpp new file mode 100644 index 00000000..896007b9 --- /dev/null +++ b/algorithm/string/leetcode_383_test.cpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag string +//@Tag 字符串 +//@Plan 数据结构入门 Day6 + +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_383_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_383_TEST_HPP + +#include +#include "leetcode_383.cpp" +#include +#include +#include + +namespace leetcode_383 { + +TEST_CASE("1 [test_383]", "[test_383]") { + Solution solution; + static constexpr const char *const inputR{"UD"}, *const inputM{"AUOKD"}; + CHECK(solution.canConstruct(inputR, inputM)); +} + +TEST_CASE("2 [test_383]", "[test_383]") { + Solution solution; + static constexpr const char *const inputR{"a"}, *const inputM{"b"}; + CHECK_FALSE(solution.canConstruct(inputR, inputM)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_383_TEST_HPP diff --git a/algorithm/string/leetcode_383_test.hpp b/algorithm/string/leetcode_383_test.hpp deleted file mode 100644 index 3413039a..00000000 --- a/algorithm/string/leetcode_383_test.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -//@Plan 数据结构入门 Day6 - -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_383_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_383_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_383 { - -using std::string; - -struct leetcode_383 { - static bool canConstruct(const string &ransomNote, const string &magazine); -}; - -TEST_CASE("1 [test_383]", "[test_383]") { - static constexpr const char *const inputR{"UD"}, *const inputM{"AUOKD"}; - CHECK(leetcode_383::canConstruct(inputR, inputM)); -} - -TEST_CASE("2 [test_383]", "[test_383]") { - static constexpr const char *const inputR{"a"}, *const inputM{"b"}; - CHECK_FALSE(leetcode_383::canConstruct(inputR, inputM)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_383_TEST_HPP diff --git a/algorithm/string/leetcode_387.cpp b/algorithm/string/leetcode_387.cpp index d66fb09c..9c3f7fbd 100644 --- a/algorithm/string/leetcode_387.cpp +++ b/algorithm/string/leetcode_387.cpp @@ -1,42 +1,49 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_387_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#include #include +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_387 { +using std::string; using std::array; +#endif -int32_t leetcode_387::firstUniqChar(const string &s) { - std::array chars{0}; - for (const auto ch: s) { - chars[ch]++; - } - for (size_t i{0}, size{s.size()}; i < size; ++i) { - if (chars[s[i]] == 1) { - return static_cast(i); +class Solution { +public: + int32_t firstUniqChar(const string &s) { + std::array chars{0}; + for (const auto ch: s) { + chars[ch]++; } + for (size_t i{0}, size{s.size()}; i < size; ++i) { + if (chars[s[i]] == 1) { + return static_cast(i); + } + } + return -1; } - return -1; -} -int32_t leetcode_387::firstUniqChar2(const string &s) { - std::array, 128> chars{}; - for (auto iter = s.crbegin(); iter != s.crend(); ++iter) { - const auto ch = *iter; - ++chars[ch].first; - chars[ch].second = s.crend() - iter; - } - int32_t will_return{0x3f3f3f3f}; - for (const auto&[k, v]: chars) { - if (k == 1) { - will_return = std::min(will_return, static_cast(v - 1)); + int32_t firstUniqChar2(const string &s) { + std::array, 128> chars{}; + for (auto iter = s.crbegin(); iter != s.crend(); ++iter) { + const auto ch = *iter; + ++chars[ch].first; + chars[ch].second = s.crend() - iter; + } + int32_t will_return{0x3f3f3f3f}; + for (const auto&[k, v]: chars) { + if (k == 1) { + will_return = std::min(will_return, static_cast(v - 1)); + } } + return will_return == 0x3f3f3f3f ? -1 : will_return; } - return will_return == 0x3f3f3f3f ? -1 : will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_387_test.cpp b/algorithm/string/leetcode_387_test.cpp new file mode 100644 index 00000000..d62bcc14 --- /dev/null +++ b/algorithm/string/leetcode_387_test.cpp @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag string +//@Tag 字符串] +//@Sword-Offer 50 +//@Plan 数据结构入门 Day6 +//@Plan 剑指OfferII-I Day05 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_387_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_387_TEST_HPP + +#include +#include "leetcode_387.cpp" +#include +#include +#include + +namespace leetcode_387 { + +TEST_CASE("1 [test_387]", "[test_387]") { + Solution solution; + static constexpr const char *const input{"UD"}; + static constexpr const auto result{0}; + CHECK(result == solution.firstUniqChar(input)); + CHECK(result == solution.firstUniqChar2(input)); +} + +TEST_CASE("2 [test_387]", "[test_387]") { + Solution solution; + static constexpr const char *const input{"leetcode"}; + static constexpr const auto result{0}; + CHECK(result == solution.firstUniqChar(input)); + CHECK(result == solution.firstUniqChar2(input)); +} + +TEST_CASE("3 [test_387]", "[test_387]") { + Solution solution; + static constexpr const char *const input{"loveleetcode"}; + static constexpr const auto result{2}; + CHECK(result == solution.firstUniqChar(input)); + CHECK(result == solution.firstUniqChar2(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_387_TEST_HPP diff --git a/algorithm/string/leetcode_387_test.hpp b/algorithm/string/leetcode_387_test.hpp deleted file mode 100644 index 0e0c92fa..00000000 --- a/algorithm/string/leetcode_387_test.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串] -//@Sword-Offer 50 -//@Plan 数据结构入门 Day6 -//@Plan 剑指OfferII-I Day05 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_387_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_387_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_387 { - -using std::string; - -struct leetcode_387 { - static int32_t firstUniqChar(const string &s); // better for short str - - static int32_t firstUniqChar2(const string &s); // better for long str -}; - -TEST_CASE("1 [test_387]", "[test_387]") { - static constexpr const char *const input{"UD"}; - static constexpr const auto result{0}; - CHECK(result == leetcode_387::firstUniqChar(input)); - CHECK(result == leetcode_387::firstUniqChar2(input)); -} - -TEST_CASE("2 [test_387]", "[test_387]") { - static constexpr const char *const input{"leetcode"}; - static constexpr const auto result{0}; - CHECK(result == leetcode_387::firstUniqChar(input)); - CHECK(result == leetcode_387::firstUniqChar2(input)); -} - -TEST_CASE("3 [test_387]", "[test_387]") { - static constexpr const char *const input{"loveleetcode"}; - static constexpr const auto result{2}; - CHECK(result == leetcode_387::firstUniqChar(input)); - CHECK(result == leetcode_387::firstUniqChar2(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_387_TEST_HPP diff --git a/algorithm/string/leetcode_38_test.cpp b/algorithm/string/leetcode_38_test.cpp new file mode 100644 index 00000000..5234137c --- /dev/null +++ b/algorithm/string/leetcode_38_test.cpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag string +//@Tag 字符串 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_38_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_38_TEST_HPP + +#include +#include "leetcode_38.cpp" +#include +#include +#include + +namespace leetcode_38 { + +TEST_CASE("1 [test_38]", "[test_38]") { + Solution solution; + CHECK(solution.countAndSay(1) == "1"); + CHECK(solution.countAndSay(2) == "11"); + CHECK(solution.countAndSay(3) == "21"); + CHECK(solution.countAndSay(4) == "1211"); + CHECK(solution.countAndSay(5) == "111221"); + CHECK(solution.countAndSay(6) == "312211"); + CHECK(solution.countAndSay(7) == "13112221"); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_38_TEST_HPP diff --git a/algorithm/string/leetcode_38_test.hpp b/algorithm/string/leetcode_38_test.hpp deleted file mode 100644 index f1ab2960..00000000 --- a/algorithm/string/leetcode_38_test.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_38_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_38_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_38 { - -using std::string; - -struct leetcode_38 { - static string countAndSay(int32_t n); -}; - -TEST_CASE("1 [test_38]", "[test_38]") { - CHECK(leetcode_38::countAndSay(1) == "1"); - CHECK(leetcode_38::countAndSay(2) == "11"); - CHECK(leetcode_38::countAndSay(3) == "21"); - CHECK(leetcode_38::countAndSay(4) == "1211"); - CHECK(leetcode_38::countAndSay(5) == "111221"); - CHECK(leetcode_38::countAndSay(6) == "312211"); - CHECK(leetcode_38::countAndSay(7) == "13112221"); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_38_TEST_HPP diff --git a/algorithm/string/leetcode_3_test.hpp b/algorithm/string/leetcode_3_test.cpp similarity index 58% rename from algorithm/string/leetcode_3_test.hpp rename to algorithm/string/leetcode_3_test.cpp index fb9bf9ac..e0cbd794 100644 --- a/algorithm/string/leetcode_3_test.hpp +++ b/algorithm/string/leetcode_3_test.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag string //@Tag 字符串 //@Tag HashMap @@ -12,30 +7,23 @@ Copyright (C) 2020-2023 nanoseeds //@Tag 滑动窗口 //@Plan 数据结构入门 Day10 //@Plan 剑指OfferII-I Day10 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_3_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_3_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_3_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_3_TEST_HPP #include +#include "leetcode_3.cpp" #include #include #include +#include namespace leetcode_3 { -using std::endl; -using std::string; - -struct leetcode_3 final { - static int32_t lengthOfLongestSubstring(const string &s); - - static int32_t lengthOfLongestSubstring2(const string &s); - - static int32_t lengthOfLongestSubstring3(const string &s); -}; void warpper(const string &s, int32_t length) { - CHECK(length == leetcode_3::lengthOfLongestSubstring(s)); - CHECK(length == leetcode_3::lengthOfLongestSubstring2(s)); - CHECK(length == leetcode_3::lengthOfLongestSubstring3(s)); + Solution solution; + CHECK(length == solution.lengthOfLongestSubstring(s)); + CHECK(length == solution.lengthOfLongestSubstring2(s)); + CHECK(length == solution.lengthOfLongestSubstring3(s)); } TEST_CASE("1 [test_3]", "[test_3]") { @@ -54,8 +42,9 @@ TEST_CASE("3 [test_3]", "[test_3]") { } TEST_CASE("4 [test_3]", "[test_3]") { + Solution solution; string str{"abba"}; - cout << leetcode_3::lengthOfLongestSubstring(str) << endl; + std::cout << solution.lengthOfLongestSubstring(str) << std::endl; warpper(str, 2); } @@ -79,4 +68,4 @@ TEST_CASE("8 [test_3]", "[test_3]") { warpper(str, 4); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_3_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_3_TEST_HPP diff --git a/algorithm/string/leetcode_535.cpp b/algorithm/string/leetcode_535.cpp index ae3c36c6..2c8fcc72 100644 --- a/algorithm/string/leetcode_535.cpp +++ b/algorithm/string/leetcode_535.cpp @@ -1,34 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_535_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#include #include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_535 { +using std::string; using std::unordered_map; +#endif -class c1 : public base { +class Solution { + unordered_map long_to_short; + unordered_map short_to_long; + static constexpr const char *const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + static constexpr const size_t url_len = 6; public: - [[nodiscard]] string encode(const string longUrl) override { - return longUrl; - } - - [[nodiscard]] string decode(const string shortUrl) override { + // Encodes a URL to a shortened URL. + string encode(string longUrl) { + if (long_to_short.count(longUrl)) { + return long_to_short[longUrl]; + } + string shortUrl; + do { + shortUrl = "http://tinyurl.com/"; + for (size_t i = 0; i < url_len; ++i) { + shortUrl += chars[rand() % 62]; + } + } while (short_to_long.count(shortUrl)); + long_to_short[longUrl] = shortUrl; + short_to_long[shortUrl] = longUrl; return shortUrl; } - static base *getPointer() { - static base *const pointer = new c1{}; - return pointer; + // Decodes a shortened URL to its original URL. + string decode(string shortUrl) { + return short_to_long[shortUrl]; } }; - -base *leetcode_535::getObject1() { - return c1::getPointer(); -} +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_535_test.cpp b/algorithm/string/leetcode_535_test.cpp new file mode 100644 index 00000000..0956d2e5 --- /dev/null +++ b/algorithm/string/leetcode_535_test.cpp @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag string +//@Tag 字符串 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_535_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_535_TEST_HPP + +#include "leetcode_535.cpp" +#include +#include + +namespace leetcode_535 { + +TEST_CASE("1 [test_535]", "[test_535]") { + Solution solution; + static constexpr const char *const input{"you know the rules and so do I"}; + CHECK(input == solution.decode(solution.encode(input))); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_535_TEST_HPP diff --git a/algorithm/string/leetcode_535_test.hpp b/algorithm/string/leetcode_535_test.hpp deleted file mode 100644 index 9e8ec376..00000000 --- a/algorithm/string/leetcode_535_test.hpp +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_535_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_535_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_535 { - -using std::string; - -class base { -public: - ~base() = default; - - virtual string encode(string longUrl) = 0; - - virtual string decode(string shortUrl) = 0; - - void ensure(const string &input) { - CHECK(this->decode(this->encode(input)) == input); - } -}; - -struct leetcode_535 { - static base *getObject1(); - -}; - -TEST_CASE("1 [test_535]", "[test_535]") { - static constexpr const char *const input{"you know the rules and so do I"}; - base *const pointer = leetcode_535::getObject1(); - CHECK(input == pointer->decode(pointer->encode(input))); - pointer->ensure(input); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_535_TEST_HPP diff --git a/algorithm/string/leetcode_6.cpp b/algorithm/string/leetcode_6.cpp index a3520bdf..92f4557a 100644 --- a/algorithm/string/leetcode_6.cpp +++ b/algorithm/string/leetcode_6.cpp @@ -1,48 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_6_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_6 { -string leetcode_6::convert(const string &s, int numRows) { - const auto s_size{s.size()}, numRows_size{static_cast(numRows)}; - if (s_size <= numRows_size || numRows_size == 1) { - return s; - } - vector vec(s_size); - const size_t batch{numRows_size * 2 - 2}, - block_number{s_size / batch}, - batch_size{batch * block_number}, - left_num{s_size - batch_size}; - size_t count{0uLL}; - for (size_t i{0}; i < s_size; i += batch, count++) { - vec[count] = s[i]; - } - for (size_t i{1}; i < numRows_size - 1; i++) { - for (size_t j{0}; j < batch_size; j += batch, count += 2) { - vec[count] = s[j + i]; - vec[count + 1] = s[j + batch - i]; +using std::string; +using std::vector; +#endif + +class Solution { +public: + string convert(const string &s, int numRows) { + const auto s_size{s.size()}, numRows_size{static_cast(numRows)}; + if (s_size <= numRows_size || numRows_size == 1) { + return s; } - if (left_num > i) { - vec[count] = s[batch_size + i]; - count++; - if (left_num > batch - i) { - vec[count] = s[batch_size + batch - i]; - count++; + string will_return; + will_return.reserve(s_size); + const size_t batch{numRows_size * 2 - 2}; + for (size_t i = 0; i < numRows_size; ++i) { + for (size_t j = 0; j + i < s_size; j += batch) { + will_return += s[j + i]; + if (i > 0 && i < numRows_size - 1 && j + batch - i < s_size) { + will_return += s[j + batch - i]; + } } } + return will_return; } - for (size_t i{0}; i < batch_size; i += batch, count++) { - vec[count] = s[i + (numRows_size - 1)]; - } - if (left_num >= numRows_size) { - vec[count] = s[batch_size + numRows_size - 1]; - } - return {vec.cbegin(), vec.cend()}; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_657.cpp b/algorithm/string/leetcode_657.cpp index 37ba3036..11a6f262 100644 --- a/algorithm/string/leetcode_657.cpp +++ b/algorithm/string/leetcode_657.cpp @@ -1,36 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_657_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_657 { +using std::string; +#endif -bool leetcode_657::judgeCircle(const string &moves) { - int32_t x{0}, y{0}; - for (size_t i{0}, moves_size{moves.size()}; i < moves_size; ++i) { - switch (moves[i]) { - case ('L'): { - x++; - break; - } - case ('R'): { - x--; - break; - } - case ('U'): { - y++; - break; - } - case ('D'): { - y--; - break; +class Solution { +public: + bool judgeCircle(const string &moves) { + int32_t x{0}, y{0}; + for (const auto move : moves) { + switch (move) { + case 'L': + x++; + break; + case 'R': + x--; + break; + case 'U': + y++; + break; + case 'D': + y--; + break; } } + return (x == 0 && y == 0); } - return (x == 0 && y == 0); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_657_test.cpp b/algorithm/string/leetcode_657_test.cpp new file mode 100644 index 00000000..e420d652 --- /dev/null +++ b/algorithm/string/leetcode_657_test.cpp @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag string +//@Tag 字符串 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_657_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_657_TEST_HPP + +#include +#include "leetcode_657.cpp" +#include + +namespace leetcode_657 { + +TEST_CASE("1 [test_657]", "[test_657]") { + Solution solution; + static constexpr const char *const input{"UD"}; + CHECK(solution.judgeCircle(input)); +} + +TEST_CASE("2 [test_657]", "[test_657]") { + Solution solution; + static constexpr const char *const input{"LL"}; + CHECK_FALSE(solution.judgeCircle(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_657_TEST_HPP diff --git a/algorithm/string/leetcode_657_test.hpp b/algorithm/string/leetcode_657_test.hpp deleted file mode 100644 index 0d4ac8bd..00000000 --- a/algorithm/string/leetcode_657_test.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_657_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_657_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_657 { -using std::string; - -struct leetcode_657 { - static bool judgeCircle(const string &moves); -}; - -TEST_CASE("1 [test_657]", "[test_657]") { - static constexpr const char *const input{"UD"}; - CHECK(leetcode_657::judgeCircle(input)); -} - -TEST_CASE("2 [test_657]", "[test_657]") { - static constexpr const char *const input{"LL"}; - CHECK_FALSE(leetcode_657::judgeCircle(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_657_TEST_HPP diff --git a/algorithm/string/leetcode_6_test.cpp b/algorithm/string/leetcode_6_test.cpp new file mode 100644 index 00000000..2e4eb402 --- /dev/null +++ b/algorithm/string/leetcode_6_test.cpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag string +//@Tag 字符串 +//@Tag 模仿 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_6_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_6_TEST_HPP + +#include "leetcode_6.cpp" +#include +#include +#include + +namespace leetcode_6 { + +TEST_CASE("test basic [test_6]", "[test_6]") { + Solution solution; + CHECK(solution.convert("PAYPALISHIRING", 3) == "PAHNAPLSIIGYIR"); + CHECK(solution.convert("PAYPALISHIRING", 4) == "PINALSIGYAHRPI"); + CHECK(solution.convert("A", 1) == "A"); + CHECK(solution.convert("AB", 2) == "AB"); + CHECK(solution.convert("ABC", 3) == "ABC"); + CHECK(solution.convert("ABCD", 4) == "ABCD"); + CHECK(solution.convert("ABCDE", 4) == "ABCED"); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_6_TEST_HPP diff --git a/algorithm/string/leetcode_6_test.hpp b/algorithm/string/leetcode_6_test.hpp deleted file mode 100644 index af25cb2b..00000000 --- a/algorithm/string/leetcode_6_test.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -//@Tag 模仿 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_6_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_6_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_6 { -using std::string; - -struct leetcode_6 { - static string convert(const string &s, int32_t numRows); -}; - - -TEST_CASE("test basic [test_6]", "[test_6]") { - CHECK(leetcode_6::convert("PAYPALISHIRING", 3) == "PAHNAPLSIIGYIR"); - CHECK(leetcode_6::convert("PAYPALISHIRING", 4) == "PINALSIGYAHRPI"); - CHECK(leetcode_6::convert("A", 1) == "A"); - CHECK(leetcode_6::convert("AB", 2) == "AB"); - CHECK(leetcode_6::convert("ABC", 3) == "ABC"); - CHECK(leetcode_6::convert("ABCD", 4) == "ABCD"); - CHECK(leetcode_6::convert("ABCDE", 4) == "ABCED"); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_6_TEST_HPP diff --git a/algorithm/string/leetcode_709.cpp b/algorithm/string/leetcode_709.cpp index f388fd98..10f041a6 100644 --- a/algorithm/string/leetcode_709.cpp +++ b/algorithm/string/leetcode_709.cpp @@ -1,30 +1,27 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_709_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include #include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_709 { +using std::string; using std::array; +#endif -constexpr std::array::max() + 1> prepare() { - std::array::max() + 1> bigs{0}; - for (char ch{'A'}; ch <= 'Z'; ++ch) { - bigs[ch] = ('a' - 'A'); +class Solution { +public: + string toLowerCase(string s) { + for (char &c : s) { + if (c >= 'A' && c <= 'Z') { + c = c - 'A' + 'a'; + } + } + return s; } - return bigs; -} +}; -string leetcode_709::toLowerCase(const string &str) { - static constexpr const std::array arr{prepare()}; - string will_return{str}; - for (auto &ch: will_return) { - ch += arr[ch]; - } - return will_return; -} +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_709_test.cpp b/algorithm/string/leetcode_709_test.cpp new file mode 100644 index 00000000..bd1bdc57 --- /dev/null +++ b/algorithm/string/leetcode_709_test.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag string +//@Tag 字符串 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_709_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_709_TEST_HPP + +#include +#include "leetcode_709.cpp" +#include + +namespace leetcode_709 { + +using Catch::Matchers::Equals; + +TEST_CASE("1 [test_709]", "[test_709]") { + Solution solution; + static constexpr const char *const input{"UD"}, *const output{"ud"}; + CHECK_THAT(output, Equals(solution.toLowerCase(input))); +} + +TEST_CASE("2 [test_709]", "[test_709]") { + Solution solution; + static constexpr const char *const input{"LoL"}, *const output{"lol"}; + CHECK_THAT(output, Equals(solution.toLowerCase(input))); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_709_TEST_HPP diff --git a/algorithm/string/leetcode_709_test.hpp b/algorithm/string/leetcode_709_test.hpp deleted file mode 100644 index 03478408..00000000 --- a/algorithm/string/leetcode_709_test.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_709_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_709_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_709 { -using std::string; - -struct leetcode_709 { - static string toLowerCase(const string &str); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("1 [test_709]", "[test_709]") { - static constexpr const char *const input{"UD"}, *const output{"ud"}; - CHECK_THAT(output, Equals(leetcode_709::toLowerCase(input))); -} - -TEST_CASE("2 [test_709]", "[test_709]") { - static constexpr const char *const input{"LoL"}, *const output{"lol"}; - CHECK_THAT(output, Equals(leetcode_709::toLowerCase(input))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_709_TEST_HPP diff --git a/algorithm/string/leetcode_763.cpp b/algorithm/string/leetcode_763.cpp index b2c31397..1fef2097 100644 --- a/algorithm/string/leetcode_763.cpp +++ b/algorithm/string/leetcode_763.cpp @@ -1,30 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_763_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +#include #include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_763 { +using std::string; +using std::vector; using std::array; +#endif -vector leetcode_763::partitionLabels(const string &S) { - array vals{0}; - vector willreturn{}; - for (size_t i{0}; i < S.size(); i++) { - vals[S[i] - 'a'] = i; // chara -> rightest pos - } - for (size_t left{0}, right{0}, i{0}; i < S.size(); i++) { - right = std::max(right, vals[S[i] - 'a']); - // this and the next judge means, if the left's range final in here. - if (right == i) { - willreturn.push_back(right - left + 1); - left += willreturn.back(); +class Solution { +public: + vector partitionLabels(const string &S) { + array vals{0}; + vector willreturn{}; + for (size_t i{0}; i < S.size(); i++) { + vals[S[i] - 'a'] = i; // chara -> rightest pos } + for (size_t left{0}, right{0}, i{0}; i < S.size(); i++) { + right = std::max(right, vals[S[i] - 'a']); + // this and the next judge means, if the left's range final in here. + if (right == i) { + willreturn.push_back(right - left + 1); + left += willreturn.back(); + } + } + return willreturn; } - return willreturn; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_763_test.cpp b/algorithm/string/leetcode_763_test.cpp new file mode 100644 index 00000000..10f0535f --- /dev/null +++ b/algorithm/string/leetcode_763_test.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag string +//@Tag 字符串 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_763_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_763_TEST_HPP + +#include +#include "leetcode_763.cpp" +#include +#include + +namespace leetcode_763 { + +using Catch::Matchers::Equals; + +TEST_CASE("1 [test_763]", "[test_763]") { + Solution solution; + static constexpr const char *const input{"ababcbacadefegdehijhklij"}; + const vector output{9, 7, 8}; + CHECK_THAT(output, Equals(solution.partitionLabels(input))); +} + +TEST_CASE("2 [test_763]", "[test_763]") { + Solution solution; + static constexpr const char *const input{"eccbbbbdec"}; + const vector output{10}; + CHECK_THAT(output, Equals(solution.partitionLabels(input))); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_763_TEST_HPP diff --git a/algorithm/string/leetcode_763_test.hpp b/algorithm/string/leetcode_763_test.hpp deleted file mode 100644 index a13181b5..00000000 --- a/algorithm/string/leetcode_763_test.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_763_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_763_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_763 { -using std::vector; -using std::string; - -struct leetcode_763 { - static vector partitionLabels(const string &S); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("1 [test_763]", "[test_763]") { - static constexpr const char *const input{"ababcbacadefegdehijhklij"}; - const vector output{9, 7, 8}; - CHECK_THAT(output, Equals(leetcode_763::partitionLabels(input))); -} - -TEST_CASE("2 [test_763]", "[test_763]") { - static constexpr const char *const input{"eccbbbbdec"}; - const vector output{10}; - CHECK_THAT(output, Equals(leetcode_763::partitionLabels(input))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_763_TEST_HPP diff --git a/algorithm/string/leetcode_771.cpp b/algorithm/string/leetcode_771.cpp index ffa5151a..3697cb0b 100644 --- a/algorithm/string/leetcode_771.cpp +++ b/algorithm/string/leetcode_771.cpp @@ -1,25 +1,30 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_771_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include #include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_771 { +using std::string; using std::array; +#endif -int leetcode_771::numJewelsInStones(const string &jewels, const string &stones) { - std::array umap{false}; - int count = 0; - for (const auto jewel: jewels) { - umap[jewel] = true; - } - for (const auto stone: stones) { - count += (umap[stone]); +class Solution { +public: + int numJewelsInStones(const string &jewels, const string &stones) { + std::array umap{false}; + int count = 0; + for (const auto jewel: jewels) { + umap[jewel] = true; + } + for (const auto stone: stones) { + count += (umap[stone]); + } + return count; } - return count; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_771_test.cpp b/algorithm/string/leetcode_771_test.cpp new file mode 100644 index 00000000..99134fff --- /dev/null +++ b/algorithm/string/leetcode_771_test.cpp @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag string +//@Tag 字符串 +//@Description 非常简单 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_771_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_771_TEST_HPP + +#include +#include "leetcode_771.cpp" +#include + +namespace leetcode_771 { + +TEST_CASE("1 [test_771]", "[test_771]") { + Solution solution; + static constexpr const char *const jewels{"aA"}, *const stones{"aAAbbbb"}; + static constexpr const auto output{3}; + CHECK(output == solution.numJewelsInStones(jewels, stones)); +} + +TEST_CASE("2 [test_771]", "[test_771]") { + Solution solution; + static constexpr const char *const jewels{"z"}, *const stones{"ZZ"}; + static constexpr const auto output{0}; + CHECK(output == solution.numJewelsInStones(jewels, stones)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_771_TEST_HPP diff --git a/algorithm/string/leetcode_771_test.hpp b/algorithm/string/leetcode_771_test.hpp deleted file mode 100644 index 39be8f78..00000000 --- a/algorithm/string/leetcode_771_test.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -//@Description 非常简单 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_771_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_771_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_771 { -using std::string; - -struct leetcode_771 { - static int numJewelsInStones(const string &jewels, const string &stones); -}; - -TEST_CASE("1 [test_771]", "[test_771]") { - static constexpr const char *const jewels{"aA"}, *const stones{"aAAbbbb"}; - static constexpr const auto output{3}; - CHECK(output == leetcode_771::numJewelsInStones(jewels, stones)); -} - -TEST_CASE("2 [test_771]", "[test_771]") { - static constexpr const char *const jewels{"z"}, *const stones{"ZZ"}; - static constexpr const auto output{0}; - CHECK(output == leetcode_771::numJewelsInStones(jewels, stones)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_771_TEST_HPP diff --git a/algorithm/string/leetcode_784.cpp b/algorithm/string/leetcode_784.cpp index fa4b78d2..3331523d 100644 --- a/algorithm/string/leetcode_784.cpp +++ b/algorithm/string/leetcode_784.cpp @@ -1,48 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_784_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_784 { - -static constexpr const char diff = 'A' - 'a'; - -char low_to_up(const char &ch) { - if (ch >= 'A' && ch <= 'Z') { - return ch - diff; - } - return ch; -} - -char up_to_low(const char &ch) { - if (ch >= 'a' && ch <= 'z') { - return ch + diff; +using std::string; +using std::vector; +#endif + +class Solution { +public: + vector letterCasePermutation(string S) { + vector result; + dfs(S, 0, result); + return result; } - return ch; -} -vector leetcode_784::letterCasePermutation(const string &S) { - const auto s_size{S.size()}; - vector pos; - pos.reserve(s_size); - for (size_t i{0}; i < s_size; ++i) { - if (std::isalpha(S[i])) { - pos.push_back(i); +private: + void dfs(string &s, int index, vector &result) { + if (index == s.length()) { + result.push_back(s); + return; } - } - const size_t pos_size{pos.size()}, will_return_size = 1 << pos_size; - vector will_return(will_return_size, S); - for (size_t i{0}; i < pos_size; ++i) { - const int divisor = (1 << (pos.size() - 1 - i)); - for (size_t j{0}; j < will_return_size; ++j) { - will_return[j][pos[i]] = ((j / divisor) % 2 == 0) ? low_to_up(S[pos[i]]) : up_to_low(S[pos[i]]); + dfs(s, index + 1, result); + if (isalpha(s[index])) { + s[index] ^= 32; + dfs(s, index + 1, result); } } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_784_test.cpp b/algorithm/string/leetcode_784_test.cpp new file mode 100644 index 00000000..d0edde73 --- /dev/null +++ b/algorithm/string/leetcode_784_test.cpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag string +//@Tag 字符串 +//@Description 非常简单 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_784_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_784_TEST_HPP + +#include +#include "leetcode_784.cpp" +#include +#include +#include + +namespace leetcode_784 { + +using Catch::Matchers::UnorderedEquals; + +TEST_CASE("1 [test_784]", "[test_784]") { + Solution solution; + static constexpr const char *const input{"a1b2"}; + static const std::array arr{"a1b2", "a1B2", "A1b2", "A1B2"}; + const vector output{arr.cbegin(), arr.cend()}; + CHECK_THAT(solution.letterCasePermutation(input), UnorderedEquals(output)); +} + +TEST_CASE("2 [test_784]", "[test_784]") { + Solution solution; + static constexpr const char *const input{"3z4"}; + static const std::array arr{"3z4", "3Z4"}; + const vector output{arr.cbegin(), arr.cend()}; + CHECK_THAT(solution.letterCasePermutation(input), UnorderedEquals(output)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_784_TEST_HPP diff --git a/algorithm/string/leetcode_784_test.hpp b/algorithm/string/leetcode_784_test.hpp deleted file mode 100644 index ec3fd022..00000000 --- a/algorithm/string/leetcode_784_test.hpp +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -//@Description 非常简单 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_784_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_784_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_784 { -using std::string; - -struct leetcode_784 { - static vector letterCasePermutation(const string &S); -}; - -using Catch::Matchers::UnorderedEquals; - -TEST_CASE("1 [test_784]", "[test_784]") { - static constexpr const char *const input{"a1b2"}; - static constexpr const std::array arr{"a1b2", "a1B2", "A1b2", "A1B2"}; - const vector output{arr.cbegin(), arr.cend()}; - CHECK_THAT(output, UnorderedEquals(leetcode_784::letterCasePermutation(input))); -} - -TEST_CASE("2 [test_784]", "[test_784]") { - static constexpr const char *const input{"3z4"}; - static constexpr const std::array arr{"3z4", "3Z4"}; - const vector output{arr.cbegin(), arr.cend()}; - CHECK_THAT(output, UnorderedEquals(leetcode_784::letterCasePermutation(input))); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_784_TEST_HPP diff --git a/algorithm/string/leetcode_8.cpp b/algorithm/string/leetcode_8.cpp index d44be3e9..35b212b9 100644 --- a/algorithm/string/leetcode_8.cpp +++ b/algorithm/string/leetcode_8.cpp @@ -1,37 +1,45 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_8_test.hpp" +#include +#include namespace leetcode_8 { +using std::string; +#endif -int leetcode_8::myAtoi(const string &str) { - size_t begin{0}; - int8_t sign{1}; - int64_t will_return{0}; - while (str[begin] == ' ') { - begin++; - } - if (str[begin] >= 'a' && str[begin] <= 'z') { - return 0; - } else if (str[begin] == '+') { - begin++; - } else if (str[begin] == '-') { - sign = -1; - begin++; - } - while (str[begin] >= '0' && str[begin] <= '9') { - will_return = will_return * 10 + (str[begin] - '0'); - begin++; - if (will_return > std::numeric_limits::max()) { - return sign == 1 ? std::numeric_limits::max() : - std::numeric_limits::min(); +class Solution { +public: + int myAtoi(const string &str) { + size_t begin{0}; + int8_t sign{1}; + int64_t will_return{0}; + while (str[begin] == ' ') { + begin++; + } + if (str[begin] >= 'a' && str[begin] <= 'z') { + return 0; + } else if (str[begin] == '+') { + begin++; + } else if (str[begin] == '-') { + sign = -1; + begin++; + } + while (str[begin] >= '0' && str[begin] <= '9') { + will_return = will_return * 10 + (str[begin] - '0'); + begin++; + if (will_return > std::numeric_limits::max()) { + return sign == 1 ? std::numeric_limits::max() : + std::numeric_limits::min(); + } } + return static_cast(will_return * sign); } - return static_cast(will_return * sign); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif + + diff --git a/algorithm/string/leetcode_8_test.cpp b/algorithm/string/leetcode_8_test.cpp new file mode 100644 index 00000000..65f21e45 --- /dev/null +++ b/algorithm/string/leetcode_8_test.cpp @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag string +//@Tag 字符串 +//@Tag 模拟 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_8_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_8_TEST_HPP + +#include +#include "leetcode_8.cpp" + +namespace leetcode_8 { + +TEST_CASE("1 [test_8]", "[test_8]") { + Solution solution; + CHECK(solution.myAtoi("42") == 42); + CHECK(solution.myAtoi("65537") == 65537); + CHECK(solution.myAtoi("114514") == 114514); + CHECK(solution.myAtoi("1919810") == 1919810); +} + +TEST_CASE("2 [test_8]", "[test_8]") { + Solution solution; + CHECK(solution.myAtoi("+42") == 42); + CHECK(solution.myAtoi("+65537") == 65537); + CHECK(solution.myAtoi("+114514") == 114514); + CHECK(solution.myAtoi("+1919810") == 1919810); +} + +TEST_CASE("3 [test_8]", "[test_8]") { + Solution solution; + CHECK(solution.myAtoi("-42") == -42); + CHECK(solution.myAtoi("-65537") == -65537); + CHECK(solution.myAtoi("-114514") == -114514); + CHECK(solution.myAtoi("-1919810") == -1919810); +} + +TEST_CASE("4 [test_8]", "[test_8]") { + Solution solution; + CHECK(solution.myAtoi(" -42") == -42); + CHECK(solution.myAtoi(" -65537") == -65537); + CHECK(solution.myAtoi(" -114514") == -114514); + CHECK(solution.myAtoi(" -1919810") == -1919810); +} + +TEST_CASE("5 [test_8]", "[test_8]") { + Solution solution; + CHECK(solution.myAtoi("114514 with meaningless words") == 114514); + CHECK(solution.myAtoi("meaningless words with -65537") == 0); + CHECK(solution.myAtoi("2147483647") == std::numeric_limits::max()); + CHECK(solution.myAtoi("-2147483648") == std::numeric_limits::min()); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_8_TEST_HPP diff --git a/algorithm/string/leetcode_8_test.hpp b/algorithm/string/leetcode_8_test.hpp deleted file mode 100644 index 819c235b..00000000 --- a/algorithm/string/leetcode_8_test.hpp +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -//@Tag 模拟 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_8_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_8_TEST_HPP - -#include -#include - -namespace leetcode_8 { -using std::string; - -struct leetcode_8 { - static int myAtoi(const string &str); -}; - -TEST_CASE("1 [test_8]", "[test_8]") { - CHECK(leetcode_8::myAtoi("42") == 42); - CHECK(leetcode_8::myAtoi("65537") == 65537); - CHECK(leetcode_8::myAtoi("114514") == 114514); - CHECK(leetcode_8::myAtoi("1919810") == 1919810); -} - -TEST_CASE("2 [test_8]", "[test_8]") { - CHECK(leetcode_8::myAtoi("+42") == 42); - CHECK(leetcode_8::myAtoi("+65537") == 65537); - CHECK(leetcode_8::myAtoi("+114514") == 114514); - CHECK(leetcode_8::myAtoi("+1919810") == 1919810); -} - -TEST_CASE("3 [test_8]", "[test_8]") { - CHECK(leetcode_8::myAtoi("-42") == -42); - CHECK(leetcode_8::myAtoi("-65537") == -65537); - CHECK(leetcode_8::myAtoi("-114514") == -114514); - CHECK(leetcode_8::myAtoi("-1919810") == -1919810); -} - -TEST_CASE("4 [test_8]", "[test_8]") { - CHECK(leetcode_8::myAtoi(" -42") == -42); - CHECK(leetcode_8::myAtoi(" -65537") == -65537); - CHECK(leetcode_8::myAtoi(" -114514") == -114514); - CHECK(leetcode_8::myAtoi(" -1919810") == -1919810); -} - -TEST_CASE("5 [test_8]", "[test_8]") { - CHECK(leetcode_8::myAtoi("114514 with meaningless words") == 114514); - CHECK(leetcode_8::myAtoi("meaningless words with -65537") == 0); - CHECK(leetcode_8::myAtoi("2147483647") == std::numeric_limits::max()); - CHECK(leetcode_8::myAtoi("-2147483648") == std::numeric_limits::min()); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_8_TEST_HPP diff --git a/algorithm/string/leetcode_so_05.cpp b/algorithm/string/leetcode_so_05.cpp index bc59f439..60957e79 100644 --- a/algorithm/string/leetcode_so_05.cpp +++ b/algorithm/string/leetcode_so_05.cpp @@ -1,34 +1,39 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_so_05_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_so_05 { -string leetcode_so_05::replaceSpace(const string &str) { - size_t space{0}; - for (const auto ch: str) { - if (ch == ' ') { - space++; +using std::string; +#endif + +class Solution { +public: + string replaceSpace(const string &str) { + size_t space{0}; + for (const auto ch: str) { + if (ch == ' ') { + space++; + } } - } - const auto str_size{str.size()}; - string will_return; - will_return.resize((space << 1) + str_size); - for (size_t r{str_size}, r_will{will_return.size() - 1}; r > 0; --r, --r_will) { - if (str[r - 1] != ' ') { - will_return[r_will] = str[r - 1]; - } else { - will_return[r_will] = '0'; - --r_will; - will_return[r_will] = '2'; - --r_will; - will_return[r_will] = '%'; + const auto str_size{str.size()}; + string will_return; + will_return.resize((space << 1) + str_size); + for (size_t r{str_size}, r_will{will_return.size() - 1}; r > 0; --r, --r_will) { + if (str[r - 1] != ' ') { + will_return[r_will] = str[r - 1]; + } else { + will_return[r_will] = '0'; + --r_will; + will_return[r_will] = '2'; + --r_will; + will_return[r_will] = '%'; + } } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_so_05_test.cpp b/algorithm/string/leetcode_so_05_test.cpp new file mode 100644 index 00000000..61fea1dc --- /dev/null +++ b/algorithm/string/leetcode_so_05_test.cpp @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag string +//@Tag 字符串 +//@Plan 剑指OfferII-I Day03 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_05_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_05_TEST_HPP + +#include +#include "leetcode_so_05.cpp" +#include + +namespace leetcode_so_05 { + +TEST_CASE("1 [test_so_05]", "[test_so_05]") { + Solution solution; + static constexpr const char *const input{"We are happy."}, *const result{"We%20are%20happy."}; + CHECK(result == solution.replaceSpace(input)); +} + +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_05_TEST_HPP diff --git a/algorithm/string/leetcode_so_05_test.hpp b/algorithm/string/leetcode_so_05_test.hpp deleted file mode 100644 index 36464b46..00000000 --- a/algorithm/string/leetcode_so_05_test.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -//@Plan 剑指OfferII-I Day03 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_05_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_05_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_so_05 { - -using std::string; - -struct leetcode_so_05 { - static string replaceSpace(const string &str); -}; - - -TEST_CASE("1 [test_so_05]", "[test_so_05]") { - static constexpr const char *const input{"We are happy."}, *const result{"We%20are%20happy."}; - CHECK(result == leetcode_so_05::replaceSpace(input)); -} - -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_05_TEST_HPP diff --git a/algorithm/string/leetcode_so_58.cpp b/algorithm/string/leetcode_so_58.cpp index 978e9b54..03d81dd2 100644 --- a/algorithm/string/leetcode_so_58.cpp +++ b/algorithm/string/leetcode_so_58.cpp @@ -1,48 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_so_58_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#include +#include +#include +#ifdef ALGORITHM_TEST_MACRO namespace leetcode_so_58 { +using std::string; +using std::vector; +#endif -string leetcode_so_58::reverseLeftWords(const string &s, int32_t n) { - const auto s_size{s.size()}; - const auto mid{s_size - n}; - string will_reutrn(s_size, ' '); - for (size_t i = n; i < s_size; ++i) { - will_reutrn[i - n] = s[i]; +class Solution { +public: + string reverseLeftWords(string s, int n) { + std::reverse(s.begin(), s.begin() + n); + std::reverse(s.begin() + n, s.end()); + std::reverse(s.begin(), s.end()); + return s; } - for (int32_t i{0}; i < n; ++i) { - will_reutrn[mid + i] = s[i]; - } - return will_reutrn; -} -string leetcode_so_58::reverseWords(const string &s) { - const auto s_size{s.size()}; - vector strs; - string str{}; - str.reserve(s_size); - for (size_t left{0}; left < s_size; ++left, str.clear()) { - for (; left < s_size && s[left] == ' '; ++left) {} - for (; left < s_size && s[left] != ' '; ++left) { str += s[left]; } - if (!str.empty()) { - strs.push_back(str); + string reverseWords(string s) { + std::reverse(s.begin(), s.end()); + int n = s.length(); + int idx = 0; + for (int start = 0; start < n; ++start) { + if (s[start] != ' ') { + if (idx != 0) s[idx++] = ' '; + int end = start; + while (end < n && s[end] != ' ') s[idx++] = s[end++]; + std::reverse(s.begin() + idx - (end - start), s.begin() + idx); + start = end; + } } + s.erase(s.begin() + idx, s.end()); + return s; } - if (strs.empty()) { - return {}; - } - string will_return{}; - will_return = strs.back(); - for (auto iter = strs.rbegin() + 1; iter != strs.rend(); ++iter) { - //will_return = will_return + *iter; - will_return += ' ' + *iter; - } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string/leetcode_so_58_test.cpp b/algorithm/string/leetcode_so_58_test.cpp new file mode 100644 index 00000000..ea16c1fc --- /dev/null +++ b/algorithm/string/leetcode_so_58_test.cpp @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag string +//@Tag 字符串 +//@Plan 剑指OfferII-I Day03 +//@Plan 剑指OfferII-I Day13 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_58_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_58_TEST_HPP + +#include +#include "leetcode_so_58.cpp" +#include + +namespace leetcode_so_58 { + +using Catch::Matchers::Equals; + +TEST_CASE("2 [test_so_58 i]", "[test_so_58]") { + Solution solution; + static constexpr const char *const input{" hello world! "}, *const result{"world! hello"}; + CHECK_THAT(solution.reverseWords(input), Equals(result)); +} + +TEST_CASE("1 [test_so_58 i]", "[test_so_58]") { + Solution solution; + static constexpr const char *const input{"I am a aritist."}, *const result{"aritist. a am I"}; + CHECK_THAT(solution.reverseWords(input), Equals(result)); +} + +TEST_CASE("1 [test_so_58 ii]", "[test_so_58]") { + Solution solution; + static constexpr const char *const input{"abcdefg"}, *const result{"cdefgab"}; + static constexpr const auto n{2}; + CHECK_THAT(solution.reverseLeftWords(input, n), Equals(result)); +} + +TEST_CASE("2 [test_so_58 ii]", "[test_so_58]") { + Solution solution; + static constexpr const char *const input{"lrloseumgh"}, *const result{"umghlrlose"}; + static constexpr const auto n{6}; + CHECK_THAT(solution.reverseLeftWords(input, n), Equals(result)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_58_TEST_HPP diff --git a/algorithm/string/leetcode_so_58_test.hpp b/algorithm/string/leetcode_so_58_test.hpp deleted file mode 100644 index 1d821975..00000000 --- a/algorithm/string/leetcode_so_58_test.hpp +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -//@Plan 剑指OfferII-I Day03 -//@Plan 剑指OfferII-I Day13 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_58_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_58_TEST_HPP - -#include -#include -#include -#include - -namespace leetcode_so_58 { - -using std::string; - -struct leetcode_so_58 { - static string reverseLeftWords(const string &s, int32_t n); - - static string reverseWords(const string &s); -}; - -using Catch::Matchers::Equals; - -TEST_CASE("2 [test_so_58 i]", "[test_so_58]") { - static constexpr const char *const input{" hello world! "}, *const result{"world! hello"}; - CHECK_THAT(result, Equals(leetcode_so_58::reverseWords(input))); -} - -TEST_CASE("1 [test_so_58 i]", "[test_so_58]") { - static constexpr const char *const input{"I am a aritist."}, *const result{"aritist. a am I"}; - CHECK_THAT(result, Equals(leetcode_so_58::reverseWords(input))); -} - -TEST_CASE("1 [test_so_58 ii]", "[test_so_58]") { - static constexpr const char *const input{"We are happy."}, *const result{"are happy.We "}; - static constexpr const auto n{3}; - CHECK_THAT(result, Equals(leetcode_so_58::reverseLeftWords(input, n))); -} - -TEST_CASE("2 [test_so_58 ii]", "[test_so_58]") { - static constexpr const char *const input{"We%20are%20happy."}, *const result{"20are%20happy.We%"}; - static constexpr const auto n{3}; - CHECK_THAT(result, Equals(leetcode_so_58::reverseLeftWords(input, n))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_SO_58_TEST_HPP diff --git a/algorithm/string_search/CMakeLists.txt b/algorithm/string_search/CMakeLists.txt index 3a4cca87..655f38d2 100644 --- a/algorithm/string_search/CMakeLists.txt +++ b/algorithm/string_search/CMakeLists.txt @@ -12,9 +12,9 @@ foreach (elementName IN LISTS dependencies) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_${elementName}_test ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) - target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE CS203_DSAA_TEST_MACRO) + target_compile_definitions(${PROJECT_NAME}_${elementName}_test PRIVATE ALGORITHM_TEST_MACRO) target_link_libraries(${PROJECT_NAME}_${elementName}_test PRIVATE - ${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) + ${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}_test) set(CMAKE_CXX_STANDARD 11) @@ -26,9 +26,10 @@ set(dependencies 28) LIST(TRANSFORM dependencies PREPEND leetcode_) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE ${PROJECT_NAME}_kmp) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE ${PROJECT_NAME}_kmp) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) unset(elementName) endforeach () diff --git a/algorithm/string_search/kmp.cpp b/algorithm/string_search/kmp.cpp index a17aef8d..9b99b562 100644 --- a/algorithm/string_search/kmp.cpp +++ b/algorithm/string_search/kmp.cpp @@ -1,16 +1,6 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanos - * @Date: 2021-04-02 09:50:56 - * @LastEditors: nanos - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2021-2025 nanoseeds -Copyright (C) 2021-2023 nanos - -*/ #include "kmp.hpp" namespace string_search { diff --git a/algorithm/string_search/kmp.hpp b/algorithm/string_search/kmp.hpp index 7218b4f8..4b7a5396 100644 --- a/algorithm/string_search/kmp.hpp +++ b/algorithm/string_search/kmp.hpp @@ -1,18 +1,8 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanos - * @Date: 2021-04-02 10:12:44 - * @LastEditors: nanos - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2021-2025 nanoseeds -Copyright (C) 2021-2023 nanos - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_SEARCH_KMP_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_SEARCH_KMP_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_SEARCH_KMP_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_SEARCH_KMP_HPP #include #include @@ -23,4 +13,4 @@ using std::string; int strStr(const std::string &h, const std::string &n); } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_SEARCH_KMP_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_SEARCH_KMP_HPP diff --git a/algorithm/string_search/kmp_test.cpp b/algorithm/string_search/kmp_test.cpp index 930fee25..a904071f 100644 --- a/algorithm/string_search/kmp_test.cpp +++ b/algorithm/string_search/kmp_test.cpp @@ -1,16 +1,6 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanos - * @Date: 2021-04-02 10:12:44 - * @LastEditors: nanos - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2021-2025 nanoseeds -Copyright (C) 2021-2023 nanos - -*/ #include #include "kmp.hpp" diff --git a/algorithm/string_search/leetcode_28.cpp b/algorithm/string_search/leetcode_28.cpp index 6f9bf05d..a41f2519 100644 --- a/algorithm/string_search/leetcode_28.cpp +++ b/algorithm/string_search/leetcode_28.cpp @@ -1,15 +1,23 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +#include -Copyright (C) 2020-2023 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -*/ -#include "leetcode_28_test.hpp" #include "kmp.hpp" namespace leetcode_28 { -int32_t leetcode_28::strStr(const string &haystack, const string &needle) { - return string_search::strStr(haystack, needle); -} +using std::string; +#endif + +class Solution { +public: + int32_t strStr(const string &haystack, const string &needle) { + return string_search::strStr(haystack, needle); + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/string_search/leetcode_28_test.cpp b/algorithm/string_search/leetcode_28_test.cpp new file mode 100644 index 00000000..181e1884 --- /dev/null +++ b/algorithm/string_search/leetcode_28_test.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag string +//@Tag 字符串 +//@Tag 烤馍片 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_28_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_28_TEST_HPP + +#include +#include +#include "leetcode_28.cpp" + +namespace leetcode_28 { +using std::string; + +using Catch::Matchers::UnorderedEquals; + +TEST_CASE("1 [test_28]", "[test_28]") { + Solution solution; + CHECK(solution.strStr("hello", "ll") == 2); + CHECK(solution.strStr("aaaaa", "bba") == -1); + CHECK(solution.strStr("aaaaa", "") == 0); + CHECK(solution.strStr("a", "a") == 0); + CHECK(solution.strStr("mississippi", "issi") == 1); + CHECK(solution.strStr("mississippi", "issip") == 4); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_28_TEST_HPP diff --git a/algorithm/string_search/leetcode_28_test.hpp b/algorithm/string_search/leetcode_28_test.hpp deleted file mode 100644 index 1dd9cf6c..00000000 --- a/algorithm/string_search/leetcode_28_test.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag string -//@Tag 字符串 -//@Tag 烤馍片 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_28_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_28_TEST_HPP - -#include -#include - -namespace leetcode_28 { -using std::string; - -struct leetcode_28 { - static int32_t strStr(const string &haystack, const string &needle); -}; - -using Catch::Matchers::UnorderedEquals; - -TEST_CASE("1 [test_28]", "[test_28]") { - CHECK(leetcode_28::strStr("hello", "ll") == 2); - CHECK(leetcode_28::strStr("aaaaa", "bba") == -1); - CHECK(leetcode_28::strStr("aaaaa", "") == 0); - CHECK(leetcode_28::strStr("a", "a") == 0); - CHECK(leetcode_28::strStr("mississippi", "issi") == 1); - CHECK(leetcode_28::strStr("mississippi", "issip") == 4); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_28_TEST_HPP diff --git a/algorithm/tree/CMakeLists.txt b/algorithm/tree/CMakeLists.txt index 7612cc9d..c2296ea3 100644 --- a/algorithm/tree/CMakeLists.txt +++ b/algorithm/tree/CMakeLists.txt @@ -5,7 +5,7 @@ set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") enable_testing() -set(dependencies traverse_test huffman_test) +set(dependencies traverse huffman) set(leetcode_order 94 95 96 98 100) LIST(APPEND leetcode_order 104 226 530 559 589) @@ -13,7 +13,7 @@ LIST(APPEND leetcode_order 590 617 654 669 700) LIST(APPEND leetcode_order 701 144 145 102 101) LIST(APPEND leetcode_order 112 235 653 so_32 so_26) LIST(APPEND leetcode_order 113 426 so_54 114 230) -LIST(APPEND leetcode_order 236 543 199 814 872) +LIST(APPEND leetcode_order unknown 543 199 814 872) LIST(APPEND leetcode_order 894 897 938 965 993) LIST(APPEND leetcode_order 1008 1022 1038 1104 1261) LIST(APPEND leetcode_order 1302 1315 1325 1367 1372) @@ -25,10 +25,10 @@ unset(leetcode_order) foreach (elementName IN LISTS dependencies) add_executable(${PROJECT_NAME}_${elementName} - ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName} - CS203_DSAA_template_INCLUDE) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) endforeach () unset(dependencies) diff --git a/algorithm/tree/RBTree/CMakeLists.txt b/algorithm/tree/RBTree/CMakeLists.txt index f08c64bf..52faac98 100644 --- a/algorithm/tree/RBTree/CMakeLists.txt +++ b/algorithm/tree/RBTree/CMakeLists.txt @@ -7,6 +7,6 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/RBTest.cpp) -target_link_libraries(${PROJECT_NAME} CS203_DSAA_template_INCLUDE) +target_link_libraries(${PROJECT_NAME} algorithm_template_INCLUDE) #add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}) diff --git a/algorithm/tree/RBTree/RBTNode.hpp b/algorithm/tree/RBTree/RBTNode.hpp index 0a596115..ce8947b9 100644 --- a/algorithm/tree/RBTree/RBTNode.hpp +++ b/algorithm/tree/RBTree/RBTNode.hpp @@ -1,12 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTNODE_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTNODE_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTNODE_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTNODE_HPP #include @@ -112,4 +107,4 @@ class RBTNode : public TreeNodeTemp { }; } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTNODE_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTNODE_HPP diff --git a/algorithm/tree/RBTree/RBTest.cpp b/algorithm/tree/RBTree/RBTest.cpp index 06d98d4e..2237bd3b 100644 --- a/algorithm/tree/RBTree/RBTest.cpp +++ b/algorithm/tree/RBTree/RBTest.cpp @@ -1,16 +1,10 @@ /** - * @Github: https://github.com/Certseeds/CS203_DSAA_template * @Author: nanoseeds * @Date: 2020-08-06 22:42:27 * @LastEditors: nanoseeds */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include diff --git a/algorithm/tree/RBTree/RBTree.hpp b/algorithm/tree/RBTree/RBTree.hpp index b5ccea68..d9ae40e2 100644 --- a/algorithm/tree/RBTree/RBTree.hpp +++ b/algorithm/tree/RBTree/RBTree.hpp @@ -1,18 +1,12 @@ /** - * @Github: https://github.com/Certseeds/CS203_DSAA_template * @Author: nanoseeds * @Date: 2020-08-06 22:41:41 * @LastEditors: nanoseeds */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTREE_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTREE_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTREE_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTREE_HPP #include "RBTNode.hpp" #include @@ -597,4 +591,4 @@ bool RBTree::find(T key) const { } } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTREE_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_RBTREE_RBTREE_HPP diff --git a/algorithm/tree/avl/CMakeLists.txt b/algorithm/tree/avl/CMakeLists.txt index 3d3c1315..bb23d3fd 100644 --- a/algorithm/tree/avl/CMakeLists.txt +++ b/algorithm/tree/avl/CMakeLists.txt @@ -8,6 +8,6 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/avl.cpp) target_link_libraries(${PROJECT_NAME} - CS203_DSAA_template_INCLUDE) + algorithm_template_INCLUDE) #add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}) diff --git a/algorithm/tree/avl/avl_node.hpp b/algorithm/tree/avl/avl_node.hpp index 8e67427c..3c08e68e 100644 --- a/algorithm/tree/avl/avl_node.hpp +++ b/algorithm/tree/avl/avl_node.hpp @@ -1,5 +1,5 @@ -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_AVL_AVL_NODE_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_AVL_AVL_NODE_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_AVL_AVL_NODE_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_AVL_AVL_NODE_HPP #include @@ -24,4 +24,4 @@ struct TreeNode : public TreeNodeTemp { } }; } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_AVL_AVL_NODE_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_AVL_AVL_NODE_HPP diff --git a/algorithm/tree/huffman.cpp b/algorithm/tree/huffman.cpp index da35125e..7b342c75 100644 --- a/algorithm/tree/huffman.cpp +++ b/algorithm/tree/huffman.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include #include diff --git a/algorithm/tree/huffman_test.cpp b/algorithm/tree/huffman_test.cpp index 696dfc2c..544ec515 100644 --- a/algorithm/tree/huffman_test.cpp +++ b/algorithm/tree/huffman_test.cpp @@ -1,14 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_HUFFMAN_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_HUFFMAN_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_HUFFMAN_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_HUFFMAN_TEST_HPP #include #include "huffman.cpp" @@ -34,4 +29,4 @@ TEST_CASE("test_case 3 [test_tree_huffman]", "[test_tree_huffman]") { CHECK(str == hn.decal(hn.cal(str))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_HUFFMAN_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_HUFFMAN_TEST_HPP diff --git a/algorithm/tree/leetcode_100.cpp b/algorithm/tree/leetcode_100.cpp index 9d2db88b..2e8936d7 100644 --- a/algorithm/tree/leetcode_100.cpp +++ b/algorithm/tree/leetcode_100.cpp @@ -1,21 +1,29 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_100_test.hpp" +#include +#ifdef ALGORITHM_TEST_MACRO +#include namespace leetcode_100 { +using TreeNode = TREE_NODE::TreeNode; + +#endif + -bool leetcode_100::isSameTree(TreeNode *p, TreeNode *q) { - if (p == q) { - return true; - } else if (p == nullptr || q == nullptr) { - return false; +class Solution { +public: + bool isSameTree(TreeNode *p, TreeNode *q) { + if (p == q) { + return true; + } else if (p == nullptr || q == nullptr) { + return false; + } + return p->val == q->val && + isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } - return p->val == q->val && - isSameTree(p->left, q->left) && isSameTree(p->right, q->right); -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_1008.cpp b/algorithm/tree/leetcode_1008.cpp index 1a6cd01e..ba5a8978 100644 --- a/algorithm/tree/leetcode_1008.cpp +++ b/algorithm/tree/leetcode_1008.cpp @@ -1,65 +1,76 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_1008_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include + +#include namespace leetcode_1008 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif +using std::vector; -// find fst > value in vec[left,right] -int32_t binary_search(const vector &vec, size_t left, size_t right, int32_t value) { - if (left > right) { - return 0; - } else if (left == right) { - return right; - } else if (left + 1 == right) { - return right; - }// 一定存在,所以上面这俩能直接判定 - while (left <= right) { - if (const size_t middle = (right - left) / 2 + left; - vec[middle] > value && vec[middle - 1] < value) { - return middle; - } else if (vec[middle] > value) { - right = middle; - } else { - left = middle + 1; +class Solution { +private: + // find fst > value in vec[left,right] + int32_t binary_search(const vector &vec, size_t left, size_t right, int32_t value) { + if (left > right) { + return 0; + } else if (left == right) { + return right; + } else if (left + 1 == right) { + return right; + }// 一定存在,所以上面这俩能直接判定 + while (left <= right) { + if (const size_t middle = (right - left) / 2 + left; + vec[middle] > value && vec[middle - 1] < value) { + return middle; + } else if (vec[middle] > value) { + right = middle; + } else { + left = middle + 1; + } } + return 0; } - return 0; -} -TreeNode *rec(const vector &preorder, int32_t left, int32_t right) { - if (left > right) { - return nullptr; - } else if (left == right) { - return new TreeNode{preorder[right]}; - } - TreeNode *const root = new TreeNode{preorder[left]}; - const int32_t leftPlus = ++left; - if (preorder[leftPlus] > root->val) { - root->right = rec(preorder, leftPlus, right); - return root; - } else if (preorder[right] < root->val) { - root->left = rec(preorder, leftPlus, right); - return root; - } - // there vec[leftPlus] < root->val < vec[right] - const auto bigger = binary_search(preorder, leftPlus, right, root->val); - if (bigger == 0) { + TreeNode *rec(const vector &preorder, int32_t left, int32_t right) { + if (left > right) { + return nullptr; + } else if (left == right) { + return new TreeNode{preorder[right]}; + } + TreeNode *const root = new TreeNode{preorder[left]}; + const int32_t leftPlus = ++left; + if (preorder[leftPlus] > root->val) { + root->right = rec(preorder, leftPlus, right); + return root; + } else if (preorder[right] < root->val) { + root->left = rec(preorder, leftPlus, right); + return root; + } + // there vec[leftPlus] < root->val < vec[right] + const auto bigger = binary_search(preorder, leftPlus, right, root->val); + if (bigger == 0) { + return root; + } + root->left = rec(preorder, leftPlus, bigger - 1); + root->right = rec(preorder, bigger, right); return root; } - root->left = rec(preorder, leftPlus, bigger - 1); - root->right = rec(preorder, bigger, right); - return root; -} - -TreeNode *leetcode_1008::bstFromPreorder(const vector &preorder) { - const auto sizes{preorder.size() - 1}; - return rec(preorder, 0, sizes); -} +public: + TreeNode *bstFromPreorder(const vector &preorder) { + const auto sizes{preorder.size() - 1}; + return rec(preorder, 0, sizes); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/tree/leetcode_1008_test.hpp b/algorithm/tree/leetcode_1008_test.cpp similarity index 73% rename from algorithm/tree/leetcode_1008_test.hpp rename to algorithm/tree/leetcode_1008_test.cpp index e8085b68..c56ff646 100644 --- a/algorithm/tree/leetcode_1008_test.hpp +++ b/algorithm/tree/leetcode_1008_test.cpp @@ -1,31 +1,26 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1008_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1008_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1008_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1008_TEST_HPP #include #include #include +#include #include #include +#include "leetcode_1008.cpp" namespace leetcode_1008 { -using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_1008 final { - static TreeNode *bstFromPreorder(const vector &preorder); -}; using TreeNodeLink = TREE_NODE::TreeNodeLink; +using TreeNode = TREE_NODE::TreeNode; +using std::vector; TEST_CASE("test_case 4 [test_1008]", "[test_1008]") { + Solution solution; const vector input{1, 2, 3}; const vector result{ 1, @@ -33,12 +28,13 @@ TEST_CASE("test_case 4 [test_1008]", "[test_1008]") { TreeNode::No, 3, TreeNode::No, TreeNode::No }; - TreeNode *const pointer = leetcode_1008::bstFromPreorder(input); + TreeNode *const pointer = solution.bstFromPreorder(input); const TreeNodeLink treeNodeLink{pointer}; CHECK(TREE_NODE::judge_equal(pointer, result)); } TEST_CASE("test_case 1 [test_1008]", "[test_1008]") { + Solution solution; const vector input{8, 5, 1, 7, 10, 12}; const vector result{ 8, @@ -46,35 +42,38 @@ TEST_CASE("test_case 1 [test_1008]", "[test_1008]") { 1, 7, TreeNode::No, 12, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No }; - TreeNode *const pointer = leetcode_1008::bstFromPreorder(input); + TreeNode *const pointer = solution.bstFromPreorder(input); const TreeNodeLink treeNodeLink{pointer}; CHECK(TREE_NODE::judge_equal(pointer, result)); } TEST_CASE("test_case 2 [test_1008]", "[test_1008]") { + Solution solution; const vector input{1}; const vector result{ 1, TreeNode::No, TreeNode::No }; - TreeNode *const pointer = leetcode_1008::bstFromPreorder(input); + TreeNode *const pointer = solution.bstFromPreorder(input); const TreeNodeLink treeNodeLink{pointer}; CHECK(TREE_NODE::judge_equal(pointer, result)); } TEST_CASE("test_case 3 [test_1008]", "[test_1008]") { + Solution solution; const vector input{4, 2}; const vector result{ 4, 2, TreeNode::No, TreeNode::No, TreeNode::No }; - TreeNode *const pointer = leetcode_1008::bstFromPreorder(input); + TreeNode *const pointer = solution.bstFromPreorder(input); const TreeNodeLink treeNodeLink{pointer}; CHECK(TREE_NODE::judge_equal(pointer, result)); } TEST_CASE("test_case 5 [test_1008]", "[test_1008]") { + Solution solution; const vector input{15, 13, 12, 18}; const vector result{ 15, @@ -82,9 +81,9 @@ TEST_CASE("test_case 5 [test_1008]", "[test_1008]") { 12, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No }; - TreeNode *const pointer = leetcode_1008::bstFromPreorder(input); + TreeNode *const pointer = solution.bstFromPreorder(input); const TreeNodeLink treeNodeLink{pointer}; CHECK(TREE_NODE::judge_equal(pointer, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1008_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1008_TEST_HPP diff --git a/algorithm/tree/leetcode_100_test.hpp b/algorithm/tree/leetcode_100_test.cpp similarity index 58% rename from algorithm/tree/leetcode_100_test.hpp rename to algorithm/tree/leetcode_100_test.cpp index bbc98625..0c097f04 100644 --- a/algorithm/tree/leetcode_100_test.hpp +++ b/algorithm/tree/leetcode_100_test.cpp @@ -1,16 +1,12 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_100_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_100_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_100_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_100_TEST_HPP #include +#include "leetcode_100.cpp" #include #include #include @@ -21,26 +17,25 @@ using std::vector; using TreeNode = TREE_NODE::TreeNode; using TreeNodeLink = TREE_NODE::TreeNodeLink; -struct leetcode_100 { - static bool isSameTree(TreeNode *p, TreeNode *q); -}; - TEST_CASE("test_case 1 [test_100]", "[test_100]") { + Solution solution; const TreeNodeLink vec{1, 2}; const TreeNodeLink vec2{1, TreeNode::No, 2}; - CHECK_FALSE(leetcode_100::isSameTree(vec[0], vec2[0])); + CHECK_FALSE(solution.isSameTree(vec[0], vec2[0])); } TEST_CASE("test_case 2 [test_100]", "[test_100]") { + Solution solution; const TreeNodeLink vec{1, 2, 3}; const TreeNodeLink vec2{1, 2, 3}; - CHECK(leetcode_100::isSameTree(vec[0], vec2[0])); + CHECK(solution.isSameTree(vec[0], vec2[0])); } TEST_CASE("test_case 3 [test_100]", "[test_100]") { + Solution solution; const TreeNodeLink vec{1, 2, 1}; const TreeNodeLink vec2{1, 1, 2}; - CHECK_FALSE(leetcode_100::isSameTree(vec[0], vec2[0])); + CHECK_FALSE(solution.isSameTree(vec[0], vec2[0])); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_100_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_100_TEST_HPP diff --git a/algorithm/tree/leetcode_101.cpp b/algorithm/tree/leetcode_101.cpp index 97dfcd29..3b4cc8b6 100644 --- a/algorithm/tree/leetcode_101.cpp +++ b/algorithm/tree/leetcode_101.cpp @@ -1,28 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +namespace leetcode_101 { +using TreeNode = TREE_NODE::TreeNode; -Copyright (C) 2020-2023 nanoseeds +#endif -*/ -#include "leetcode_101_test.hpp" -namespace leetcode_101 { -bool isSym(TreeNode *left, TreeNode *right) { - if (left == nullptr && right == nullptr) { - return true; - } else if ((left == nullptr) != (right == nullptr)) { - return false; +class Solution { +private: + bool isSym(TreeNode *left, TreeNode *right) { + if (left == nullptr && right == nullptr) { + return true; + } else if ((left == nullptr) != (right == nullptr)) { + return false; + } + return left->val == right->val && isSym(left->left, right->right) && isSym(left->right, right->left); } - return left->val == right->val && isSym(left->left, right->right) && isSym(left->right, right->left); -} -bool leetcode_101::isSymmetric(TreeNode *root) { - if (root == nullptr) { - return true; +public: + bool isSymmetric(TreeNode *root) { + if (root == nullptr) { + return true; + } + return isSym(root->left, root->right); } - return isSym(root->left, root->right); -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_101_test.hpp b/algorithm/tree/leetcode_101_test.cpp similarity index 57% rename from algorithm/tree/leetcode_101_test.hpp rename to algorithm/tree/leetcode_101_test.cpp index 6355fb3c..bc218ced 100644 --- a/algorithm/tree/leetcode_101_test.hpp +++ b/algorithm/tree/leetcode_101_test.cpp @@ -1,48 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@Sword-Offer 28 //@Plan 数据结构入门 Day11 //@Plan 剑指OfferII-I Day07 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_101_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_101_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_101_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_101_TEST_HPP #include -#include -#include -#include +#include "leetcode_101.cpp" #include -#include namespace leetcode_101 { using std::vector; -using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_101 { - static bool isSymmetric(TreeNode *root); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; +using TreeNode = TREE_NODE::TreeNode; TEST_CASE("test_case 1 [test_101]", "[test_101]") { + Solution solution; const TreeNodeLink vec{1, 2, 2, 3, 4, 4, 3}; - CHECK(leetcode_101::isSymmetric(vec[0])); + CHECK(solution.isSymmetric(vec[0])); } TEST_CASE("test_case 2 [test_101]", "[test_101]") { + Solution solution; const TreeNodeLink vec{1, 2, 2, TreeNode::No, 3, TreeNode::No, 3}; - CHECK_FALSE(leetcode_101::isSymmetric(vec[0])); + CHECK_FALSE(solution.isSymmetric(vec[0])); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_101_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_101_TEST_HPP diff --git a/algorithm/tree/leetcode_102.cpp b/algorithm/tree/leetcode_102.cpp index 18aac457..84437dc5 100644 --- a/algorithm/tree/leetcode_102.cpp +++ b/algorithm/tree/leetcode_102.cpp @@ -1,37 +1,45 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_102_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include - +#include +#include +#include namespace leetcode_102 { + +using std::vector; +using TreeNode = TREE_NODE::TreeNode; using std::queue; +#endif -vector> leetcode_102::levelOrder(TreeNode *root) { - if (root == nullptr) { - return {}; - } - vector> will_return{}; - for (queue now{{root}}, next{}; !now.empty();) { - vector line{}; - while (!now.empty()) { - const auto *const head = now.front(); - now.pop(); - line.push_back(head->val); - if (head->left != nullptr) { - next.push(head->left); - } - if (head->right != nullptr) { - next.push(head->right); + +class Solution { +public: + vector> levelOrder(TreeNode *root) { + if (root == nullptr) { + return {}; + } + vector> will_return{}; + for (queue now{{root}}, next{}; !now.empty();) { + vector line{}; + while (!now.empty()) { + const auto *const head = now.front(); + now.pop(); + line.push_back(head->val); + if (head->left != nullptr) { + next.push(head->left); + } + if (head->right != nullptr) { + next.push(head->right); + } } + will_return.push_back(line); + std::swap(now, next); } - will_return.push_back(line); - std::swap(now, next); + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_1022.cpp b/algorithm/tree/leetcode_1022.cpp index 54d317fa..c0cb2a0e 100644 --- a/algorithm/tree/leetcode_1022.cpp +++ b/algorithm/tree/leetcode_1022.cpp @@ -1,35 +1,48 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_1022_test.hpp" + +#ifdef ALGORITHM_TEST_MACRO +#include +#include #include +#include namespace leetcode_1022 { +using std::vector; using std::stack; +using TreeNode = TREE_NODE::TreeNode; +#endif -int32_t leetcode_1022::sumRootToLeaf(TreeNode *root) { - int32_t willreturn{0}; - for (stack tree{{root}}; !tree.empty();) { - TreeNode *const begin = tree.top(); - tree.pop(); - if (begin->left == nullptr && begin->right == nullptr) { - willreturn += begin->val; - continue; - } - if (begin->left != nullptr) { - begin->left->val += begin->val << 1; - tree.push(begin->left); +#include + +class Solution { +public: + int32_t sumRootToLeaf(TreeNode *root) { + if (root == nullptr) { + return 0; } - if (begin->right != nullptr) { - begin->right->val += begin->val << 1; - tree.push(begin->right); + int32_t willreturn{0}; + for (stack tree{{root}}; !tree.empty();) { + TreeNode *const begin = tree.top(); + tree.pop(); + if (begin->left == nullptr && begin->right == nullptr) { + willreturn += begin->val; + continue; + } + if (begin->left != nullptr) { + begin->left->val += begin->val << 1; + tree.push(begin->left); + } + if (begin->right != nullptr) { + begin->right->val += begin->val << 1; + tree.push(begin->right); + } } + return willreturn; } - return willreturn; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_1022_test.hpp b/algorithm/tree/leetcode_1022_test.cpp similarity index 64% rename from algorithm/tree/leetcode_1022_test.hpp rename to algorithm/tree/leetcode_1022_test.cpp index 746885d8..381a5968 100644 --- a/algorithm/tree/leetcode_1022_test.hpp +++ b/algorithm/tree/leetcode_1022_test.cpp @@ -1,32 +1,24 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1022_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1022_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1022_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1022_TEST_HPP #include #include #include #include #include +#include "leetcode_1022.cpp" namespace leetcode_1022 { -using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_1022 final { - static int32_t sumRootToLeaf(TreeNode *root); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; +using TreeNode = TREE_NODE::TreeNode; TEST_CASE("test_case 2 [test_1022]", "[test_1022]") { + Solution solution; const TreeNodeLink input{ 1, 0, 1, @@ -35,17 +27,18 @@ TEST_CASE("test_case 2 [test_1022]", "[test_1022]") { TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No }; static constexpr const auto result{22}; - CHECK(result == leetcode_1022::sumRootToLeaf(input[0])); + CHECK(result == solution.sumRootToLeaf(input[0])); } TEST_CASE("test_case 1 [test_1022]", "[test_1022]") { + Solution solution; const TreeNodeLink input{ 0, TreeNode::No, TreeNode::No }; static constexpr const auto result{0}; - CHECK(result == leetcode_1022::sumRootToLeaf(input[0])); + CHECK(result == solution.sumRootToLeaf(input[0])); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1022_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1022_TEST_HPP diff --git a/algorithm/tree/leetcode_102_test.hpp b/algorithm/tree/leetcode_102_test.cpp similarity index 60% rename from algorithm/tree/leetcode_102_test.hpp rename to algorithm/tree/leetcode_102_test.cpp index 63e11f18..152b3df6 100644 --- a/algorithm/tree/leetcode_102_test.hpp +++ b/algorithm/tree/leetcode_102_test.cpp @@ -1,56 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@Sword-Offer 32-II //@Plan 数据结构入门 Day11 //@Plan 剑指OfferII-I Day06 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_102_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_102_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_102_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_102_TEST_HPP #include -#include -#include -#include +#include "leetcode_102.cpp" #include -#include namespace leetcode_102 { -using std::vector; -using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_102 { - static vector> levelOrder(TreeNode *root); -}; - using Catch::Matchers::Equals; using TreeNodeLink = TREE_NODE::TreeNodeLink; +using TreeNode = TREE_NODE::TreeNode; +using std::vector; TEST_CASE("test_case 1 [test_102]", "[test_102]") { + Solution solution; const TreeNodeLink vec{3, 9, 20, TreeNode::No, TreeNode::No, 15, 7}; const vector> result{{3}, {9, 20}, {15, 7}}; - CHECK_THAT(result, Equals(leetcode_102::levelOrder(vec[0]))); + CHECK_THAT(solution.levelOrder(vec[0]), Equals(result)); } TEST_CASE("test_case 2 [test_102]", "[test_102]") { + Solution solution; const TreeNodeLink vec{1}; const vector> result{{1},}; - CHECK_THAT(result, Equals(leetcode_102::levelOrder(vec[0]))); + CHECK_THAT(solution.levelOrder(vec[0]), Equals(result)); } TEST_CASE("test_case 3 [test_102]", "[test_102]") { + Solution solution; const vector> result{}; - CHECK_THAT(result, Equals(leetcode_102::levelOrder(nullptr))); + CHECK_THAT(solution.levelOrder(nullptr), Equals(result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_102_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_102_TEST_HPP diff --git a/algorithm/tree/leetcode_1038.cpp b/algorithm/tree/leetcode_1038.cpp index d27e0ee5..49749ab1 100644 --- a/algorithm/tree/leetcode_1038.cpp +++ b/algorithm/tree/leetcode_1038.cpp @@ -1,27 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_1038_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_1038 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -int32_t rec(TreeNode *const root, int32_t sum) { // 最小和数大概是反过来? - if (root == nullptr) { - return sum; +class Solution { +private: + int32_t rec(TreeNode *const root, int32_t sum) { // 最小和数大概是反过来? + if (root == nullptr) { + return sum; + } + const auto rightMax{rec(root->right, sum)}; + root->val += rightMax; + const auto leftMax{rec(root->left, root->val)}; + return leftMax; } - const auto rightMax{rec(root->right, sum)}; - root->val += rightMax; - const auto leftMax{rec(root->left, root->val)}; - return leftMax; -} - -TreeNode *leetcode_1038::bstToGst(TreeNode *root) { - rec(root, 0); - return root; -} +public: + TreeNode *bstToGst(TreeNode *root) { + rec(root, 0); + return root; + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/tree/leetcode_1038_test.hpp b/algorithm/tree/leetcode_1038_test.cpp similarity index 74% rename from algorithm/tree/leetcode_1038_test.hpp rename to algorithm/tree/leetcode_1038_test.cpp index d39a9444..99aced25 100644 --- a/algorithm/tree/leetcode_1038_test.hpp +++ b/algorithm/tree/leetcode_1038_test.cpp @@ -1,32 +1,27 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 //@Tag 更大和数 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1038_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1038_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1038_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1038_TEST_HPP #include #include #include +#include #include #include +#include "leetcode_1038.cpp" namespace leetcode_1038 { -using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_1038 final { - static TreeNode *bstToGst(TreeNode *root); -}; using TreeNodeLink = TREE_NODE::TreeNodeLink; +using TreeNode = TREE_NODE::TreeNode; +using std::vector; TEST_CASE("test_case 1 [test_1038]", "[test_1038]") { + Solution solution; const TreeNodeLink input{ 4, 1, 6, @@ -41,11 +36,12 @@ TEST_CASE("test_case 1 [test_1038]", "[test_1038]") { TreeNode::No, TreeNode::No, TreeNode::No, 33, TreeNode::No, TreeNode::No, TreeNode::No, 8, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No }; - const auto output = leetcode_1038::bstToGst(input[0]); + const auto output = solution.bstToGst(input[0]); CHECK(TREE_NODE::judge_equal(output, result)); } TEST_CASE("test_case 2 [test_1038]", "[test_1038]") { + Solution solution; const TreeNodeLink input{ 0, TreeNode::No, 1, TreeNode::No, TreeNode::No @@ -54,8 +50,8 @@ TEST_CASE("test_case 2 [test_1038]", "[test_1038]") { 1, TreeNode::No, 1, TreeNode::No, TreeNode::No }; - const auto output = leetcode_1038::bstToGst(input[0]); + const auto output = solution.bstToGst(input[0]); CHECK(TREE_NODE::judge_equal(output, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1038_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1038_TEST_HPP diff --git a/algorithm/tree/leetcode_104.cpp b/algorithm/tree/leetcode_104.cpp index 91b10f84..ea23bcb9 100644 --- a/algorithm/tree/leetcode_104.cpp +++ b/algorithm/tree/leetcode_104.cpp @@ -1,37 +1,45 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +namespace leetcode_104 { +using std::stack; +using TreeNode = TREE_NODE::TreeNode; -*/ -#include "leetcode_104_test.hpp" +#endif -namespace leetcode_104 { -int32_t leetcode_104::maxDepth(TreeNode *root) { - if (root == nullptr) { - return 0; - } - root->val = 1; - int32_t will_return{1}; - stack tree{{root}}; - while (!tree.empty()) { - const TreeNode *begin = tree.top(); - tree.pop(); - if (begin->left == nullptr && begin->right == nullptr) { - will_return = std::max(will_return, begin->val); - continue; +class Solution { +public: + int32_t maxDepth(TreeNode *root) { + if (root == nullptr) { + return 0; } - if (begin->left != nullptr) { - begin->left->val = begin->val + 1; - tree.push(begin->left); - } - if (begin->right != nullptr) { - begin->right->val = begin->val + 1; - tree.push(begin->right); + root->val = 1; + int32_t will_return{1}; + stack tree{{root}}; + while (!tree.empty()) { + const TreeNode *begin = tree.top(); + tree.pop(); + if (begin->left == nullptr && begin->right == nullptr) { + will_return = std::max(will_return, begin->val); + continue; + } + if (begin->left != nullptr) { + begin->left->val = begin->val + 1; + tree.push(begin->left); + } + if (begin->right != nullptr) { + begin->right->val = begin->val + 1; + tree.push(begin->right); + } } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_104_test.cpp b/algorithm/tree/leetcode_104_test.cpp new file mode 100644 index 00000000..2ad69c58 --- /dev/null +++ b/algorithm/tree/leetcode_104_test.cpp @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag tree +//@Tag 树 +//@Plan 数据结构入门 Day11 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_104_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_104_TEST_HPP + +#include +#include "leetcode_104.cpp" +#include + +namespace leetcode_104 { + +using TreeNodeLink = TREE_NODE::TreeNodeLink; +using TreeNode = TREE_NODE::TreeNode; + +TEST_CASE("test_case 1 [test_104]", "[test_104]") { + Solution solution; + const TreeNodeLink input{3, 9, 20, TreeNode::No, TreeNode::No, 15, 7}; + static constexpr const auto result{3}; + CHECK(result == solution.maxDepth(input[0])); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_104_TEST_HPP diff --git a/algorithm/tree/leetcode_104_test.hpp b/algorithm/tree/leetcode_104_test.hpp deleted file mode 100644 index 2dd8affd..00000000 --- a/algorithm/tree/leetcode_104_test.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag tree -//@Tag 树 -//@Plan 数据结构入门 Day11 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_104_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_104_TEST_HPP - -#include -#include -#include -#include -#include -#include - -namespace leetcode_104 { - -using std::stack; -using TreeNode = TREE_NODE::TreeNode; -using TreeNodeLink = TREE_NODE::TreeNodeLink; - -struct leetcode_104 { - static int32_t maxDepth(TreeNode *root); -}; - -TEST_CASE("test_case 1 [test_104]", "[test_104]") { - const TreeNodeLink input{3, 9, 20, TreeNode::No, TreeNode::No, 15, 7}; - static constexpr const auto result{3}; - CHECK(result == leetcode_104::maxDepth(input[0])); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_104_TEST_HPP diff --git a/algorithm/tree/leetcode_1104.cpp b/algorithm/tree/leetcode_1104.cpp index 2e31e617..d22899f1 100644 --- a/algorithm/tree/leetcode_1104.cpp +++ b/algorithm/tree/leetcode_1104.cpp @@ -1,48 +1,57 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_1104_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include namespace leetcode_1104 { +using std::vector; -vector leetcode_1104::pathInZigZagTree(int32_t label) { - // 第一步,先把在哪一行计算出来 - const auto input{label}; - const auto [level, number] = [input]() { - int32_t lev{0}, num{0}; - for (; num < input; ++lev) { - num += (1 << lev); - } - return std::make_tuple(lev, num); - }(); - // 拿到最后一行从0开始,从左向右数的序数 - const auto final_order = [](auto num_diff, auto lev) { - if (lev % 2 == 0) { - return (1 << lev) - num_diff - 1; - } else { - return num_diff; +#endif + + +class Solution { +public: + vector pathInZigZagTree(int32_t label) { + // 第一步,先把在哪一行计算出来 + const auto input{label}; + const auto [level, number] = [input]() { + int32_t lev{0}, num{0}; + for (; num < input; ++lev) { + num += (1 << lev); + } + return std::make_tuple(lev, num); + }(); + // 拿到最后一行从0开始,从左向右数的序数 + const auto final_order = [](auto num_diff, auto lev) { + if (lev % 2 == 0) { + return (1 << lev) - num_diff - 1; + } else { + return num_diff; + } + }(number - input, level - 1); + // 得到每一行自0开始,从左向右的序数(反向排列,一会儿需要用crbegin()) + vector each_level{}; + for (auto order_num{final_order}, lev{0}; lev < level; order_num /= 2, ++lev) { + each_level.push_back(order_num); } - }(number - input, level - 1); - // 得到每一行自0开始,从左向右的序数(反向排列,一会儿需要用crbegin()) - vector each_level{}; - for (auto order_num{final_order}, lev{0}; lev < level; order_num /= 2, ++lev) { - each_level.push_back(order_num); - } - // 一行一行的对应到数字 - vector will_return{}; - for (auto [lev, min, iter] {std::make_tuple(0, 1, each_level.crbegin())}; lev < level; ++lev, ++iter) { - if (lev % 2 == 0) { - will_return.push_back(min + *iter); - } else { - will_return.push_back(min - *iter + (1 << lev) - 1); + // 一行一行的对应到数字 + vector will_return{}; + for (auto [lev, min, iter] {std::make_tuple(0, 1, each_level.crbegin())}; lev < level; ++lev, ++iter) { + if (lev % 2 == 0) { + will_return.push_back(min + *iter); + } else { + will_return.push_back(min - *iter + (1 << lev) - 1); + } + min += (1 << lev); } - min += (1 << lev); + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_1104_test.cpp b/algorithm/tree/leetcode_1104_test.cpp new file mode 100644 index 00000000..95fadf19 --- /dev/null +++ b/algorithm/tree/leetcode_1104_test.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag tree +//@Tag 树 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1104_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1104_TEST_HPP + +#include +#include +#include +#include "leetcode_1104.cpp" + +namespace leetcode_1104 { + +using Catch::Matchers::Equals; +using std::vector; + +TEST_CASE("test_case 1 [test_1104]", "[test_1104]") { + Solution solution; + static constexpr const auto input{14}; + const vector output{1, 3, 4, 14}; + CHECK_THAT(solution.pathInZigZagTree(input), Equals(output)); +} + +TEST_CASE("test_case 2 [test_1104]", "[test_1104]") { + Solution solution; + static constexpr const auto input{26}; + const vector output{1, 2, 6, 10, 26}; + CHECK_THAT(solution.pathInZigZagTree(input), Equals(output)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1104_TEST_HPP diff --git a/algorithm/tree/leetcode_1104_test.hpp b/algorithm/tree/leetcode_1104_test.hpp deleted file mode 100644 index 2e9a14dd..00000000 --- a/algorithm/tree/leetcode_1104_test.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag tree -//@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1104_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1104_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_1104 { -using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_1104 final { - static vector pathInZigZagTree(int32_t label); -}; - -using TreeNodeLink = TREE_NODE::TreeNodeLink; -using Catch::Matchers::Equals; - -TEST_CASE("test_case 1 [test_1104]", "[test_1104]") { - static constexpr const auto input{14}; - const vector output{1, 3, 4, 14}; - CHECK_THAT(output, Equals(leetcode_1104::pathInZigZagTree(input))); -} - -TEST_CASE("test_case 2 [test_1104]", "[test_1104]") { - static constexpr const auto input{26}; - const vector output{1, 2, 6, 10, 26}; - CHECK_THAT(output, Equals(leetcode_1104::pathInZigZagTree(input))); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1104_TEST_HPP diff --git a/algorithm/tree/leetcode_112.cpp b/algorithm/tree/leetcode_112.cpp index 37dc16b3..6f6005f5 100644 --- a/algorithm/tree/leetcode_112.cpp +++ b/algorithm/tree/leetcode_112.cpp @@ -1,36 +1,45 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_112_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include #include +#include namespace leetcode_112 { +using std::vector; using std::queue; +using TreeNode = TREE_NODE::TreeNode; +#endif -bool leetcode_112::hasPathSum(TreeNode *root, int targetSum) { - if (root == nullptr) { - return false; - } - for (queue now{{root}}; !now.empty();) { - auto *head = now.front(); - now.pop(); - if (head->val == targetSum && head->left == nullptr && head->right == nullptr) { - return true; - } - if (head->left != nullptr) { - head->left->val += head->val; - now.push(head->left); +#include + +class Solution { +public: + bool hasPathSum(TreeNode *root, int targetSum) { + if (root == nullptr) { + return false; } - if (head->right != nullptr) { - head->right->val += head->val; - now.push(head->right); + for (queue now{{root}}; !now.empty();) { + auto *head = now.front(); + now.pop(); + if (head->val == targetSum && head->left == nullptr && head->right == nullptr) { + return true; + } + if (head->left != nullptr) { + head->left->val += head->val; + now.push(head->left); + } + if (head->right != nullptr) { + head->right->val += head->val; + now.push(head->right); + } } + return false; } - return false; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_112_test.hpp b/algorithm/tree/leetcode_112_test.cpp similarity index 65% rename from algorithm/tree/leetcode_112_test.hpp rename to algorithm/tree/leetcode_112_test.cpp index 3a352529..247e5a27 100644 --- a/algorithm/tree/leetcode_112_test.hpp +++ b/algorithm/tree/leetcode_112_test.cpp @@ -1,51 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@description 中序遍历 //@Plan 数据结构入门 Day12 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_112_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_112_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_112_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_112_TEST_HPP #include #include #include +#include #include #include -#include +#include "leetcode_112.cpp" namespace leetcode_112 { using std::vector; -using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_112 { - static bool hasPathSum(TreeNode *root, int targetSum); -}; - -using Catch::Matchers::Equals; using TreeNodeLink = TREE_NODE::TreeNodeLink; +using TreeNode = TREE_NODE::TreeNode; TEST_CASE("test_case 1 [test_112]", "[test_112]") { + Solution solution; const TreeNodeLink input{5, 4, 8, 11, TreeNode::No, 13, 4, 7, 2, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, 1 }; static constexpr const auto target{22}; - CHECK(leetcode_112::hasPathSum(input[0], target)); + CHECK(solution.hasPathSum(input[0], target)); } TEST_CASE("test_case 2 [test_112]", "[test_112]") { + Solution solution; const TreeNodeLink input{1, 2, 3}; static constexpr const auto target{5}; - CHECK_FALSE(leetcode_112::hasPathSum(input[0], target)); + CHECK_FALSE(solution.hasPathSum(input[0], target)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_112_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_112_TEST_HPP diff --git a/algorithm/tree/leetcode_113.cpp b/algorithm/tree/leetcode_113.cpp index 1dde3d1e..388571ed 100644 --- a/algorithm/tree/leetcode_113.cpp +++ b/algorithm/tree/leetcode_113.cpp @@ -1,44 +1,53 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_113_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include #include +#include namespace leetcode_113 { -using std::queue; +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -vector> leetcode_113::pathSum(TreeNode *root, int target) { - vector> sums; - if (root == nullptr) { - return sums; - } - for (queue>> now{{{root, {root->val}}}}; !now.empty();) { - const auto[head, vec] = now.front(); - now.pop(); - if (head->val == target && head->left == nullptr && head->right == nullptr) { - sums.push_back(vec); - continue; - } - if (head->left != nullptr) { - vector path{vec}; - path.push_back(head->left->val); - head->left->val += head->val; - now.emplace(head->left, path); +using std::queue; +using std::vector; + +class Solution { +public: + vector> pathSum(TreeNode *root, int target) { + vector> sums; + if (root == nullptr) { + return sums; } - if (head->right != nullptr) { - vector path{vec}; - path.push_back(head->right->val); - head->right->val += head->val; - now.emplace(head->right, path); + for (queue>> now{{{root, {root->val}}}}; !now.empty();) { + const auto[head, vec] = now.front(); + now.pop(); + if (head->val == target && head->left == nullptr && head->right == nullptr) { + sums.push_back(vec); + continue; + } + if (head->left != nullptr) { + vector path{vec}; + path.push_back(head->left->val); + head->left->val += head->val; + now.emplace(head->left, path); + } + if (head->right != nullptr) { + vector path{vec}; + path.push_back(head->right->val); + head->right->val += head->val; + now.emplace(head->right, path); + } } + return sums; } - return sums; -} - - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_113_test.hpp b/algorithm/tree/leetcode_113_test.cpp similarity index 70% rename from algorithm/tree/leetcode_113_test.hpp rename to algorithm/tree/leetcode_113_test.cpp index d74e2b1a..2b9b1860 100644 --- a/algorithm/tree/leetcode_113_test.hpp +++ b/algorithm/tree/leetcode_113_test.cpp @@ -1,37 +1,29 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@description 中序遍历 //@Plan 数据结构入门 Day12 //@Plan 剑指OfferII-I Day15 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_113_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_113_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_113_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_113_TEST_HPP #include #include #include +#include #include #include -#include +#include "leetcode_113.cpp" namespace leetcode_113 { using std::vector; using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_113 { - static vector> pathSum(TreeNode *root, int target); -}; - using Catch::Matchers::Equals; using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_113]", "[test_113]") { + Solution solution; const TreeNodeLink input{5, 4, 8, 11, TreeNode::No, 13, 4, @@ -40,23 +32,25 @@ TEST_CASE("test_case 1 [test_113]", "[test_113]") { static constexpr const auto target{22}; const vector> output{{5, 4, 11, 2}, {5, 8, 4, 5}}; - CHECK_THAT(output, Equals(leetcode_113::pathSum(input[0], target))); + CHECK_THAT(output, Equals(solution.pathSum(input[0], target))); } TEST_CASE("test_case 2 [test_113]", "[test_113]") { + Solution solution; const TreeNodeLink input{1, 2, 3}; static constexpr const auto target{5}; const vector> output{}; - CHECK_THAT(output, Equals(leetcode_113::pathSum(input[0], target))); + CHECK_THAT(output, Equals(solution.pathSum(input[0], target))); } TEST_CASE("test_case 3 [test_113]", "[test_113]") { + Solution solution; const TreeNodeLink input{1, 2}; static constexpr const auto target{0}; const vector> output{}; - CHECK_THAT(output, Equals(leetcode_113::pathSum(input[0], target))); + CHECK_THAT(output, Equals(solution.pathSum(input[0], target))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_113_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_113_TEST_HPP diff --git a/algorithm/tree/leetcode_114.cpp b/algorithm/tree/leetcode_114.cpp index d810f849..aa1aca87 100644 --- a/algorithm/tree/leetcode_114.cpp +++ b/algorithm/tree/leetcode_114.cpp @@ -1,35 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_114_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include #include +#include namespace leetcode_114 { +using std::vector; using std::stack; +using TreeNode = TREE_NODE::TreeNode; +#endif -void leetcode_114::flatten(TreeNode *root) { - if (root == nullptr) { - return; - } - TreeNode base{-1}; - TreeNode *last = &base; - for (stack sta{{root}}; !sta.empty();) { - TreeNode *const head = sta.top(); - sta.pop(); - if (head->right != nullptr) { - sta.push(head->right); +class Solution { +public: + void flatten(TreeNode *root) { + if (root == nullptr) { + return; } - if (head->left != nullptr) { - sta.push(head->left); + TreeNode base{-1}; + TreeNode *last = &base; + for (stack sta{{root}}; !sta.empty();) { + TreeNode *const head = sta.top(); + sta.pop(); + if (head->right != nullptr) { + sta.push(head->right); + } + if (head->left != nullptr) { + sta.push(head->left); + } + last->right = head; + last->left = nullptr; + last = head; } - last->right = head; - last->left = nullptr; - last = head; } +}; +#ifdef ALGORITHM_TEST_MACRO } - -} +#endif diff --git a/algorithm/tree/leetcode_114_test.hpp b/algorithm/tree/leetcode_114_test.cpp similarity index 72% rename from algorithm/tree/leetcode_114_test.hpp rename to algorithm/tree/leetcode_114_test.cpp index 93bdc3cb..89144d79 100644 --- a/algorithm/tree/leetcode_114_test.hpp +++ b/algorithm/tree/leetcode_114_test.cpp @@ -1,40 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@description 先序遍历 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_114_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_114_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_114_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_114_TEST_HPP #include #include #include +#include #include #include -#include +#include "leetcode_114.cpp" namespace leetcode_114 { using std::vector; using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_114 { - static void flatten(TreeNode *root); -}; - using Catch::Matchers::Equals; using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_114]", "[test_114]") { + Solution solution; const TreeNodeLink input{1, 2, 5, 3, 4, TreeNode::No, 6 }; - leetcode_114::flatten(input[0]); + solution.flatten(input[0]); CHECK(1 == input[0]->val); CHECK(2 == input[0]->right->val); CHECK(3 == input[0]->right->right->val); @@ -44,15 +36,17 @@ TEST_CASE("test_case 1 [test_114]", "[test_114]") { } TEST_CASE("test_case 2 [test_114]", "[test_114]") { - leetcode_114::flatten(nullptr); + Solution solution; + solution.flatten(nullptr); } TEST_CASE("test_case 3 [test_114]", "[test_114]") { + Solution solution; const TreeNodeLink input{0}; - leetcode_114::flatten(input[0]); + solution.flatten(input[0]); CHECK(0 == input[0]->val); CHECK(nullptr == input[0]->right); CHECK(nullptr == input[0]->left); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_114_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_114_TEST_HPP diff --git a/algorithm/tree/leetcode_1261.cpp b/algorithm/tree/leetcode_1261.cpp index 8de80917..53e63fe2 100644 --- a/algorithm/tree/leetcode_1261.cpp +++ b/algorithm/tree/leetcode_1261.cpp @@ -1,21 +1,24 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_1261_test.hpp" +#ifdef ALGORITHM_TEST_MACRO #include +#include +#include namespace leetcode_1261 { -class tree : public findElements { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif + +class FindElements { private: TreeNode *const root; public: - explicit tree(TreeNode *root_) : root(root_) { + explicit FindElements(TreeNode *root_) : root(root_) { TreeNode *node = root; + if (node == nullptr) return; node->val = 0; for (std::stack sta{{node}}; !sta.empty();) { TreeNode *const top = sta.top(); @@ -33,8 +36,11 @@ class tree : public findElements { } } - [[nodiscard]] bool find(int32_t target) const override { + [[nodiscard]] bool find(int32_t target) { std::stack sta; + if (target == 0) { + return root != nullptr; + } for (int32_t temp{target}; temp != 0;) { if (temp % 2 == 0) { sta.push(1); // means right @@ -46,7 +52,7 @@ class tree : public findElements { } // 15: (1,7),(1,3),(1,1),(1,0) // 30: (0,14),(0,6),(0,2),(0,0) - const TreeNode *base{root}; + TreeNode *base{root}; while (!sta.empty()) { const auto v = sta.top(); sta.pop(); @@ -62,10 +68,6 @@ class tree : public findElements { return (base != nullptr); } }; - - -std::unique_ptr init(TreeNode *root) { - return std::make_unique(root); -} - +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_1261_test.hpp b/algorithm/tree/leetcode_1261_test.cpp similarity index 50% rename from algorithm/tree/leetcode_1261_test.hpp rename to algorithm/tree/leetcode_1261_test.cpp index 14158c22..1cfd7404 100644 --- a/algorithm/tree/leetcode_1261_test.hpp +++ b/algorithm/tree/leetcode_1261_test.cpp @@ -1,36 +1,22 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1261_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1261_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1261_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1261_TEST_HPP #include #include #include #include #include -#include +#include "leetcode_1261.cpp" namespace leetcode_1261 { using TreeNode = TREE_NODE::TreeNode; constexpr const auto junk{-1}; -class findElements { -public: - [[nodiscard]] virtual bool find(int target) const = 0; - - virtual ~findElements() = default; -}; - -std::unique_ptr init(TreeNode *root); - using TreeNodeLink = TREE_NODE::TreeNodeLink; using Catch::Matchers::Equals; @@ -40,12 +26,12 @@ TEST_CASE("test_case 1 [test_1261]", "[test_1261]") { TreeNode::No, junk, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, }; - const auto tree{init(input[0])}; - CHECK(tree->find(0)); - CHECK_FALSE(tree->find(1)); - CHECK(tree->find(2)); - CHECK_FALSE(tree->find(3)); - CHECK_FALSE(tree->find(4)); + FindElements tree(input[0]); + CHECK(tree.find(0)); + CHECK_FALSE(tree.find(1)); + CHECK(tree.find(2)); + CHECK_FALSE(tree.find(3)); + CHECK_FALSE(tree.find(4)); } TEST_CASE("test_case 2 [test_1261]", "[test_1261]") { @@ -56,16 +42,16 @@ TEST_CASE("test_case 2 [test_1261]", "[test_1261]") { TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, }; - const auto tree{init(input[0])}; - CHECK(tree->find(0)); - CHECK(tree->find(1)); - CHECK(tree->find(2)); - CHECK(tree->find(3)); - CHECK(tree->find(4)); - CHECK_FALSE(tree->find(5)); - CHECK_FALSE(tree->find(6)); - CHECK_FALSE(tree->find(7)); + FindElements tree(input[0]); + CHECK(tree.find(0)); + CHECK(tree.find(1)); + CHECK(tree.find(2)); + CHECK(tree.find(3)); + CHECK(tree.find(4)); + CHECK_FALSE(tree.find(5)); + CHECK_FALSE(tree.find(6)); + CHECK_FALSE(tree.find(7)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1261_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1261_TEST_HPP diff --git a/algorithm/tree/leetcode_1302.cpp b/algorithm/tree/leetcode_1302.cpp index 78a58138..b43ef4f3 100644 --- a/algorithm/tree/leetcode_1302.cpp +++ b/algorithm/tree/leetcode_1302.cpp @@ -1,54 +1,62 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_1302_test.hpp" +#ifdef ALGORITHM_TEST_MACRO #include +#include +#include +#include +#include +#include namespace leetcode_1302 { - -void visit(const TreeNode *const root, vector &nums, int32_t depth) { - if (root == nullptr) { - return; - } - const auto length{nums.size()}; - if (length <= depth) { - nums.push_back(0); - } - nums[depth] += root->val; - visit(root->left, nums, depth + 1); - visit(root->right, nums, depth + 1); -} - -int32_t leetcode_1302::deepestLeavesSumRec(TreeNode *root) { - vector nums{}; - visit(root, nums, 0); - return nums.back(); -} - -int32_t leetcode_1302::deepestLeavesSumIter(TreeNode *root) { - int32_t willReturn{0}, height{0}; - for (std::stack> que{{std::make_tuple(root, 0)}};!que.empty();) { - const auto [node, depth] = que.top(); - que.pop(); - if (node == nullptr) { - continue; +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif + +class Solution { +private: + void visit(const TreeNode *const root, vector &nums, int32_t depth) { + if (root == nullptr) { + return; } - if (height == depth) { - willReturn += node->val; - } else if (height < depth) { - willReturn = node->val; - height = depth; + const auto length{nums.size()}; + if (length <= depth) { + nums.push_back(0); } - que.push(std::make_tuple(node->left, depth + 1)); - que.push(std::make_tuple(node->right, depth + 1)); + nums[depth] += root->val; + visit(root->left, nums, depth + 1); + visit(root->right, nums, depth + 1); } - return willReturn; -} +public: + int32_t deepestLeavesSumRec(TreeNode *root) { + vector nums{}; + visit(root, nums, 0); + return nums.back(); + } + int32_t deepestLeavesSumIter(TreeNode *root) { + int32_t willReturn{0}, height{0}; + for (std::stack> que{{std::make_tuple(root, 0)}};!que.empty();) { + const auto [node, depth] = que.top(); + que.pop(); + if (node == nullptr) { + continue; + } + if (height == depth) { + willReturn += node->val; + } else if (height < depth) { + willReturn = node->val; + height = depth; + } + que.push(std::make_tuple(node->left, depth + 1)); + que.push(std::make_tuple(node->right, depth + 1)); + } + return willReturn; + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_1302_test.hpp b/algorithm/tree/leetcode_1302_test.cpp similarity index 63% rename from algorithm/tree/leetcode_1302_test.hpp rename to algorithm/tree/leetcode_1302_test.cpp index 819346cd..839b9002 100644 --- a/algorithm/tree/leetcode_1302_test.hpp +++ b/algorithm/tree/leetcode_1302_test.cpp @@ -1,34 +1,25 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1302_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1302_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1302_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1302_TEST_HPP #include #include #include +#include #include #include -#include +#include "leetcode_1302.cpp" namespace leetcode_1302 { using TreeNode = TREE_NODE::TreeNode; - -namespace leetcode_1302 { -int32_t deepestLeavesSumRec(TreeNode *root); -int32_t deepestLeavesSumIter(TreeNode *root); -} - using TreeNodeLink = TREE_NODE::TreeNodeLink; using Catch::Matchers::Equals; TEST_CASE("test_case 1 [test_1302]", "[test_1302]") { + Solution solution; const TreeNodeLink input{ 1, 1, 4, @@ -36,14 +27,15 @@ TEST_CASE("test_case 1 [test_1302]", "[test_1302]") { TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, 1, 9 }; const auto root{input[0]}; - const auto outputRec = leetcode_1302::deepestLeavesSumRec(root); - const auto outputIter = leetcode_1302::deepestLeavesSumRec(root); + const auto outputRec = solution.deepestLeavesSumRec(root); + const auto outputIter = solution.deepestLeavesSumIter(root); constexpr const auto result{10}; CHECK(outputRec == result); CHECK(outputIter == result); } TEST_CASE("test_cas 2 [test_1302]", "[test_1302]") { + Solution solution; const TreeNodeLink input{ 1, 1, 4, @@ -51,11 +43,11 @@ TEST_CASE("test_cas 2 [test_1302]", "[test_1302]") { 1, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, 9 }; const auto root{input[0]}; - const auto outputRec = leetcode_1302::deepestLeavesSumRec(root); - const auto outputIter = leetcode_1302::deepestLeavesSumIter(root); + const auto outputRec = solution.deepestLeavesSumRec(root); + const auto outputIter = solution.deepestLeavesSumIter(root); constexpr const auto result{10}; CHECK(outputRec == result); CHECK(outputIter == result); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1302_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1302_TEST_HPP diff --git a/algorithm/tree/leetcode_1315.cpp b/algorithm/tree/leetcode_1315.cpp index e3cb2baa..78e81c23 100644 --- a/algorithm/tree/leetcode_1315.cpp +++ b/algorithm/tree/leetcode_1315.cpp @@ -1,57 +1,64 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_1315_test.hpp" +#ifdef ALGORITHM_TEST_MACRO #include +#include +#include +#include +#include namespace leetcode_1315 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -int32_t visit(const TreeNode *const pp, const TreeNode *const p, const TreeNode *const node) { - if (node == nullptr) { - return 0; - } - int32_t will_return{0}; - if (pp->val % 2 == 0) { - will_return += node->val; - } - will_return += visit(p, node, node->left); - will_return += visit(p, node, node->right); - return will_return; -} - -int32_t leetcode_1315::sumEvenGrandparentRec(TreeNode *root) { - TreeNode ppNode{1}, pNode{1}; - ppNode.left = &pNode; - pNode.left = root; - const auto result = visit(&ppNode, &pNode, root); - return result; -} - -int32_t leetcode_1315::sumEvenGrandparentIter(TreeNode *root) { - TreeNode ppNode{1}, pNode{1}; - ppNode.left = &pNode; - pNode.left = root; - int32_t will_return{0}; - for (std::stack> sta{ - {std::make_tuple(&ppNode, &pNode, root)}}; !sta.empty();) { - const auto [pp, p, node] = sta.top(); - sta.pop(); +class Solution { +private: + int32_t visit(const TreeNode *const pp, const TreeNode *const p, const TreeNode *const node) { if (node == nullptr) { - continue; + return 0; } + int32_t will_return{0}; if (pp->val % 2 == 0) { will_return += node->val; } - sta.push(std::make_tuple(p, node, node->left)); - sta.push(std::make_tuple(p, node, node->right)); + will_return += visit(p, node, node->left); + will_return += visit(p, node, node->right); + return will_return; } - return will_return; -} +public: + int32_t sumEvenGrandparentRec(TreeNode *root) { + TreeNode ppNode{1}, pNode{1}; + ppNode.left = &pNode; + pNode.left = root; + const auto result = visit(&ppNode, &pNode, root); + return result; + } + int32_t sumEvenGrandparentIter(TreeNode *root) { + TreeNode ppNode{1}, pNode{1}; + ppNode.left = &pNode; + pNode.left = root; + int32_t will_return{0}; + for (std::stack> sta{ + {std::make_tuple(&ppNode, &pNode, root)}}; !sta.empty();) { + const auto [pp, p, node] = sta.top(); + sta.pop(); + if (node == nullptr) { + continue; + } + if (pp->val % 2 == 0) { + will_return += node->val; + } + sta.push(std::make_tuple(p, node, node->left)); + sta.push(std::make_tuple(p, node, node->right)); + } + return will_return; + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_1315_test.hpp b/algorithm/tree/leetcode_1315_test.cpp similarity index 63% rename from algorithm/tree/leetcode_1315_test.hpp rename to algorithm/tree/leetcode_1315_test.cpp index 17669e6f..c84165f3 100644 --- a/algorithm/tree/leetcode_1315_test.hpp +++ b/algorithm/tree/leetcode_1315_test.cpp @@ -1,34 +1,24 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1315_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1315_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1315_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1315_TEST_HPP #include #include #include #include #include +#include "leetcode_1315.cpp" namespace leetcode_1315 { using TreeNode = TREE_NODE::TreeNode; - -namespace leetcode_1315 { -int sumEvenGrandparentRec(TreeNode *root); - -int sumEvenGrandparentIter(TreeNode *root); -} - using TreeNodeLink = TREE_NODE::TreeNodeLink; using Catch::Matchers::Equals; TEST_CASE("test_case 1 [test_1315]", "[test_1315]") { + Solution solution; const TreeNodeLink input{ 1, 1, 4, @@ -36,14 +26,15 @@ TEST_CASE("test_case 1 [test_1315]", "[test_1315]") { TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, 1, 9 }; const auto root{input[0]}; - const auto outputRec = leetcode_1315::sumEvenGrandparentRec(root); - const auto outputIter = leetcode_1315::sumEvenGrandparentIter(root); + const auto outputRec = solution.sumEvenGrandparentRec(root); + const auto outputIter = solution.sumEvenGrandparentIter(root); constexpr const auto result{10}; CHECK(outputRec == result); CHECK(outputIter == result); } TEST_CASE("test_cas 2 [test_1315]", "[test_1315]") { + Solution solution; const TreeNodeLink input{ 1, 1, 4, @@ -51,11 +42,11 @@ TEST_CASE("test_cas 2 [test_1315]", "[test_1315]") { 1, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, 9 }; const auto root{input[0]}; - const auto outputRec = leetcode_1315::sumEvenGrandparentRec(root); - const auto outputIter = leetcode_1315::sumEvenGrandparentIter(root); + const auto outputRec = solution.sumEvenGrandparentRec(root); + const auto outputIter = solution.sumEvenGrandparentIter(root); constexpr const auto result{9}; CHECK(outputRec == result); CHECK(outputIter == result); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1315_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_1315_TEST_HPP diff --git a/algorithm/tree/leetcode_1325.cpp b/algorithm/tree/leetcode_1325.cpp index a6037099..6d4ad7ee 100644 --- a/algorithm/tree/leetcode_1325.cpp +++ b/algorithm/tree/leetcode_1325.cpp @@ -1,28 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_1325_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_1325 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -TreeNode *leetcode_1325::removeLeafNodesRec(TreeNode *root, int target) { - if (root == nullptr) { - return nullptr; - } - TreeNode *const left = removeLeafNodesRec(root->left, target); - TreeNode *const right = removeLeafNodesRec(root->right, target); - if (left == nullptr && right == nullptr) { - if (root->val == target) { +class Solution { +public: + TreeNode *removeLeafNodesRec(TreeNode *root, int target) { + if (root == nullptr) { return nullptr; } + TreeNode *const left = removeLeafNodesRec(root->left, target); + TreeNode *const right = removeLeafNodesRec(root->right, target); + if (left == nullptr && right == nullptr) { + if (root->val == target) { + return nullptr; + } + } + root->left = left; + root->right = right; + return root; } - root->left = left; - root->right = right; - return root; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_1325_test.hpp b/algorithm/tree/leetcode_1325_test.cpp similarity index 59% rename from algorithm/tree/leetcode_1325_test.hpp rename to algorithm/tree/leetcode_1325_test.cpp index e5a29b92..86601b3c 100644 --- a/algorithm/tree/leetcode_1325_test.hpp +++ b/algorithm/tree/leetcode_1325_test.cpp @@ -1,35 +1,24 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1325_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1325_TEST_HPP #include #include #include +#include #include #include +#include "leetcode_1325.cpp" namespace leetcode_1325 { using TreeNode = TREE_NODE::TreeNode; - -namespace leetcode_1325 { -TreeNode *removeLeafNodesRec(TreeNode *root, int32_t target); - - -TreeNode *removeLeafNodesIter(TreeNode *root, int32_t target); -} - using TreeNodeLink = TREE_NODE::TreeNodeLink; using Catch::Matchers::Equals; +using std::vector; TEST_CASE("test_case 1 [test_1325]", "[test_1325]") { + Solution solution; const TreeNodeLink input{ 1, 1, 4, @@ -38,16 +27,15 @@ TEST_CASE("test_case 1 [test_1325]", "[test_1325]") { }; const auto root{input[0]}; constexpr const auto target{1}; - const auto outputRec = leetcode_1325::removeLeafNodesRec(root, target); + const auto outputRec = solution.removeLeafNodesRec(root, target); const vector result{ 1, 1, 4, 5, TreeNode::No, TreeNode::No, 4, - TreeNode::No, TreeNode::No,/*TreeNode::No, TreeNode::No,TreeNode::No, TreeNode::No,*/ TreeNode::No, 9, + TreeNode::No, TreeNode::No, TreeNode::No, 9, TreeNode::No, TreeNode::No, }; CHECK(TREE_NODE::judge_equal(outputRec, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1325_TEST_HPP diff --git a/algorithm/tree/leetcode_1367.cpp b/algorithm/tree/leetcode_1367.cpp index 64b6e090..622d0be8 100644 --- a/algorithm/tree/leetcode_1367.cpp +++ b/algorithm/tree/leetcode_1367.cpp @@ -1,52 +1,59 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_1367_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include #include - +#include namespace leetcode_1367 { using std::queue; +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +using LISTNODE::ListNode; +#endif -bool isSubPathRec(ListNode *head, TreeNode *root) { - if (head == nullptr) { - return true; - } - if (root == nullptr) { - return false; - } - if (head->val != root->val) { - return false; - } - const auto left = isSubPathRec(head->next, root->left); - const auto right = isSubPathRec(head->next, root->right); - return left || right; -} - -bool leetcode_1367::isSubPath(ListNode *head, TreeNode *root) { - if (head == nullptr) { - return true; - } else if (root == nullptr) { - return false; - } - for (queue que{{root}}; !que.empty();) { - const auto leader = que.front(); - que.pop(); - if (leader->left != nullptr) { - que.push(leader->left); +class Solution { +private: + bool isSubPathRec(ListNode *head, TreeNode *root) { + if (head == nullptr) { + return true; } - if (leader->right != nullptr) { - que.push(leader->right); + if (root == nullptr) { + return false; } - if (isSubPathRec(head, leader)) { - return true; + if (head->val != root->val) { + return false; } + const auto left = isSubPathRec(head->next, root->left); + const auto right = isSubPathRec(head->next, root->right); + return left || right; } - return false; -} - +public: + bool isSubPath(ListNode *head, TreeNode *root) { + if (head == nullptr) { + return true; + } else if (root == nullptr) { + return false; + } + for (queue que{{root}}; !que.empty();) { + const auto leader = que.front(); + que.pop(); + if (leader->left != nullptr) { + que.push(leader->left); + } + if (leader->right != nullptr) { + que.push(leader->right); + } + if (isSubPathRec(head, leader)) { + return true; + } + } + return false; + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_1367_test.hpp b/algorithm/tree/leetcode_1367_test.cpp similarity index 74% rename from algorithm/tree/leetcode_1367_test.hpp rename to algorithm/tree/leetcode_1367_test.cpp index 68ac5b3c..f2c984ae 100644 --- a/algorithm/tree/leetcode_1367_test.hpp +++ b/algorithm/tree/leetcode_1367_test.cpp @@ -1,35 +1,24 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1367_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1367_TEST_HPP #include #include #include -#include -#include -#include -namespace leetcode_1367 { -using TreeNode = TREE_NODE::TreeNode; -using LISTNODE::ListNode; -using LISTNODE::ListNodeLink; + +#include +#include "leetcode_1367.cpp" namespace leetcode_1367 { -bool isSubPath(ListNode *head, TreeNode *root); -} +using LISTNODE::ListNodeLink; using TreeNodeLink = TREE_NODE::TreeNodeLink; using Catch::Matchers::Equals; TEST_CASE("test_case 1 [test_1367]", "[test_1367]") { + Solution solution; const ListNodeLink vec1{4, 2, 8}; const TreeNodeLink vec2{ 1, @@ -39,10 +28,11 @@ TEST_CASE("test_case 1 [test_1367]", "[test_1367]") { TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, \ TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, 1, 3 }; - CHECK(leetcode_1367::isSubPath(vec1[0], vec2[0])); + CHECK(solution.isSubPath(vec1[0], vec2[0])); } TEST_CASE("test_case 2 [test_1367]", "[test_1367]") { + Solution solution; const ListNodeLink vec1{1, 4, 2, 6}; const TreeNodeLink vec2{ 1, @@ -52,11 +42,12 @@ TEST_CASE("test_case 2 [test_1367]", "[test_1367]") { TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, \ TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, 1, 3 }; - CHECK(leetcode_1367::isSubPath(vec1[0], vec2[0])); + CHECK(solution.isSubPath(vec1[0], vec2[0])); } TEST_CASE("test_case 3 [test_1367]", "[test_1367]") { + Solution solution; const ListNodeLink vec1{1, 4, 2, 6, 8}; const TreeNodeLink vec2{ 1, @@ -66,7 +57,6 @@ TEST_CASE("test_case 3 [test_1367]", "[test_1367]") { TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, \ TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, 1, 3 }; - CHECK_FALSE(leetcode_1367::isSubPath(vec1[0], vec2[0])); + CHECK_FALSE(solution.isSubPath(vec1[0], vec2[0])); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1367_TEST_HPP diff --git a/algorithm/tree/leetcode_1372.cpp b/algorithm/tree/leetcode_1372.cpp index aff847d9..56fe8ca6 100644 --- a/algorithm/tree/leetcode_1372.cpp +++ b/algorithm/tree/leetcode_1372.cpp @@ -1,57 +1,62 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_1372_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include #include +#include +#include +#include namespace leetcode_1372 { +using std::vector; using std::queue; - -int32_t longestZigZagLeft(TreeNode *root); - -int32_t longestZigZagRight(TreeNode *root); - -int32_t longestZigZagLeft(TreeNode *root) { - if (root->right == nullptr) { - return 0; +using TreeNode = TREE_NODE::TreeNode; +#endif + +class Solution { +private: + int32_t longestZigZagLeft(TreeNode *root) { + if (root->right == nullptr) { + return 0; + } + return longestZigZagRight(root->right) + 1; } - return longestZigZagRight(root->right) + 1; -} -int32_t longestZigZagRight(TreeNode *root) { - if (root->left == nullptr) { - return 0; + int32_t longestZigZagRight(TreeNode *root) { + if (root->left == nullptr) { + return 0; + } + return longestZigZagLeft(root->left) + 1; } - return longestZigZagLeft(root->left) + 1; -} -int32_t leetcode_1372::longestZigZag(TreeNode *root) { - if (root == nullptr) { - return 0; - } - int32_t maximum{longestZigZagLeft(root)}; // so we can left the other special case. - for (queue> que{{{root, true}}}; !que.empty();) { - const auto [head, dire] {que.front()}; - que.pop(); - if (dire) { - const auto v = longestZigZagRight(head); - maximum = std::max(maximum, v); - } else { - const auto v = longestZigZagLeft(head); - maximum = std::max(maximum, v); +public: + int32_t longestZigZag(TreeNode *root) { + if (root == nullptr) { + return 0; } - if (head->left != nullptr) { - que.emplace(head->left, true); - } - if (head->right != nullptr) { - que.emplace(head->right, false); + int32_t maximum{longestZigZagLeft(root)}; // so we can left the other special case. + for (queue> que{{{root, true}}}; !que.empty();) { + const auto [head, dire] {que.front()}; + que.pop(); + if (dire) { + const auto v = longestZigZagRight(head); + maximum = std::max(maximum, v); + } else { + const auto v = longestZigZagLeft(head); + maximum = std::max(maximum, v); + } + if (head->left != nullptr) { + que.emplace(head->left, true); + } + if (head->right != nullptr) { + que.emplace(head->right, false); + } } + return maximum; } - return maximum; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_1372_test.hpp b/algorithm/tree/leetcode_1372_test.cpp similarity index 64% rename from algorithm/tree/leetcode_1372_test.hpp rename to algorithm/tree/leetcode_1372_test.cpp index b4850e3b..e9e18754 100644 --- a/algorithm/tree/leetcode_1372_test.hpp +++ b/algorithm/tree/leetcode_1372_test.cpp @@ -1,32 +1,21 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1372_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1372_TEST_HPP #include #include #include #include #include +#include "leetcode_1372.cpp" namespace leetcode_1372 { using TreeNode = TREE_NODE::TreeNode; - - -namespace leetcode_1372 { -int32_t longestZigZag(TreeNode *root); -} - using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_1372]", "[test_1372]") { + Solution solution; const TreeNodeLink vec2{ 1, TreeNode::No, 1, @@ -36,13 +25,13 @@ TEST_CASE("test_case 1 [test_1372]", "[test_1372]") { TreeNode node2{1}, node3{1}; vec2[13]->right = &node2; node2.right = &node3; - CHECK(3 == leetcode_1372::longestZigZag(vec2[0])); + CHECK(3 == solution.longestZigZag(vec2[0])); } TEST_CASE("test_case 2 [test_1372]", "[test_1372]") { + Solution solution; const TreeNodeLink vec2{1}; - CHECK(0 == leetcode_1372::longestZigZag(vec2[0])); + CHECK(0 == solution.longestZigZag(vec2[0])); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_1372_TEST_HPP diff --git a/algorithm/tree/leetcode_144.cpp b/algorithm/tree/leetcode_144.cpp index 7a70223c..1f1da570 100644 --- a/algorithm/tree/leetcode_144.cpp +++ b/algorithm/tree/leetcode_144.cpp @@ -1,27 +1,36 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_144_test.hpp" -#include "traverse.cpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include +#include +#include "traverse.cpp" namespace leetcode_144 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; using namespace Tree_Traverse; +#endif -vector leetcode_144::preorderTraversalIter(TreeNode *root) { - vector will_return{}; - const auto function = [&will_return](const TreeNode *tn) -> void { will_return.push_back(tn->val); }; - iter::pre1(root, function); - return will_return; -} +class Solution { +public: + vector preorderTraversalIter(TreeNode *root) { + vector will_return{}; + const auto function = [&will_return](const TreeNode *tn) -> void { will_return.push_back(tn->val); }; + iter::pre1(root, function); + return will_return; + } -vector leetcode_144::preorderTraversal(TreeNode *root) { - vector will_return{}; - const auto function = [&will_return](const TreeNode *tn) -> void { will_return.push_back(tn->val); }; - rec::pre(root, function); - return will_return; -} + vector preorderTraversal(TreeNode *root) { + vector will_return{}; + const auto function = [&will_return](const TreeNode *tn) -> void { will_return.push_back(tn->val); }; + rec::pre(root, function); + return will_return; + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_144_test.hpp b/algorithm/tree/leetcode_144_test.cpp similarity index 61% rename from algorithm/tree/leetcode_144_test.hpp rename to algorithm/tree/leetcode_144_test.cpp index 976b58e6..80413239 100644 --- a/algorithm/tree/leetcode_144_test.hpp +++ b/algorithm/tree/leetcode_144_test.cpp @@ -1,16 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@description 中序遍历 //@Plan 数据结构入门 Day10 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_144_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_144_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_144_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_144_TEST_HPP #include #include @@ -18,41 +13,38 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include "leetcode_144.cpp" namespace leetcode_144 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_144 { - static vector preorderTraversal(TreeNode *root); - - static vector preorderTraversalIter(TreeNode *root); -}; - using Catch::Matchers::Equals; using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_144]", "[test_144]") { + Solution solution; const TreeNodeLink input{4, 2, 7, 1, 3, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, }; const vector result{4, 2, 1, 3, 7}; - CHECK_THAT(result, Equals(leetcode_144::preorderTraversal(input[0]))); - CHECK_THAT(result, Equals(leetcode_144::preorderTraversalIter(input[0]))); + CHECK_THAT(result, Equals(solution.preorderTraversal(input[0]))); + CHECK_THAT(result, Equals(solution.preorderTraversalIter(input[0]))); } TEST_CASE("test_case 2 [test_144]", "[test_144]") { + Solution solution; const TreeNodeLink input{4, 2, 7, 1, 3, 5, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, }; const vector result{4, 2, 1, 3, 7, 5}; - CHECK_THAT(result, Equals(leetcode_144::preorderTraversal(input[0]))); - CHECK_THAT(result, Equals(leetcode_144::preorderTraversalIter(input[0]))); + CHECK_THAT(result, Equals(solution.preorderTraversal(input[0]))); + CHECK_THAT(result, Equals(solution.preorderTraversalIter(input[0]))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_144_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_144_TEST_HPP diff --git a/algorithm/tree/leetcode_145.cpp b/algorithm/tree/leetcode_145.cpp index f7657425..e1982293 100644 --- a/algorithm/tree/leetcode_145.cpp +++ b/algorithm/tree/leetcode_145.cpp @@ -1,27 +1,37 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_145_test.hpp" -#include "traverse.cpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include +#include +#include +#include "traverse.cpp" namespace leetcode_145 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; using namespace Tree_Traverse; +#endif -vector leetcode_145::postorderTraversalIter(TreeNode *root) { - vector will_return{}; - const auto function = [&will_return](const TreeNode *tn) -> void { will_return.push_back(tn->val); }; - iter::post(root, function); - return will_return; -} +class Solution { +public: + vector postorderTraversalIter(TreeNode *root) { + vector will_return{}; + const auto function = [&will_return](const TreeNode *tn) -> void { will_return.push_back(tn->val); }; + iter::post(root, function); + return will_return; + } -vector leetcode_145::postorderTraversal(TreeNode *root) { - vector will_return{}; - const auto function = [&will_return](const TreeNode *tn) -> void { will_return.push_back(tn->val); }; - rec::post(root, function); - return will_return; -} + vector postorderTraversal(TreeNode *root) { + vector will_return{}; + const auto function = [&will_return](const TreeNode *tn) -> void { will_return.push_back(tn->val); }; + rec::post(root, function); + return will_return; + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_145_test.hpp b/algorithm/tree/leetcode_145_test.cpp similarity index 61% rename from algorithm/tree/leetcode_145_test.hpp rename to algorithm/tree/leetcode_145_test.cpp index c341007e..9ffa5257 100644 --- a/algorithm/tree/leetcode_145_test.hpp +++ b/algorithm/tree/leetcode_145_test.cpp @@ -1,17 +1,12 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@description 中序遍历 //@Plan 数据结构入门 Day10 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_145_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_145_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_145_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_145_TEST_HPP #include #include @@ -19,41 +14,38 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include "leetcode_145.cpp" namespace leetcode_145 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_145 { - static vector postorderTraversal(TreeNode *root); - - static vector postorderTraversalIter(TreeNode *root); -}; - using Catch::Matchers::Equals; using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_145]", "[test_145]") { + Solution solution; const TreeNodeLink input{4, 2, 7, 1, 3, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, }; const vector result{1, 3, 2, 7, 4}; - CHECK_THAT(result, Equals(leetcode_145::postorderTraversal(input[0]))); - CHECK_THAT(result, Equals(leetcode_145::postorderTraversalIter(input[0]))); + CHECK_THAT(result, Equals(solution.postorderTraversal(input[0]))); + CHECK_THAT(result, Equals(solution.postorderTraversalIter(input[0]))); } TEST_CASE("test_case 2 [test_145]", "[test_145]") { + Solution solution; const TreeNodeLink input{4, 2, 7, 1, 3, 5, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, }; const vector result{1, 3, 2, 5, 7, 4}; - CHECK_THAT(result, Equals(leetcode_145::postorderTraversal(input[0]))); - CHECK_THAT(result, Equals(leetcode_145::postorderTraversalIter(input[0]))); + CHECK_THAT(result, Equals(solution.postorderTraversal(input[0]))); + CHECK_THAT(result, Equals(solution.postorderTraversalIter(input[0]))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_145_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_145_TEST_HPP diff --git a/algorithm/tree/leetcode_199.cpp b/algorithm/tree/leetcode_199.cpp index 78a44fe2..ae98dffe 100644 --- a/algorithm/tree/leetcode_199.cpp +++ b/algorithm/tree/leetcode_199.cpp @@ -1,37 +1,43 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_199_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include #include +#include namespace leetcode_199 { +using std::vector; using std::queue; +using TreeNode = TREE_NODE::TreeNode; +#endif -vector leetcode_199::rightSideView(const TreeNode *root) { - if (root == nullptr) { - return {}; - } - vector will_return{}; - for (queue now{{root}}, next{}; !now.empty(); std::swap(now, next)) { - vector line{}; - while (!now.empty()) { - const auto *const head = now.front(); - now.pop(); - line.push_back(head->val); - if (head->left != nullptr) { - next.push(head->left); - } - if (head->right != nullptr) { - next.push(head->right); +class Solution { +public: + vector rightSideView(const TreeNode *root) { + if (root == nullptr) { + return {}; + } + vector will_return{}; + for (queue now{{root}}, next{}; !now.empty(); std::swap(now, next)) { + vector line{}; + while (!now.empty()) { + const auto *const head = now.front(); + now.pop(); + line.push_back(head->val); + if (head->left != nullptr) { + next.push(head->left); + } + if (head->right != nullptr) { + next.push(head->right); + } } + will_return.push_back(line.back()); } - will_return.push_back(line.back()); + return will_return; } - return will_return; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_199_test.hpp b/algorithm/tree/leetcode_199_test.cpp similarity index 62% rename from algorithm/tree/leetcode_199_test.hpp rename to algorithm/tree/leetcode_199_test.cpp index 1ac4020b..4a2d70e9 100644 --- a/algorithm/tree/leetcode_199_test.hpp +++ b/algorithm/tree/leetcode_199_test.cpp @@ -1,16 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@description 层序遍历 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_199_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_199_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_199_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_199_TEST_HPP #include #include @@ -18,32 +13,31 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include "leetcode_199.cpp" namespace leetcode_199 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_199 { - static vector rightSideView(const TreeNode *root); -}; - using Catch::Matchers::Equals; using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_199]", "[test_199]") { + Solution solution; const TreeNodeLink input{1, 1, 4, 5, 1, TreeNode::No, 4, 1, TreeNode::No, 9 }; const vector result{1, 4, 4, 9}; - CHECK_THAT(result, Equals(leetcode_199::rightSideView(input[0]))); + CHECK_THAT(result, Equals(solution.rightSideView(input[0]))); } TEST_CASE("test_case 2 [test_199]", "[test_199]") { + Solution solution; const vector result{}; - CHECK_THAT(result, Equals(leetcode_199::rightSideView(nullptr))); + CHECK_THAT(result, Equals(solution.rightSideView(nullptr))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_199_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_199_TEST_HPP diff --git a/algorithm/tree/leetcode_226.cpp b/algorithm/tree/leetcode_226.cpp index 45868fa8..d3fb2831 100644 --- a/algorithm/tree/leetcode_226.cpp +++ b/algorithm/tree/leetcode_226.cpp @@ -1,21 +1,27 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_226_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include namespace leetcode_226 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -TreeNode *leetcode_226::invertTree(TreeNode *const root) { - if (root == nullptr) { - return nullptr; +class Solution { +public: + TreeNode *invertTree(TreeNode *const root) { + if (root == nullptr) { + return nullptr; + } + TreeNode *const temp = root->left; + root->left = invertTree(root->right); + root->right = invertTree(temp); + return root; } - TreeNode *const temp = root->left; - root->left = invertTree(root->right); - root->right = invertTree(temp); - return root; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_226_test.hpp b/algorithm/tree/leetcode_226_test.cpp similarity index 67% rename from algorithm/tree/leetcode_226_test.hpp rename to algorithm/tree/leetcode_226_test.cpp index 6c3b2be4..ae2d7029 100644 --- a/algorithm/tree/leetcode_226_test.hpp +++ b/algorithm/tree/leetcode_226_test.cpp @@ -1,40 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@Sword-Offer 27 //@Plan 数据结构入门 Day12 //@Plan 剑指OfferII-I Day07 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_226_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_226_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_226_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_226_TEST_HPP #include #include #include #include #include +#include "leetcode_226.cpp" namespace leetcode_226 { using TreeNode = TREE_NODE::TreeNode; -struct leetcode_226 { - static TreeNode *invertTree(TreeNode *root); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_226]", "[test_226]") { + Solution solution; const TreeNodeLink input{4, 2, 7, 1, 3, 6, 9}; - leetcode_226::invertTree(input[0]); + solution.invertTree(input[0]); const vector result{4, 7, 2, 9, 6, 3, 1, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No}; CHECK(TREE_NODE::judge_equal(input[0], result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_226_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_226_TEST_HPP diff --git a/algorithm/tree/leetcode_230.cpp b/algorithm/tree/leetcode_230.cpp index 2d80e6c2..758b3d2c 100644 --- a/algorithm/tree/leetcode_230.cpp +++ b/algorithm/tree/leetcode_230.cpp @@ -1,31 +1,40 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_230_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include #include +#include namespace leetcode_230 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif + +#include + using std::stack; -int32_t leetcode_230::kthSmallest(TreeNode *root, int32_t k) { - if (root == nullptr) { - return -1; - } - for (stack sta; root != nullptr || !sta.empty(); root = root->right) { - for (; root != nullptr; root = root->left) { - sta.push(root); +class Solution { +public: + int32_t kthSmallest(TreeNode *root, int32_t k) { + if (root == nullptr) { + return -1; } - root = sta.top(); - sta.pop(); - --k; - if (k == 0) { - break; + for (stack sta; root != nullptr || !sta.empty(); root = root->right) { + for (; root != nullptr; root = root->left) { + sta.push(root); + } + root = sta.top(); + sta.pop(); + --k; + if (k == 0) { + break; + } } + return root->val; } - return root->val; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/tree/leetcode_230_test.hpp b/algorithm/tree/leetcode_230_test.cpp similarity index 65% rename from algorithm/tree/leetcode_230_test.hpp rename to algorithm/tree/leetcode_230_test.cpp index 01c8b22e..5d71d597 100644 --- a/algorithm/tree/leetcode_230_test.hpp +++ b/algorithm/tree/leetcode_230_test.cpp @@ -1,41 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_230_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_230_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_230_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_230_TEST_HPP #include #include #include #include #include +#include "leetcode_230.cpp" namespace leetcode_230 { using TreeNode = TREE_NODE::TreeNode; -struct leetcode_230 { - static int32_t kthSmallest(TreeNode *root, int32_t k); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_230]", "[test_230]") { + Solution solution; const TreeNodeLink input{3, 1, 4, TreeNode::No, 2}; static constexpr const auto k{1}; static constexpr const auto result{1}; - CHECK(result == leetcode_230::kthSmallest(input[0], k)); + CHECK(result == solution.kthSmallest(input[0], k)); } TEST_CASE("test_case 2 [test_230]", "[test_230]") { + Solution solution; const TreeNodeLink input{5, 3, 6, 2, 4, TreeNode::No, TreeNode::No, @@ -43,7 +37,7 @@ TEST_CASE("test_case 2 [test_230]", "[test_230]") { }; static constexpr const auto k{3}; static constexpr const auto result{3}; - CHECK(result == leetcode_230::kthSmallest(input[0], k)); + CHECK(result == solution.kthSmallest(input[0], k)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_230_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_230_TEST_HPP diff --git a/algorithm/tree/leetcode_235.cpp b/algorithm/tree/leetcode_235.cpp index 2368ab90..b46d3097 100644 --- a/algorithm/tree/leetcode_235.cpp +++ b/algorithm/tree/leetcode_235.cpp @@ -1,30 +1,100 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_235_test.hpp" -#include "traverse.cpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_235 { -using namespace Tree_Traverse; +using std::vector; +using std::unordered_map; +using TreeNode = TREE_NODE::TreeNode; +#endif -bool leetcode_235::findTarget(TreeNode *root, int k) { - vector targets{}; - const auto func = [&targets](const TreeNode *tn) -> void { targets.push_back(tn->val); }; - iter::in(root, func); - for (size_t ll{0}, rr{targets.size() - 1}; ll < rr;) { - const auto sum = targets[ll] + targets[rr]; - if (sum == k) { +class Solution { +public: + const TreeNode *lowestCommonAncestorV2(TreeNode *root, + TreeNode *p, TreeNode *q) { + // first, visit the p node, find it's parent-link + // then, visit the q node and match it's parents one by one. + if (root->val == p->val || root->val == q->val){ + return root; + } + unordered_map node_to_depth{}; + int32_t depth{1}; + for(TreeNode* base{root};base != nullptr && base->val != p->val;depth++ ) { + node_to_depth[base] = depth; + if (base->val > p->val) { + base = base->left; + } else if (base->val < p->val) { + base = base->right; + } + } + node_to_depth[p] = depth; + TreeNode* will_return{nullptr}; + depth = 0; + for(TreeNode* base{root};base != nullptr && base->val != q->val;) { + if (node_to_depth.count(base) != 0 && node_to_depth[base] > depth) { + will_return = base; + depth = node_to_depth[base]; + } + if (base->val > q->val) { + base = base->left; + } else if (base->val val) { + base = base->right; + } + } + if (node_to_depth.count(q) != 0 && node_to_depth[q] > depth) { + will_return = q; + } + return will_return; + } +private: + bool nodeHadValue(unordered_map &umap, TreeNode *base, int32_t value) { + if (base == nullptr) { + return false; + } + if (umap.count(base) != 0) { + return umap.at(base); + } + if (base->val == value) { + umap[base] = true; return true; - } else if (sum > k) { - --rr; - } else if (sum < k) { - ++ll; } + const auto will_return = nodeHadValue(umap, base->left, value) || nodeHadValue(umap, base->right, value); + umap[base] = will_return; + return will_return; } - return false; -} +public: + const TreeNode *lowestCommonAncestor(const TreeNode *root, const TreeNode *const p, const TreeNode *const q) { + if (root == nullptr) { + return nullptr; + } + for (unordered_map pmap, qmap; root != nullptr;) { + if (root->val == p->val) { + return p; + } else if (root->val == q->val) { + return q; + } + const auto pleft = nodeHadValue(pmap, root->left, p->val); + const auto pright = nodeHadValue(pmap, root->right, p->val); + + const auto qleft = nodeHadValue(qmap, root->left, q->val); + const auto qright = nodeHadValue(qmap, root->right, q->val); + if (pleft && qright) { + return root; + } else if (pright && qleft) { + return root; + } else if (pleft && qleft) { + root = root->left; + } else { + root = root->right; + } + } + return nullptr; + } +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_235_test.cpp b/algorithm/tree/leetcode_235_test.cpp new file mode 100644 index 00000000..d2353483 --- /dev/null +++ b/algorithm/tree/leetcode_235_test.cpp @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag tree +//@Tag 树 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_235_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_235_TEST_HPP + +#include +#include +#include +#include +#include +#include +#include "leetcode_235.cpp" + +namespace leetcode_235 { + +using TreeNode = TREE_NODE::TreeNode; + +using TreeNodeLink = TREE_NODE::TreeNodeLink; +using TREE_NODE::numToTree; + +TEST_CASE("test_case 1 [test_235]", "[test_235]") { + Solution solution; + const TreeNodeLink input{6, + 2, 8, + 0, 4, 7, 9, + TreeNode::No, TreeNode::No, 3, 5}; + const TreeNode p{2}, q{8}; + static constexpr const auto result{6}; + CHECK(result == solution.lowestCommonAncestor(input[0], &p, &q)->val); + CHECK(result == solution.lowestCommonAncestorV2(input[0], input[1], input[2])->val); +} +TEST_CASE("test_case 2 [test_235]", "[test_235]") { + Solution solution; + const TreeNodeLink input{2, + 1}; + const TreeNode p{1}, q{2}; + static constexpr const auto result{2}; + CHECK(result == solution.lowestCommonAncestor(input[0], &p, &q)->val); + CHECK(result == solution.lowestCommonAncestorV2(input[0], input[0], input[1])->val); +} + +TEST_CASE("test_case 3 [test_235]", "[test_235]") { + Solution solution; + const TreeNodeLink input{6, + 2, 8, + 0, 4, 7, 9, + TreeNode::No, TreeNode::No, 3, 5}; + TreeNode p{2}, q{4}; + static constexpr const auto result{2}; + CHECK(result == solution.lowestCommonAncestor(input[0], &p, &q)->val); + CHECK(result == solution.lowestCommonAncestorV2(input[0], input[1], input[4])->val); +} +TEST_CASE("test_case 4 [test_235]", "[test_235]") { + Solution solution; + const TreeNodeLink input{5, + 3, 6, + 2, 4,TreeNode::No, TreeNode::No, + 1}; + TreeNode p{1}, q{3}; + static constexpr const auto result{3}; + CHECK(result == solution.lowestCommonAncestor(input[0], &p, &q)->val); + CHECK(result == solution.lowestCommonAncestorV2(input[0], input[7], input[1])->val); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_235_TEST_HPP diff --git a/algorithm/tree/leetcode_236.cpp b/algorithm/tree/leetcode_236.cpp deleted file mode 100644 index 20ea71bf..00000000 --- a/algorithm/tree/leetcode_236.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_236_test.hpp" -#include - -namespace leetcode_236 { -using std::unordered_map; - -bool nodeHadValue(unordered_map &umap, TreeNode *base, int32_t value) { - if (base == nullptr) { - return false; - } - if (umap.count(base) != 0) { - return umap.at(base); - } - if (base->val == value) { - umap[base] = true; - return true; - } - const auto will_return = nodeHadValue(umap, base->left, value) || nodeHadValue(umap, base->right, value); - umap[base] = will_return; - return will_return; -} - -const TreeNode * -leetcode_236::lowestCommonAncestor(const TreeNode *root, const TreeNode *const p, const TreeNode *const q) { - if (root == nullptr) { - return nullptr; - } - for (unordered_map pmap, qmap; root != nullptr;) { - if (root->val == p->val) { - return p; - } else if (root->val == q->val) { - return q; - } - const auto pleft = nodeHadValue(pmap, root->left, p->val); - const auto pright = nodeHadValue(pmap, root->right, p->val); - - const auto qleft = nodeHadValue(qmap, root->left, q->val); - const auto qright = nodeHadValue(qmap, root->right, q->val); - if (pleft && qright) { - return root; - } else if (pright && qleft) { - return root; - } else if (pleft && qleft) { - root = root->left; - } else { - root = root->right; - } - } - return nullptr; -} - -} diff --git a/algorithm/tree/leetcode_236_test.hpp b/algorithm/tree/leetcode_236_test.hpp deleted file mode 100644 index 9a4037e2..00000000 --- a/algorithm/tree/leetcode_236_test.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag tree -//@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_236_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_236_TEST_HPP - -#include -#include -#include -#include -#include -#include - -namespace leetcode_236 { - -using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_236 { - static const TreeNode *lowestCommonAncestor(const TreeNode *root, const TreeNode *p, const TreeNode *q); -}; - - -using TreeNodeLink = TREE_NODE::TreeNodeLink; -using TREE_NODE::numToTree; - -TEST_CASE("test_case 1 [test_236]", "[test_236]") { - const TreeNodeLink input{3, - 5, 1, - 6, 2, 0, 8, - TreeNode::No, TreeNode::No, 7, 4}; - const TreeNode p{5}, q{1}; - static constexpr const auto result{3}; - CHECK(result == leetcode_236::lowestCommonAncestor(input[0], &p, &q)->val); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_236_TEST_HPP diff --git a/algorithm/tree/leetcode_426.cpp b/algorithm/tree/leetcode_426.cpp index dcec021b..d021e6f3 100644 --- a/algorithm/tree/leetcode_426.cpp +++ b/algorithm/tree/leetcode_426.cpp @@ -1,41 +1,48 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_426_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include #include +#include namespace leetcode_426 { +using std::vector; +using Node = TREE_NODE::TreeNode; using std::stack; -Node *leetcode_426::treeToDoublyList(Node *root) { - if (root == nullptr) { - return nullptr; - } - Node *base{nullptr}; - Node *head = root; - bool temp{false}; - for (stack sta; head != nullptr || !sta.empty(); head = head->right) { - for (; head != nullptr; head = head->left) { - sta.push(head); - } - head = sta.top(); - sta.pop(); - if (base != nullptr) { - base->right = head; +#endif + +class Solution { +public: + Node *treeToDoublyList(Node *root) { + if (root == nullptr) { + return nullptr; } - head->left = base; - if (!temp) { - root = head; - temp = true; + Node *base{nullptr}; + Node *head = root; + bool temp{false}; + for (stack sta; head != nullptr || !sta.empty(); head = head->right) { + for (; head != nullptr; head = head->left) { + sta.push(head); + } + head = sta.top(); + sta.pop(); + if (base != nullptr) { + base->right = head; + } + head->left = base; + if (!temp) { + root = head; + temp = true; + } + base = head; } - base = head; + root->left = base; + base->right = root; + return root; } - root->left = base; - base->right = root; - return root; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_426_test.hpp b/algorithm/tree/leetcode_426_test.cpp similarity index 71% rename from algorithm/tree/leetcode_426_test.hpp rename to algorithm/tree/leetcode_426_test.cpp index 24050607..ed14527d 100644 --- a/algorithm/tree/leetcode_426_test.hpp +++ b/algorithm/tree/leetcode_426_test.cpp @@ -1,16 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@Plan 数据结构入门 Day14 //@Plan 剑指OfferII-I Day15 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_426_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_426_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_426_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_426_TEST_HPP #include #include @@ -18,22 +13,20 @@ Copyright (C) 2020-2023 nanoseeds #include #include #include +#include "leetcode_426.cpp" namespace leetcode_426 { using TreeNode = TREE_NODE::TreeNode; using Node = TreeNode; -struct leetcode_426 { - static Node *treeToDoublyList(Node *root); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; TEST_CASE("test_case 1 [test_426]", "[test_426]") { + Solution solution; const TreeNodeLink input{4, 2, 5, 1, 3}; - leetcode_426::treeToDoublyList(input[0]); + solution.treeToDoublyList(input[0]); CHECK(3 == input[0]->left->val); CHECK(5 == input[0]->right->val); CHECK(1 == input[1]->left->val); @@ -46,4 +39,4 @@ TEST_CASE("test_case 1 [test_426]", "[test_426]") { CHECK(4 == input[4]->right->val); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_426_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_426_TEST_HPP diff --git a/algorithm/tree/leetcode_530.cpp b/algorithm/tree/leetcode_530.cpp index 2a20cbea..3f06e840 100644 --- a/algorithm/tree/leetcode_530.cpp +++ b/algorithm/tree/leetcode_530.cpp @@ -1,57 +1,63 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_530_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include #include - +#include +#include +#include namespace leetcode_530 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; -using std::stack; +#endif -int32_t leetcode_530::getMinimumDifference(TreeNode *root) { - if (root == nullptr) { - return std::numeric_limits::max(); - } - const auto *left = root->left; - const auto *right = root->right; - while (left != nullptr && left->right != nullptr) { - left = left->right; - } - while (right != nullptr && right->left != nullptr) { - right = right->left; - } - int32_t left_son_diff{std::numeric_limits::max()}, right_son_diff{std::numeric_limits::max()}; - if (left != nullptr) { - left_son_diff = root->val - left->val; - } - if (right != nullptr) { - right_son_diff = right->val - root->val; +class Solution { +public: + int32_t getMinimumDifference(TreeNode *root) { + if (root == nullptr) { + return std::numeric_limits::max(); + } + const auto *left = root->left; + const auto *right = root->right; + while (left != nullptr && left->right != nullptr) { + left = left->right; + } + while (right != nullptr && right->left != nullptr) { + right = right->left; + } + int32_t left_son_diff{std::numeric_limits::max()}, right_son_diff{std::numeric_limits::max()}; + if (left != nullptr) { + left_son_diff = root->val - left->val; + } + if (right != nullptr) { + right_son_diff = right->val - root->val; + } + const int32_t left_will_return = getMinimumDifference(root->left); + const int32_t right_will_return = getMinimumDifference(root->right); + return std::min({left_son_diff, right_son_diff, left_will_return, right_will_return}); } - const int32_t left_will_return = getMinimumDifference(root->left); - const int32_t right_will_return = getMinimumDifference(root->right); - return std::min({left_son_diff, right_son_diff, left_will_return, right_will_return}); -} -int32_t leetcode_530::getMinimumDifference2(TreeNode *root) { - if (root == nullptr) { - return std::numeric_limits::max(); - } - stack sta{}; - int32_t lastValue{-0x3f3f3f3f}, will_return{std::numeric_limits::max()}; - for (TreeNode *head{root}; head != nullptr || !sta.empty(); head = head->right) { - while (head != nullptr) { - sta.push(head); - head = head->left; + int32_t getMinimumDifference2(TreeNode *root) { + if (root == nullptr) { + return std::numeric_limits::max(); } - head = sta.top(); - sta.pop(); - will_return = std::min(will_return, head->val - lastValue); - lastValue = head->val; + std::stack sta{}; + int32_t lastValue{-0x3f3f3f3f}, will_return{std::numeric_limits::max()}; + for (TreeNode *head{root}; head != nullptr || !sta.empty(); head = head->right) { + while (head != nullptr) { + sta.push(head); + head = head->left; + } + head = sta.top(); + sta.pop(); + will_return = std::min(will_return, head->val - lastValue); + lastValue = head->val; + } + return will_return; } - return will_return; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_530_test.hpp b/algorithm/tree/leetcode_530_test.cpp similarity index 54% rename from algorithm/tree/leetcode_530_test.hpp rename to algorithm/tree/leetcode_530_test.cpp index b2f69907..09c8b0d5 100644 --- a/algorithm/tree/leetcode_530_test.hpp +++ b/algorithm/tree/leetcode_530_test.cpp @@ -1,54 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@Tag in-traverse //@Tag 中序遍历二叉树 //@Same 783 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_530_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_530_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_530_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_530_TEST_HPP #include #include #include #include #include +#include "leetcode_530.cpp" namespace leetcode_530 { using TreeNode = TREE_NODE::TreeNode; -struct leetcode_530 { - static int32_t getMinimumDifference(TreeNode *root); - - static int32_t getMinimumDifference2(TreeNode *root); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_530]", "[test_530]") { + Solution solution; const TreeNodeLink input{4, 2, 6, 1, 3}; static constexpr const auto result{1}; THEN("case 1") { - CHECK(result == leetcode_530::getMinimumDifference(input[0])); + CHECK(result == solution.getMinimumDifference(input[0])); }THEN("case 2") { - CHECK(result == leetcode_530::getMinimumDifference2(input[0])); + CHECK(result == solution.getMinimumDifference2(input[0])); } } TEST_CASE("test_case 2 [test_530]", "[test_530]") { + Solution solution; const TreeNodeLink input{1, 0, 48, TreeNode::No, TreeNode::No, 12, 49}; static constexpr const auto result{1}; THEN("case 1") { - CHECK(result == leetcode_530::getMinimumDifference(input[0])); + CHECK(result == solution.getMinimumDifference(input[0])); }THEN("case 2") { - CHECK(result == leetcode_530::getMinimumDifference2(input[0])); + CHECK(result == solution.getMinimumDifference2(input[0])); } } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_530_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_530_TEST_HPP diff --git a/algorithm/tree/leetcode_543.cpp b/algorithm/tree/leetcode_543.cpp index 80d7725f..f64c7b75 100644 --- a/algorithm/tree/leetcode_543.cpp +++ b/algorithm/tree/leetcode_543.cpp @@ -1,28 +1,35 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_543_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include #include +#include +#include namespace leetcode_543 { -int rec(TreeNode *base, int32_t num, const std::shared_ptr& max) { - if (base == nullptr) { - return num; - } - const auto left = rec(base->left, num, max); - const auto right = rec(base->right, num, max); - *max = std::max(*max, left + right); - return std::max(left, right) + 1; -} +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -int32_t leetcode_543::diameterOfBinaryTree(TreeNode *root) { - auto maxV = std::make_shared(0); - rec(root, 0, maxV); - return *maxV; -} +class Solution { +private: + int rec(TreeNode *base, int32_t num, const std::shared_ptr& max) { + if (base == nullptr) { + return num; + } + const auto left = rec(base->left, num, max); + const auto right = rec(base->right, num, max); + *max = std::max(*max, left + right); + return std::max(left, right) + 1; + } +public: + int32_t diameterOfBinaryTree(TreeNode *root) { + auto maxV = std::make_shared(0); + rec(root, 0, maxV); + return *maxV; + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_543_test.hpp b/algorithm/tree/leetcode_543_test.cpp similarity index 55% rename from algorithm/tree/leetcode_543_test.hpp rename to algorithm/tree/leetcode_543_test.cpp index edb88704..1d64b1ac 100644 --- a/algorithm/tree/leetcode_543_test.hpp +++ b/algorithm/tree/leetcode_543_test.cpp @@ -1,36 +1,29 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_543_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_543_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_543_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_543_TEST_HPP #include #include #include #include #include +#include "leetcode_543.cpp" namespace leetcode_543 { using TreeNode = TREE_NODE::TreeNode; -struct leetcode_543 { - static int32_t diameterOfBinaryTree(TreeNode *root); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; TEST_CASE("test_case 1 [test_543]", "[test_543]") { + Solution solution; const TreeNodeLink input{4, 2, 6, 1, 3}; static constexpr const auto result{3}; - CHECK(result == leetcode_543::diameterOfBinaryTree(input[0])); + CHECK(result == solution.diameterOfBinaryTree(input[0])); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_543_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_543_TEST_HPP diff --git a/algorithm/tree/leetcode_559.cpp b/algorithm/tree/leetcode_559.cpp index edc95075..daf68494 100644 --- a/algorithm/tree/leetcode_559.cpp +++ b/algorithm/tree/leetcode_559.cpp @@ -1,22 +1,31 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2022-2023 nanoseeds -*/ -#include "leetcode_559_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include namespace leetcode_559 { +using Node = TREE_NODE::TreeNodeMulti; +using std::stack; +#endif -int leetcode_559::maxDepth(Node *root) { - if (root == nullptr) { - return 0; - } - int32_t maxvalue{0}; - for (const auto pointer: root->children) { - maxvalue = std::max(maxvalue, maxDepth(pointer)); + +class Solution { +public: + int maxDepth(Node *root) { + if (root == nullptr) { + return 0; + } + int maxvalue{0}; + for (const auto pointer: root->children) { + maxvalue = std::max(maxvalue, maxDepth(pointer)); + } + return maxvalue + 1; } - return maxvalue + 1; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_559_test.hpp b/algorithm/tree/leetcode_559_test.cpp similarity index 55% rename from algorithm/tree/leetcode_559_test.hpp rename to algorithm/tree/leetcode_559_test.cpp index 64275573..5caf39a3 100644 --- a/algorithm/tree/leetcode_559_test.hpp +++ b/algorithm/tree/leetcode_559_test.cpp @@ -1,34 +1,27 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 //@Tag DFS //@Tag 深度优先遍历 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_559_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_559_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_559_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_559_TEST_HPP #include #include #include #include #include +#include "leetcode_559.cpp" namespace leetcode_559 { using Node = TREE_NODE::TreeNodeMulti; using std::stack; -struct leetcode_559 { - static int maxDepth(Node *root); -}; - TEST_CASE("test_case 1 [test_559]", "[test_559]") { + Solution solution; CHECK(true); // too simple } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_559_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_559_TEST_HPP diff --git a/algorithm/tree/leetcode_589.cpp b/algorithm/tree/leetcode_589.cpp index 0a68c698..e7b52faa 100644 --- a/algorithm/tree/leetcode_589.cpp +++ b/algorithm/tree/leetcode_589.cpp @@ -1,47 +1,60 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2022-2023 nanoseeds -*/ -#include "leetcode_589_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_589 { +using std::vector; +using Node = TREE_NODE::TreeNodeMulti; +#endif -void real_action(const Node *const root, vector &vec) { - if (root == nullptr) { - return; - } - vec.push_back(root->val); - for (const auto child: root->children) { - real_action(child, vec); - } -} +#include +#include -vector leetcode_589::preorder(const Node *const root) { - vector vec; - real_action(root, vec); - return vec; -} +using std::vector; +using std::stack; -vector leetcode_589::preorderIter(const Node *const root) { - if (root == nullptr) { - return {}; +class Solution { +private: + void real_action(const Node *const root, vector &vec) { + if (root == nullptr) { + return; + } + vec.push_back(root->val); + for (const auto child: root->children) { + real_action(child, vec); + } } - vector vec{}; - const auto func = [&vec](const Node *const node) { - vec.push_back(node->val); - }; - for (stack sta{{root}}; !sta.empty();) { - const auto *const head = sta.top(); - sta.pop(); - func(head); - for (auto iter{head->children.rbegin()}; iter != head->children.rend(); iter++) { - sta.push(*iter); + +public: + vector preorder(const Node *const root) { + vector vec; + real_action(root, vec); + return vec; + } + + vector preorderIter(const Node *const root) { + if (root == nullptr) { + return {}; } + vector vec{}; + const auto func = [&vec](const Node *const node) { + vec.push_back(node->val); + }; + for (stack sta{{root}}; !sta.empty();) { + const auto *const head = sta.top(); + sta.pop(); + func(head); + for (auto iter{head->children.rbegin()}; iter != head->children.rend(); iter++) { + sta.push(*iter); + } + } + return vec; } - return vec; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_589_test.cpp b/algorithm/tree/leetcode_589_test.cpp new file mode 100644 index 00000000..197c6242 --- /dev/null +++ b/algorithm/tree/leetcode_589_test.cpp @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag tree +//@Tag 树 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_589_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_589_TEST_HPP + +#include +#include +#include +#include +#include +#include "leetcode_589.cpp" + +namespace leetcode_589 { + +using Node = TREE_NODE::TreeNodeMulti; +using std::stack; + +TEST_CASE("test_case 1 [test_589]", "[test_589]") { + Solution solution; + CHECK(true); // too simple +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_589_TEST_HPP diff --git a/algorithm/tree/leetcode_589_test.hpp b/algorithm/tree/leetcode_589_test.hpp deleted file mode 100644 index b7e184b1..00000000 --- a/algorithm/tree/leetcode_589_test.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag tree -//@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_589_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_589_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_589 { - -using Node = TREE_NODE::TreeNodeMulti; -using std::stack; - -struct leetcode_589 final { - static vector preorder(const Node *root); - - static vector preorderIter(const Node *root); -}; - -TEST_CASE("test_case 1 [test_589]", "[test_589]") { - CHECK(true); // too simple -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_589_TEST_HPP diff --git a/algorithm/tree/leetcode_590.cpp b/algorithm/tree/leetcode_590.cpp index 86c5f23b..ab018495 100644 --- a/algorithm/tree/leetcode_590.cpp +++ b/algorithm/tree/leetcode_590.cpp @@ -1,44 +1,53 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2022-2023 nanoseeds - -*/ -#include "leetcode_590_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include namespace leetcode_590 { +using std::vector; +using std::stack; +using std::list; +using Node = TREE_NODE::TreeNodeMulti; +#endif -void real_action(const Node *const root, vector &vec) { - if (root == nullptr) { - return; - } - for (const auto child: root->children) { - real_action(child, vec); +class Solution { +private: + void real_action(const Node *const root, vector &vec) { + if (root == nullptr) { + return; + } + for (const auto child: root->children) { + real_action(child, vec); + } + vec.push_back(root->val); } - vec.push_back(root->val); -} -vector leetcode_590::postorder(const Node *const root) { - vector vec; - real_action(root, vec); - return vec; -} - -vector leetcode_590::postorderIter(const Node *const root) { - if (root == nullptr) { - return {}; +public: + vector postorder(const Node *const root) { + vector vec; + real_action(root, vec); + return vec; } - list nodes; - for (stack sta{{root}}; !sta.empty();) { - const auto *const head = sta.top(); - sta.pop(); - nodes.push_front(head->val); - for (const auto iter: head->children) { - sta.push(iter); + + vector postorderIter(const Node *const root) { + if (root == nullptr) { + return {}; } + list nodes; + for (stack sta{{root}}; !sta.empty();) { + const auto *const head = sta.top(); + sta.pop(); + nodes.push_front(head->val); + for (const auto iter: head->children) { + sta.push(iter); + } + } + return {nodes.cbegin(), nodes.cend()}; } - return {nodes.cbegin(), nodes.cend()}; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_590_test.cpp b/algorithm/tree/leetcode_590_test.cpp new file mode 100644 index 00000000..1d87ba10 --- /dev/null +++ b/algorithm/tree/leetcode_590_test.cpp @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +//@Tag tree +//@Tag 树 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_590_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_590_TEST_HPP + +#include +#include +#include +#include +#include +#include "leetcode_590.cpp" + +namespace leetcode_590 { +using std::vector; +using Node = TREE_NODE::TreeNodeMulti; +using std::stack; +using std::list; + +TEST_CASE("test_case 1 [test_590]", "[test_590]") { + Solution solution; + CHECK(true); // too simple +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_590_TEST_HPP diff --git a/algorithm/tree/leetcode_590_test.hpp b/algorithm/tree/leetcode_590_test.hpp deleted file mode 100644 index 642685ab..00000000 --- a/algorithm/tree/leetcode_590_test.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ -//@Tag tree -//@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_590_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_590_TEST_HPP - -#include -#include -#include -#include -#include - -namespace leetcode_590 { -using std::vector; -using Node = TREE_NODE::TreeNodeMulti; -using std::stack; -using std::list; - -struct leetcode_590 final { - static vector postorder(const Node *root); - - static vector postorderIter(const Node *root); -}; - -TEST_CASE("test_case 1 [test_590]", "[test_590]") { - CHECK(true); // too simple -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_590_TEST_HPP diff --git a/algorithm/tree/leetcode_617.cpp b/algorithm/tree/leetcode_617.cpp index 5aaa72bf..75820e8f 100644 --- a/algorithm/tree/leetcode_617.cpp +++ b/algorithm/tree/leetcode_617.cpp @@ -1,46 +1,49 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2022-2023 nanoseeds -*/ -#include "leetcode_617_test.hpp" -#include "traverse.cpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include namespace leetcode_617 { -using namespace Tree_Traverse; - -int32_t returnValueOfNode(TreeNode *t1, TreeNode *t2) { - int willreturn{0}; - for (const auto i: {t1, t2}) { - if (i != nullptr) { - willreturn += i->val; +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif + +class Solution { +private: + int32_t returnValueOfNode(TreeNode *t1, TreeNode *t2) { + int willreturn{0}; + for (const auto i: {t1, t2}) { + if (i != nullptr) { + willreturn += i->val; + } } + return willreturn; } - return willreturn; -} -TreeNode *mergeTreesRec(TreeNode *t1, TreeNode *t2, const std::function &func) { - if (t1 == nullptr) { - return t2; - } else if (t2 == nullptr) { - return t1; + TreeNode *mergeTreesRec(TreeNode *t1, TreeNode *t2, const std::function &func) { + if (t1 == nullptr) { + return t2; + } else if (t2 == nullptr) { + return t1; + } + auto *const willreturn = new TreeNode{returnValueOfNode(t1, t2)}; + func(willreturn); + willreturn->left = mergeTreesRec(t1->left, t2->left, func); + willreturn->right = mergeTreesRec(t1->right, t2->right, func); + return willreturn; } - auto *const willreturn = new TreeNode{returnValueOfNode(t1, t2)}; - func(willreturn); - //cout << willreturn->val << endl; - willreturn->left = mergeTreesRec(t1->left, t2->left, func); - willreturn->right = mergeTreesRec(t1->right, t2->right, func); - return willreturn; -} - -std::pair> leetcode_617::mergeTrees(TreeNode *t1, TreeNode *t2) { - vector will_return{}; - const auto func = [&will_return](TreeNode *node) { will_return.push_back(node); }; - const auto result = mergeTreesRec(t1, t2, func); - return {result, will_return}; -} - +public: + std::pair> mergeTrees(TreeNode *t1, TreeNode *t2) { + vector will_return{}; + const auto func = [&will_return](TreeNode *node) { will_return.push_back(node); }; + const auto result = mergeTreesRec(t1, t2, func); + return {result, will_return}; + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_617_test.hpp b/algorithm/tree/leetcode_617_test.cpp similarity index 68% rename from algorithm/tree/leetcode_617_test.hpp rename to algorithm/tree/leetcode_617_test.cpp index 9c1981f4..94c965fe 100644 --- a/algorithm/tree/leetcode_617_test.hpp +++ b/algorithm/tree/leetcode_617_test.cpp @@ -1,14 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_617_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_617_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_617_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_617_TEST_HPP #include #include @@ -16,29 +11,26 @@ Copyright (C) 2022-2023 nanoseeds #include #include #include +#include "leetcode_617.cpp" namespace leetcode_617 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_617 final { - static std::pair> mergeTrees(TreeNode *root1, TreeNode *root2); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; TEST_CASE("test_case 1 [test_617]", "[test_617]") { + Solution solution; const TreeNodeLink input1{1, 3, 2, 5, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No}; const TreeNodeLink input2{2, 1, 3, TreeNode::No, 4, TreeNode::No, 7, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No}; const vector result{3, 4, 5, 5, 4, TreeNode::No, 7, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No}; - const auto[resultPtr, resultNodes] = leetcode_617::mergeTrees(input1[0], input2[0]); + const auto[resultPtr, resultNodes] = solution.mergeTrees(input1[0], input2[0]); CHECK(TREE_NODE::judge_equal(resultPtr, result)); const TreeNodeLink link3{resultNodes}; -// 内存不太好管理,停掉测试 } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_617_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_617_TEST_HPP diff --git a/algorithm/tree/leetcode_653.cpp b/algorithm/tree/leetcode_653.cpp index 41fc84eb..1579851f 100644 --- a/algorithm/tree/leetcode_653.cpp +++ b/algorithm/tree/leetcode_653.cpp @@ -1,20 +1,27 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_653_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_653 { -TreeNode *leetcode_653::lowestCommonAncestor(TreeNode *root, const TreeNode *const p, const TreeNode *const q) { - if (root->val > std::max(p->val, q->val)) { - return lowestCommonAncestor(root->left, p, q); - } else if (root->val < std::min(p->val, q->val)) { - return lowestCommonAncestor(root->right, p, q); +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif + +class Solution { +public: + TreeNode *lowestCommonAncestor(TreeNode *root, const TreeNode *const p, const TreeNode *const q) { + if (root->val > std::max(p->val, q->val)) { + return lowestCommonAncestor(root->left, p, q); + } else if (root->val < std::min(p->val, q->val)) { + return lowestCommonAncestor(root->right, p, q); + } + return root; } - return root; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_653_test.hpp b/algorithm/tree/leetcode_653_test.cpp similarity index 71% rename from algorithm/tree/leetcode_653_test.hpp rename to algorithm/tree/leetcode_653_test.cpp index 3a6d910f..c4ce8b16 100644 --- a/algorithm/tree/leetcode_653_test.hpp +++ b/algorithm/tree/leetcode_653_test.cpp @@ -1,15 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 //@Plan 数据结构入门 Day14 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_653_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_653_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_653_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_653_TEST_HPP #include #include @@ -17,18 +12,16 @@ Copyright (C) 2022-2023 nanoseeds #include #include #include +#include "leetcode_653.cpp" namespace leetcode_653 { using TreeNode = TREE_NODE::TreeNode; -struct leetcode_653 final { - static TreeNode *lowestCommonAncestor(TreeNode *root, const TreeNode *p, const TreeNode *q); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_653]", "[test_653]") { + Solution solution; const TreeNodeLink input{6, 2, 8, 0, 4, 7, 9, @@ -39,10 +32,11 @@ TEST_CASE("test_case 1 [test_653]", "[test_653]") { auto *const q = new TreeNode(8); const TreeNodeLink link2{p}, link3{q}; static constexpr const auto result{6}; - CHECK(result == leetcode_653::lowestCommonAncestor(input[0], p, q)->val); + CHECK(result == solution.lowestCommonAncestor(input[0], p, q)->val); } TEST_CASE("test_case 2 [test_653]", "[test_653]") { + Solution solution; const TreeNodeLink input{6, 2, 8, 0, 4, 7, 9, @@ -53,7 +47,7 @@ TEST_CASE("test_case 2 [test_653]", "[test_653]") { auto *const q = new TreeNode(4); const TreeNodeLink link2{p}, link3{q}; static constexpr const auto result{2}; - CHECK(result == leetcode_653::lowestCommonAncestor(input[0], p, q)->val); + CHECK(result == solution.lowestCommonAncestor(input[0], p, q)->val); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_653_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_653_TEST_HPP diff --git a/algorithm/tree/leetcode_654.cpp b/algorithm/tree/leetcode_654.cpp index 01daa057..f8ccc57d 100644 --- a/algorithm/tree/leetcode_654.cpp +++ b/algorithm/tree/leetcode_654.cpp @@ -1,39 +1,45 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_654_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include +#include namespace leetcode_654 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -inline int get_max(const vector &nums, size_t begin, size_t end) { - int maxv{INT16_MIN}, posi{0}; - for (size_t i{begin}; i < end; i++) { - if (maxv < nums[i]) { - maxv = nums[i]; - posi = i; +class Solution { +private: + inline int get_max(const vector &nums, size_t begin, size_t end) { + int maxv{std::numeric_limits::min()}, posi{0}; + for (size_t i{begin}; i < end; i++) { + if (maxv < nums[i]) { + maxv = nums[i]; + posi = i; + } } + return posi; } - return posi; -} -TreeNode *rec(const vector &nums, size_t begin, size_t end) { - //cout << begin << " " << end << endl; - if (begin == end) { - return nullptr; + TreeNode *rec(const vector &nums, size_t begin, size_t end) { + if (begin == end) { + return nullptr; + } + const int posi = get_max(nums, begin, end); + auto *const willreturn = new TreeNode(nums[posi]); + willreturn->left = rec(nums, begin, posi); + willreturn->right = rec(nums, posi + 1, end); + return willreturn; } - const int posi = get_max(nums, begin, end); - auto *const willreturn = new TreeNode(nums[posi]); - willreturn->left = rec(nums, begin, posi); - willreturn->right = rec(nums, posi + 1, end); - return willreturn; -} - -TreeNode *leetcode_654::constructMaximumBinaryTree(const vector &nums) { - return rec(nums, 0, nums.size()); -} +public: + TreeNode *constructMaximumBinaryTree(const vector &nums) { + return rec(nums, 0, nums.size()); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_654_test.hpp b/algorithm/tree/leetcode_654_test.cpp similarity index 68% rename from algorithm/tree/leetcode_654_test.hpp rename to algorithm/tree/leetcode_654_test.cpp index b4c7f1fb..41e72013 100644 --- a/algorithm/tree/leetcode_654_test.hpp +++ b/algorithm/tree/leetcode_654_test.cpp @@ -1,16 +1,13 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_654_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_654_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_654_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_654_TEST_HPP #include +#include "leetcode_654.cpp" + #include #include #include @@ -21,30 +18,28 @@ namespace leetcode_654 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_654 final { - static TreeNode *constructMaximumBinaryTree(const vector &nums); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; TEST_CASE("test_case 1 [test_654]", "[test_654]") { + Solution solution; const vector input{3, 2, 1, 6, 0, 5}; const vector result{6, 3, 5, TreeNode::No, 2, 0, TreeNode::No, TreeNode::No, 1, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No}; - auto *const resultPtr = leetcode_654::constructMaximumBinaryTree(input); + auto *const resultPtr = solution.constructMaximumBinaryTree(input); const TreeNodeLink link{resultPtr}; CHECK(TREE_NODE::judge_equal(resultPtr, result)); } TEST_CASE("test_case 2 [test_654]", "[test_654]") { + Solution solution; const vector input{3, 2, 1}; const vector result{3, TreeNode::No, 2, TreeNode::No, 1, TreeNode::No, TreeNode::No}; - auto *const resultPtr = leetcode_654::constructMaximumBinaryTree(input); + auto *const resultPtr = solution.constructMaximumBinaryTree(input); const TreeNodeLink link{resultPtr}; CHECK(TREE_NODE::judge_equal(resultPtr, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_654_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_654_TEST_HPP diff --git a/algorithm/tree/leetcode_669.cpp b/algorithm/tree/leetcode_669.cpp index e4e5b249..89f620c7 100644 --- a/algorithm/tree/leetcode_669.cpp +++ b/algorithm/tree/leetcode_669.cpp @@ -1,28 +1,33 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_669_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include namespace leetcode_669 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -TreeNode *leetcode_669::trimBST(TreeNode *root, int L, int R) { - if (root == nullptr) { - return nullptr; +class Solution { +public: + TreeNode *trimBST(TreeNode *root, int L, int R) { + if (root == nullptr) { + return nullptr; + } + if (root->val < L) { + root->left = nullptr; + return trimBST(root->right, L, R); + } else if (root->val > R) { + root->right = nullptr; + return trimBST(root->left, L, R); + } + root->left = trimBST(root->left, L, R); + root->right = trimBST(root->right, L, R); + return root; } - if (root->val < L) { - root->left = nullptr; - return trimBST(root->right, L, R); - } else if (root->val > R) { - root->right = nullptr; - return trimBST(root->left, L, R); - } - root->left = trimBST(root->left, L, R); - root->right = trimBST(root->right, L, R); - return root; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_669_test.hpp b/algorithm/tree/leetcode_669_test.cpp similarity index 62% rename from algorithm/tree/leetcode_669_test.hpp rename to algorithm/tree/leetcode_669_test.cpp index 43b05d0e..f186d55b 100644 --- a/algorithm/tree/leetcode_669_test.hpp +++ b/algorithm/tree/leetcode_669_test.cpp @@ -1,14 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_669_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_669_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_669_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_669_TEST_HPP #include #include @@ -16,27 +11,25 @@ Copyright (C) 2022-2023 nanoseeds #include #include #include +#include "leetcode_669.cpp" namespace leetcode_669 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_669 final { - static TreeNode *trimBST(TreeNode *root, int L, int R); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; TEST_CASE("test_case 1 [test_669]", "[test_669]") { + Solution solution; const TreeNodeLink input{1, 0, 2}; const vector result{1, TreeNode::No, 2, TreeNode::No, TreeNode::No }; - auto *const resultPtr = leetcode_669::trimBST(input[0], 1, 2); + auto *const resultPtr = solution.trimBST(input[0], 1, 2); CHECK(TREE_NODE::judge_equal(resultPtr, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_669_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_669_TEST_HPP diff --git a/algorithm/tree/leetcode_700.cpp b/algorithm/tree/leetcode_700.cpp index c0d03297..1bbb15c8 100644 --- a/algorithm/tree/leetcode_700.cpp +++ b/algorithm/tree/leetcode_700.cpp @@ -1,36 +1,39 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_700_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include namespace leetcode_700 { +using TreeNode = TREE_NODE::TreeNode; +#endif -TreeNode *leetcode_700::searchBST(TreeNode *root, int32_t val) { - if (root == nullptr) { - return nullptr; - } else if (root->val == val) { - return root; - } else if (root->val > val) { - return (searchBST(root->left, val)); +class Solution { +public: + TreeNode *searchBST(TreeNode *root, int32_t val) { + if (root == nullptr) { + return nullptr; + } else if (root->val == val) { + return root; + } else if (root->val > val) { + return (searchBST(root->left, val)); + } + return (searchBST(root->right, val)); } - return (searchBST(root->right, val)); -} -TreeNode *leetcode_700::searchBSTiter(TreeNode *root, int32_t val) { - TreeNode *base{root}; - while (base != nullptr) { - if (base->val == val) { - return base; - } else if (base->val > val) { - base = base->left; - } else { - base = base->right; + TreeNode *searchBSTiter(TreeNode *root, int32_t val) { + TreeNode *base{root}; + while (base != nullptr) { + if (base->val == val) { + return base; + } else if (base->val > val) { + base = base->left; + } else { + base = base->right; + } } + return nullptr; } - return nullptr; -} +}; + +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_700_test.hpp b/algorithm/tree/leetcode_700_test.cpp similarity index 59% rename from algorithm/tree/leetcode_700_test.hpp rename to algorithm/tree/leetcode_700_test.cpp index a42151dd..60016d6a 100644 --- a/algorithm/tree/leetcode_700_test.hpp +++ b/algorithm/tree/leetcode_700_test.cpp @@ -1,48 +1,39 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 //@Plan 数据结构入门 Day13 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_700_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_700_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_700_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_700_TEST_HPP #include +#include "leetcode_700.cpp" #include #include -#include -#include #include +#include namespace leetcode_700 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_700 final { - static TreeNode *searchBST(TreeNode *root, int32_t val); - - static TreeNode *searchBSTiter(TreeNode *root, int32_t val); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; TEST_CASE("test_case 1 [test_700]", "[test_700]") { + Solution solution; const TreeNodeLink input{4, 2, 7, 1, 3, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, }; static constexpr const auto search{2}; - CHECK(search == leetcode_700::searchBST(input[0], search)->val); - CHECK(search == leetcode_700::searchBSTiter(input[0], search)->val); + CHECK(search == solution.searchBST(input[0], search)->val); + CHECK(search == solution.searchBSTiter(input[0], search)->val); } TEST_CASE("test_case 2 [test_700]", "[test_700]") { + Solution solution; const TreeNodeLink input{4, 2, 7, 1, 3, TreeNode::No, TreeNode::No, @@ -50,8 +41,8 @@ TEST_CASE("test_case 2 [test_700]", "[test_700]") { }; static constexpr const auto search{5}; - CHECK(nullptr == leetcode_700::searchBST(input[0], search)); - CHECK(nullptr == leetcode_700::searchBSTiter(input[0], search)); + CHECK(nullptr == solution.searchBST(input[0], search)); + CHECK(nullptr == solution.searchBSTiter(input[0], search)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_700_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_700_TEST_HPP diff --git a/algorithm/tree/leetcode_701.cpp b/algorithm/tree/leetcode_701.cpp index c7ae3f95..4c2eec87 100644 --- a/algorithm/tree/leetcode_701.cpp +++ b/algorithm/tree/leetcode_701.cpp @@ -1,34 +1,44 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_701_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include + +#include namespace leetcode_701 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -TreeNode *leetcode_701::insertIntoBST(TreeNode *root, int32_t val) { - auto *const newnode = new TreeNode(val); - if (root == nullptr) { - return newnode; - } - for (TreeNode *base{root}; base != nullptr;) { - if (base->val > val) { - if (base->left == nullptr) { - base->left = newnode; - return root; - } - base = base->left; - } else { - if (base->right == nullptr) { - base->right = newnode; - return root; + +class Solution { +public: + TreeNode *insertIntoBST(TreeNode *root, int32_t val) { + auto *const newnode = new TreeNode(val); + if (root == nullptr) { + return newnode; + } + for (TreeNode *base{root}; base != nullptr;) { + if (base->val > val) { + if (base->left == nullptr) { + base->left = newnode; + return root; + } + base = base->left; + } else { + if (base->right == nullptr) { + base->right = newnode; + return root; + } + base = base->right; } - base = base->right; } + return nullptr; } - return nullptr; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/tree/leetcode_701_test.hpp b/algorithm/tree/leetcode_701_test.cpp similarity index 73% rename from algorithm/tree/leetcode_701_test.hpp rename to algorithm/tree/leetcode_701_test.cpp index 64e486bb..f276ce6d 100644 --- a/algorithm/tree/leetcode_701_test.hpp +++ b/algorithm/tree/leetcode_701_test.cpp @@ -1,15 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 //@Plan 数据结构入门 Day13 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_701_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_701_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_701_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_701_TEST_HPP #include #include @@ -17,19 +12,18 @@ Copyright (C) 2022-2023 nanoseeds #include #include #include +#include "leetcode_701.cpp" namespace leetcode_701 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_701 final { - static TreeNode *insertIntoBST(TreeNode *root, int32_t val); -}; using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; TEST_CASE("test_case 1 [test_701]", "[test_701]") { + Solution solution; const vector input{4, 2, 7, 1, 3, TreeNode::No, TreeNode::No, @@ -43,15 +37,16 @@ TEST_CASE("test_case 1 [test_701]", "[test_701]") { }; const vector numVecInput = numToTree(input); const TreeNodeLink link{numVecInput[0]}; - CHECK(TREE_NODE::judge_equal(leetcode_701::insertIntoBST(numVecInput[0], newV), result)); + CHECK(TREE_NODE::judge_equal(solution.insertIntoBST(numVecInput[0], newV), result)); } TEST_CASE("test_case 2 [test_701]", "[test_701]") { + Solution solution; static constexpr const auto newV{5}; const vector output{5, TreeNode::No, TreeNode::No}; - const TreeNode *const result = leetcode_701::insertIntoBST(nullptr, newV); + const TreeNode *const result = solution.insertIntoBST(nullptr, newV); const TreeNodeLink link{const_cast(result)}; CHECK(TREE_NODE::judge_equal(const_cast(result), output)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_701_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_701_TEST_HPP diff --git a/algorithm/tree/leetcode_814.cpp b/algorithm/tree/leetcode_814.cpp index 93621a7e..0924bccf 100644 --- a/algorithm/tree/leetcode_814.cpp +++ b/algorithm/tree/leetcode_814.cpp @@ -1,29 +1,36 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_814_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include + +#include namespace leetcode_814 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -TreeNode *pruneTree_rec(TreeNode *root) { - if (root == nullptr) { - return nullptr; - } - root->left = pruneTree_rec(root->left); - root->right = pruneTree_rec(root->right); - if (root->left == nullptr && root->right == nullptr && root->val == 0) { - return nullptr; +class Solution { +private: + TreeNode *pruneTree_rec(TreeNode *root) { + if (root == nullptr) { + return nullptr; + } + root->left = pruneTree_rec(root->left); + root->right = pruneTree_rec(root->right); + if (root->left == nullptr && root->right == nullptr && root->val == 0) { + return nullptr; + } + return root; } - return root; -} - -TreeNode *leetcode_814::pruneTree(TreeNode *root) { - return pruneTree_rec(root); - -} +public: + TreeNode *pruneTree(TreeNode *root) { + return pruneTree_rec(root); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/tree/leetcode_814_test.hpp b/algorithm/tree/leetcode_814_test.cpp similarity index 74% rename from algorithm/tree/leetcode_814_test.hpp rename to algorithm/tree/leetcode_814_test.cpp index c22c0912..c30fd909 100644 --- a/algorithm/tree/leetcode_814_test.hpp +++ b/algorithm/tree/leetcode_814_test.cpp @@ -1,14 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_814_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_814_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_814_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_814_TEST_HPP #include #include @@ -16,19 +11,17 @@ Copyright (C) 2022-2023 nanoseeds #include #include #include +#include "leetcode_814.cpp" namespace leetcode_814 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_814 final { - static TreeNode *pruneTree(TreeNode *root); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; TEST_CASE("test_case 1 [test_814]", "[test_814]") { + Solution solution; const TreeNodeLink input{1, TreeNode::No, 0, TreeNode::No, TreeNode::No, 0, 1 @@ -37,10 +30,11 @@ TEST_CASE("test_case 1 [test_814]", "[test_814]") { TreeNode::No, 0, TreeNode::No, 1, TreeNode::No, TreeNode::No // 这里是一处缺陷,两个TreeNode::No本应在左边 }; - const auto output = leetcode_814::pruneTree(input[0]); + const auto output = solution.pruneTree(input[0]); CHECK(TREE_NODE::judge_equal(output, result)); } TEST_CASE("test_case 2 [test_814]", "[test_814]") { + Solution solution; const TreeNodeLink input{1, 0, 0, 0, 0, 0, 1 @@ -49,9 +43,9 @@ TEST_CASE("test_case 2 [test_814]", "[test_814]") { TreeNode::No, 0, TreeNode::No, 1, TreeNode::No, TreeNode::No // 这里是一处缺陷,两个TreeNode::No本应在左边 }; - const auto output = leetcode_814::pruneTree(input[0]); + const auto output = solution.pruneTree(input[0]); CHECK(TREE_NODE::judge_equal(output, result)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_814_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_814_TEST_HPP diff --git a/algorithm/tree/leetcode_872.cpp b/algorithm/tree/leetcode_872.cpp index 14d6ba75..d4895cef 100644 --- a/algorithm/tree/leetcode_872.cpp +++ b/algorithm/tree/leetcode_872.cpp @@ -1,50 +1,61 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_872_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include #include +#include namespace leetcode_872 { -vector getNode(TreeNode *root) { - vector willreturn{}; - for (std::stack ques{{root}}; !ques.empty();) { - const TreeNode *rootnode = ques.top(); - ques.pop(); - if (rootnode->left != nullptr) { - ques.push(rootnode->left); - } - if (rootnode->right != nullptr) { - ques.push(rootnode->right); - } - if (rootnode->left == nullptr && rootnode->right == nullptr) { - willreturn.push_back(rootnode->val); +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif + +using std::vector; + +class Solution { +private: + vector getNode(TreeNode *root) { + vector willreturn{}; + for (std::stack ques{{root}}; !ques.empty();) { + const TreeNode *rootnode = ques.top(); + ques.pop(); + if (rootnode->left != nullptr) { + ques.push(rootnode->left); + } + if (rootnode->right != nullptr) { + ques.push(rootnode->right); + } + if (rootnode->left == nullptr && rootnode->right == nullptr) { + willreturn.push_back(rootnode->val); + } } + return willreturn; } - return willreturn; -} -bool leetcode_872::leafSimilar(TreeNode *root1, TreeNode *root2) { - if (root1 == nullptr && root2 == nullptr) { - return true; - } else if (root1 == nullptr || root2 == nullptr) { - return false; - } - vector val1 = getNode(root1); - vector val2 = getNode(root2); - if (val1.size() != val2.size()) { - return false; - } - for (size_t i{0}, max{val1.size()}; i < max; ++i) { - if (val1[i] != val2[i]) { +public: + bool leafSimilar(TreeNode *root1, TreeNode *root2) { + if (root1 == nullptr && root2 == nullptr) { + return true; + } else if (root1 == nullptr || root2 == nullptr) { return false; } + vector val1 = getNode(root1); + vector val2 = getNode(root2); + if (val1.size() != val2.size()) { + return false; + } + for (size_t i{0}, max{val1.size()}; i < max; ++i) { + if (val1[i] != val2[i]) { + return false; + } + } + return true; } - return true; -} - - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/tree/leetcode_872_test.hpp b/algorithm/tree/leetcode_872_test.cpp similarity index 67% rename from algorithm/tree/leetcode_872_test.hpp rename to algorithm/tree/leetcode_872_test.cpp index f8292c1d..69d384ef 100644 --- a/algorithm/tree/leetcode_872_test.hpp +++ b/algorithm/tree/leetcode_872_test.cpp @@ -1,14 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_872_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_872_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_872_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_872_TEST_HPP #include #include @@ -16,19 +11,17 @@ Copyright (C) 2022-2023 nanoseeds #include #include #include +#include "leetcode_872.cpp" namespace leetcode_872 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_872 final { - static bool leafSimilar(TreeNode *root1, TreeNode *root2); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; TEST_CASE("test_case 1 [test_872]", "[test_872]") { + Solution solution; const TreeNodeLink input1{3, 5, 1, 6, 2, 9, 8, @@ -39,14 +32,15 @@ TEST_CASE("test_case 1 [test_872]", "[test_872]") { 6, 7, 4, 2, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, 9, 8 }; - CHECK(leetcode_872::leafSimilar(input1[0], input2[0])); + CHECK(solution.leafSimilar(input1[0], input2[0])); } TEST_CASE("test_case 2 [test_872]", "[test_872]") { + Solution solution; const TreeNodeLink input1{1, 2, 3}; const TreeNodeLink input2{1, 3, 2}; - CHECK_FALSE(leetcode_872::leafSimilar(input1[0], input2[0])); + CHECK_FALSE(solution.leafSimilar(input1[0], input2[0])); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_872_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_872_TEST_HPP diff --git a/algorithm/tree/leetcode_894.cpp b/algorithm/tree/leetcode_894.cpp index 459337e8..ad285e05 100644 --- a/algorithm/tree/leetcode_894.cpp +++ b/algorithm/tree/leetcode_894.cpp @@ -1,42 +1,54 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_894_test.hpp" -#include +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include namespace leetcode_894 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif + + using std::unordered_map; +using std::vector; -vector rec(int32_t n, const unordered_map> &nodes) { - vector will_return{}; - for (int32_t i{1}; i <= n - 2; i += 2) { - vector left = nodes.at(i); - vector right = nodes.at(n - i - 1); - for (auto j: left) { - for (auto k: right) { - auto *const root = new TreeNode{0}; - root->left = j; - root->right = k; - will_return.push_back(root); +class Solution { +private: + vector rec(int32_t n, const unordered_map> &nodes) { + vector will_return{}; + for (int32_t i{1}; i <= n - 2; i += 2) { + vector left = nodes.at(i); + vector right = nodes.at(n - i - 1); + for (auto j: left) { + for (auto k: right) { + auto *const root = new TreeNode{0}; + root->left = j; + root->right = k; + will_return.push_back(root); + } } } + return will_return; } - return will_return; -} -vector leetcode_894::allPossibleFBT(int32_t n) { - if (n % 2 == 0) { - return {}; - } - unordered_map> nodes{{1, {new TreeNode{0}}}}; - vector will_return{}; - for (int32_t i{3}; i <= n; i += 2) { - nodes[i] = rec(i, nodes); +public: + vector allPossibleFBT(int32_t n) { + if (n % 2 == 0) { + return {}; + } + unordered_map> nodes{{1, {new TreeNode{0}}}}; + vector will_return{}; + for (int32_t i{3}; i <= n; i += 2) { + nodes[i] = rec(i, nodes); + } + return nodes.at(n); } - return nodes.at(n); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_894_test.hpp b/algorithm/tree/leetcode_894_test.cpp similarity index 58% rename from algorithm/tree/leetcode_894_test.hpp rename to algorithm/tree/leetcode_894_test.cpp index 910d4220..646009d5 100644 --- a/algorithm/tree/leetcode_894_test.hpp +++ b/algorithm/tree/leetcode_894_test.cpp @@ -1,14 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_894_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_894_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_894_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_894_TEST_HPP #include #include @@ -16,15 +11,12 @@ Copyright (C) 2022-2023 nanoseeds #include #include #include +#include "leetcode_894.cpp" namespace leetcode_894 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_894 final { - static vector allPossibleFBT(int32_t n); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; @@ -32,4 +24,4 @@ TEST_CASE("test_case 1 [test_894]", "[test_894]") { CHECK(std::true_type::value); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_894_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_894_TEST_HPP diff --git a/algorithm/tree/leetcode_897.cpp b/algorithm/tree/leetcode_897.cpp index 6493bc13..ba1c2f35 100644 --- a/algorithm/tree/leetcode_897.cpp +++ b/algorithm/tree/leetcode_897.cpp @@ -1,42 +1,57 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_897_test.hpp" +#ifdef ALGORITHM_TEST_MACRO + +#include #include +#include + namespace leetcode_897 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; using std::queue; -void getSon(TreeNode *const root, queue &pq) { - if (pq.empty()) { - return; +#endif + + +class Solution { +private: + void getSon(TreeNode *const root, queue &pq) { + if (pq.empty()) { + return; + } + root->left = nullptr; + root->right = pq.front(); + pq.pop(); + getSon(root->right, pq); } - root->left = nullptr; - root->right = pq.front(); - pq.pop(); - getSon(root->right, pq); -} -void rec(TreeNode *const root, queue &pq) { - if (root == nullptr) { - return; + void rec(TreeNode *const root, queue &pq) { + if (root == nullptr) { + return; + } + rec(root->left, pq); + pq.push(root); + rec(root->right, pq); } - rec(root->left, pq); - pq.push(root); - rec(root->right, pq); -} +public: + TreeNode *increasingBST(TreeNode *root) { + queue pq; + rec(root, pq); + if (pq.empty()) { + return nullptr; + } + auto *const rooted = pq.front(); + pq.pop(); + getSon(rooted, pq); + return rooted; + } +}; -TreeNode *leetcode_897::increasingBST(TreeNode *root) { - queue pq; - rec(root, pq); - auto *const rooted = pq.front(); - pq.pop(); - getSon(rooted, pq); - return rooted; -} +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/tree/leetcode_897_test.hpp b/algorithm/tree/leetcode_897_test.cpp similarity index 71% rename from algorithm/tree/leetcode_897_test.hpp rename to algorithm/tree/leetcode_897_test.cpp index 615a3d66..b97d18c5 100644 --- a/algorithm/tree/leetcode_897_test.hpp +++ b/algorithm/tree/leetcode_897_test.cpp @@ -1,14 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_897_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_897_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_897_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_897_TEST_HPP #include #include @@ -16,27 +11,24 @@ Copyright (C) 2022-2023 nanoseeds #include #include #include +#include "leetcode_897.cpp" namespace leetcode_897 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_897 final { - static TreeNode *increasingBST(TreeNode *root); -}; - - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; TEST_CASE("test_case 1 [test_897]", "[test_897]") { + Solution solution; const TreeNodeLink input{ 5, 3, 6, 2, 4, TreeNode::No, 8, 1, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, 7, 9 }; - const auto *node = leetcode_897::increasingBST(input[0]); + auto *node = solution.increasingBST(input[0]); const vector nodes{1, 2, 3, 4, 5, 6, 7, 8, 9}; for (const auto va: nodes) { CHECK(node->val == va); @@ -46,11 +38,12 @@ TEST_CASE("test_case 1 [test_897]", "[test_897]") { } TEST_CASE("test_case 2 [test_897]", "[test_897]") { + Solution solution; const TreeNodeLink input{ 5, 1, 7 }; - const auto *node = leetcode_897::increasingBST(input[0]); + auto *node = solution.increasingBST(input[0]); const vector nodes{1, 5, 7}; for (const auto va: nodes) { CHECK(node->val == va); @@ -59,4 +52,4 @@ TEST_CASE("test_case 2 [test_897]", "[test_897]") { } } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_897_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_897_TEST_HPP diff --git a/algorithm/tree/leetcode_938.cpp b/algorithm/tree/leetcode_938.cpp index 7bdbb1d0..ba094c54 100644 --- a/algorithm/tree/leetcode_938.cpp +++ b/algorithm/tree/leetcode_938.cpp @@ -1,28 +1,35 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_938_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_938 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -int32_t leetcode_938::rangeSumBST(TreeNode *root, int32_t low, int32_t high) { - if (root == nullptr) - return 0; - int32_t willreturn{0}; - willreturn += ((root->val >= low) && (root->val <= high)) ? root->val : 0; - if (root->val >= high) { - willreturn += rangeSumBST(root->left, low, high); - } else if (root->val > low && root->val < high) { - willreturn += rangeSumBST(root->left, low, high); - willreturn += rangeSumBST(root->right, low, high); - } else { - willreturn += rangeSumBST(root->right, low, high); +class Solution { +public: + int32_t rangeSumBST(TreeNode *root, int32_t low, int32_t high) { + if (root == nullptr) + return 0; + int32_t willreturn{0}; + willreturn += ((root->val >= low) && (root->val <= high)) ? root->val : 0; + if (root->val >= high) { + willreturn += rangeSumBST(root->left, low, high); + } else if (root->val > low && root->val < high) { + willreturn += rangeSumBST(root->left, low, high); + willreturn += rangeSumBST(root->right, low, high); + } else { + willreturn += rangeSumBST(root->right, low, high); + } + return willreturn; } - return willreturn; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/tree/leetcode_938_test.hpp b/algorithm/tree/leetcode_938_test.cpp similarity index 64% rename from algorithm/tree/leetcode_938_test.hpp rename to algorithm/tree/leetcode_938_test.cpp index c30f67cb..f7f1a34e 100644 --- a/algorithm/tree/leetcode_938_test.hpp +++ b/algorithm/tree/leetcode_938_test.cpp @@ -1,14 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_938_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_938_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_938_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_938_TEST_HPP #include #include @@ -16,19 +11,17 @@ Copyright (C) 2022-2023 nanoseeds #include #include #include +#include "leetcode_938.cpp" namespace leetcode_938 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_938 final { - static int32_t rangeSumBST(TreeNode *root, int32_t low, int32_t high); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; TEST_CASE("test_case 1 [test_938]", "[test_938]") { + Solution solution; const TreeNodeLink input{ 10, 5, 15, @@ -36,10 +29,11 @@ TEST_CASE("test_case 1 [test_938]", "[test_938]") { }; static constexpr const auto low{7}, high{15}; static constexpr const auto result{32}; - CHECK(result == leetcode_938::rangeSumBST(input[0], low, high)); + CHECK(result == solution.rangeSumBST(input[0], low, high)); } TEST_CASE("test_case 2 [test_938]", "[test_938]") { + Solution solution; const TreeNodeLink input{ 10, 5, 15, @@ -48,7 +42,7 @@ TEST_CASE("test_case 2 [test_938]", "[test_938]") { }; static constexpr const auto low{6}, high{10}; static constexpr const auto result{23}; - CHECK(result == leetcode_938::rangeSumBST(input[0], low, high)); + CHECK(result == solution.rangeSumBST(input[0], low, high)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_938_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_938_TEST_HPP diff --git a/algorithm/tree/leetcode_94.cpp b/algorithm/tree/leetcode_94.cpp index da8b2a2a..5718804e 100644 --- a/algorithm/tree/leetcode_94.cpp +++ b/algorithm/tree/leetcode_94.cpp @@ -1,24 +1,18 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_94_test.hpp" +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include "traverse.cpp" namespace leetcode_94 { using namespace Tree_Traverse; -vector leetcode_94::inorderTraversalIter(TreeNode *root) { +vector inorderTraversalIter(TreeNode *root) { vector will_return{}; const auto function = [&will_return](const TreeNode *tn) -> void { will_return.push_back(tn->val); }; iter::in(root, function); return will_return; } -vector leetcode_94::inorderTraversal(TreeNode *root) { +vector inorderTraversal(TreeNode *root) { vector will_return{}; const auto function = [&will_return](const TreeNode *tn) -> void { will_return.push_back(tn->val); }; rec::in(root, function); diff --git a/algorithm/tree/leetcode_94_test.hpp b/algorithm/tree/leetcode_94_test.cpp similarity index 77% rename from algorithm/tree/leetcode_94_test.hpp rename to algorithm/tree/leetcode_94_test.cpp index e4ef54d4..21e1ac65 100644 --- a/algorithm/tree/leetcode_94_test.hpp +++ b/algorithm/tree/leetcode_94_test.cpp @@ -1,19 +1,15 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@description 中序遍历 //@Plan 数据结构入门 Day10 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_94_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_94_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_94_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_94_TEST_HPP #include +#include "leetcode_94.cpp" #include #include #include @@ -23,12 +19,6 @@ namespace leetcode_94 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_94 { - static vector inorderTraversal(TreeNode *root); - - static vector inorderTraversalIter(TreeNode *root); -}; - using Catch::Matchers::Equals; using TreeNodeLink = TREE_NODE::TreeNodeLink; @@ -54,4 +44,4 @@ TEST_CASE("test_case 2 [test_94]", "[test_94]") { CHECK_THAT(result, Equals(leetcode_94::inorderTraversalIter(input[0]))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_94_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_94_TEST_HPP diff --git a/algorithm/tree/leetcode_95.cpp b/algorithm/tree/leetcode_95.cpp index ad4a8625..800234ef 100644 --- a/algorithm/tree/leetcode_95.cpp +++ b/algorithm/tree/leetcode_95.cpp @@ -1,41 +1,47 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_95_test.hpp" - +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_95 { -vector generateTrees_rec(int32_t left, int32_t right) { - if (left > right) { - return vector{nullptr}; - } else if (left == right) { - return vector{new TreeNode(left)}; - } - vector will_return; - for (int i = left; i <= right; i++) { - const auto temp = generateTrees_rec(left, i - 1); - for (auto const &j: temp) { - const auto temp2 = generateTrees_rec(i + 1, right); - for (auto const &k: temp2) { - const auto will_insert = new TreeNode(i); - will_insert->left = j; - will_insert->right = k; - will_return.emplace_back(will_insert); - //will_return.emplace_back(i,j,k); +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif + +class Solution { +private: + vector generateTrees_rec(int32_t left, int32_t right) { + if (left > right) { + return vector{nullptr}; + } else if (left == right) { + return vector{new TreeNode(left)}; + } + vector will_return; + for (int i = left; i <= right; i++) { + const auto temp = generateTrees_rec(left, i - 1); + for (auto const &j: temp) { + const auto temp2 = generateTrees_rec(i + 1, right); + for (auto const &k: temp2) { + const auto will_insert = new TreeNode(i); + will_insert->left = j; + will_insert->right = k; + will_return.emplace_back(will_insert); + } } } + return will_return; } - return will_return; -} -vector leetcode_95::generateTrees(int32_t n) { - if (n == 0) { - return vector{}; +public: + vector generateTrees(int32_t n) { + if (n == 0) { + return vector{}; + } + return generateTrees_rec(1, n); } - return generateTrees_rec(1, n); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_95_test.hpp b/algorithm/tree/leetcode_95_test.cpp similarity index 69% rename from algorithm/tree/leetcode_95_test.hpp rename to algorithm/tree/leetcode_95_test.cpp index 36f396de..cc96ec63 100644 --- a/algorithm/tree/leetcode_95_test.hpp +++ b/algorithm/tree/leetcode_95_test.cpp @@ -1,39 +1,29 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_95_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_95_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_95_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_95_TEST_HPP #include -#include +#include "leetcode_95.cpp" #include -#include -#include namespace leetcode_95 { using std::vector; -using TreeNode = TREE_NODE::TreeNode; using TreeNodeLink = TREE_NODE::TreeNodeLink; using Catch::Matchers::Equals; -struct leetcode_95 { - static vector generateTrees(int32_t n); -}; - TEST_CASE("test_case 1 [test_95]", "[test_95]") { - const auto three = leetcode_95::generateTrees(0); + Solution solution; + const auto three = solution.generateTrees(0); CHECK_THAT(three, Equals({})); const TreeNodeLink link1{three}; } TEST_CASE("test_case 2 [test_95]", "[test_95]") { + Solution solution; const vector> result{ {1, TreeNode::No, 2, TreeNode::No, 3, TreeNode::No, TreeNode::No}, {1, TreeNode::No, 3, 2, TreeNode::No, TreeNode::No, TreeNode::No}, @@ -41,7 +31,7 @@ TEST_CASE("test_case 2 [test_95]", "[test_95]") { {3, 1, TreeNode::No, TreeNode::No, 2, TreeNode::No, TreeNode::No}, {3, 2, TreeNode::No, 1, TreeNode::No, TreeNode::No, TreeNode::No}, }; - const auto three = leetcode_95::generateTrees(3); + const auto three = solution.generateTrees(3); static constexpr const auto length{5}; CHECK(length == three.size()); for (int32_t i{0}; i < length; ++i) { @@ -52,4 +42,4 @@ TEST_CASE("test_case 2 [test_95]", "[test_95]") { } } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_95_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_95_TEST_HPP diff --git a/algorithm/tree/leetcode_96.cpp b/algorithm/tree/leetcode_96.cpp index 5e5df44a..371416a6 100644 --- a/algorithm/tree/leetcode_96.cpp +++ b/algorithm/tree/leetcode_96.cpp @@ -1,36 +1,37 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_96_test.hpp" - +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_96 { +using std::unordered_map; +#endif -int32_t leetcode_96::numTrees(int32_t n) { - static unordered_map umap; - if (n <= 1) { - return 1; - } else if (n == 2) { - return 2; - } - if (umap.count(n) != 0) { - return umap[n]; - } - int32_t will_return{0}; - for (int32_t i{0}; i < n; i++) { - const auto fir{numTrees(i)}; - umap[i] = fir; - const auto sec{numTrees(n - i - 1)}; - umap[n - i - 1] = sec; - will_return += (fir * sec); +class Solution { +public: + int32_t numTrees(int32_t n) { + static unordered_map umap; + if (n <= 1) { + return 1; + } else if (n == 2) { + return 2; + } + if (umap.count(n) != 0) { + return umap[n]; + } + int32_t will_return{0}; + for (int32_t i{0}; i < n; i++) { + const auto fir{numTrees(i)}; + umap[i] = fir; + const auto sec{numTrees(n - i - 1)}; + umap[n - i - 1] = sec; + will_return += (fir * sec); + } + // 这题需要用DP,关键在于 [m,m+k]和[n,n+k] 这两个范围的节点形成的子树完全同构, 数量是一致的,可以复用 + return will_return; } - // 这题需要用DP,关键在于 [m,m+k]和[n,n+k] 这两个范围的节点形成的子树完全同构, 数量是一致的,可以复用 - return will_return; -} - +}; constexpr std::array numTreesFunc() { std::array arr{1, 1, 2}; for (size_t i{3}, arr_size{arr.size()}; i < arr_size; i++) { @@ -43,10 +44,12 @@ constexpr std::array numTreesFunc() { return arr; } -int32_t leetcode_96::numTreesConstexpr(int32_t n) { +int32_t numTreesConstexpr(int32_t n) { // ensure function run in compile time static constexpr const std::array arr{numTreesFunc()}; // constexpr,很神奇吧 return arr[n]; } +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_965.cpp b/algorithm/tree/leetcode_965.cpp index f5ec26bc..aa554022 100644 --- a/algorithm/tree/leetcode_965.cpp +++ b/algorithm/tree/leetcode_965.cpp @@ -1,47 +1,58 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_965_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include #include +#include +#include namespace leetcode_965 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; using std::stack; -bool leetcode_965::isUnivalTreeRec(TreeNode *root) { - for (stack sta{{root}}; !sta.empty();) { - const TreeNode *now = sta.top(); - sta.pop(); - const auto lambda = [now, &sta](TreeNode const *son) { - if (son != nullptr) { - if (now->val != son->val) { - return false; +#endif + + +class Solution { +public: + bool isUnivalTreeRec(TreeNode *root) { + for (stack sta{{root}}; !sta.empty();) { + const TreeNode *now = sta.top(); + sta.pop(); + const auto lambda = [now, &sta](TreeNode const *son) { + if (son != nullptr) { + if (now->val != son->val) { + return false; + } + sta.push(son); } - sta.push(son); + return true; + }; + if (!lambda(now->left) || !lambda(now->right)) { + return false; } - return true; - }; - if (!lambda(now->left) || !lambda(now->right)) { - return false; } + return true; } - return true; -} -bool leetcode_965::isUnivalTreeIter(TreeNode *root) { - const std::function judgement = - [&judgement](TreeNode *const root, int32_t value) { - if (root == nullptr) { - return true; - } - return ( - (root->val == value) && - judgement(root->left, root->val) && - judgement(root->right, root->val)); - }; - return judgement(root, root->val); -} + bool isUnivalTreeIter(TreeNode *root) { + const std::function judgement = + [&judgement](TreeNode *const root, int32_t value) { + if (root == nullptr) { + return true; + } + return ( + (root->val == value) && + judgement(root->left, root->val) && + judgement(root->right, root->val)); + }; + return judgement(root, root->val); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_965_test.hpp b/algorithm/tree/leetcode_965_test.cpp similarity index 52% rename from algorithm/tree/leetcode_965_test.hpp rename to algorithm/tree/leetcode_965_test.cpp index 931620a0..0579d6cd 100644 --- a/algorithm/tree/leetcode_965_test.hpp +++ b/algorithm/tree/leetcode_965_test.cpp @@ -1,51 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_965_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_965_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_965_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_965_TEST_HPP #include #include #include #include #include +#include "leetcode_965.cpp" namespace leetcode_965 { using TreeNode = TREE_NODE::TreeNode; -struct leetcode_965 final { - static bool isUnivalTreeRec(TreeNode *root); - - static bool isUnivalTreeIter(TreeNode *root); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_965]", "[test_965]") { + Solution solution; const TreeNodeLink input{ 1, 1, 1, 1, 1, TreeNode::No, 2 }; - CHECK_FALSE(leetcode_965::isUnivalTreeRec(input[0])); - CHECK_FALSE(leetcode_965::isUnivalTreeIter(input[0])); + CHECK_FALSE(solution.isUnivalTreeRec(input[0])); + CHECK_FALSE(solution.isUnivalTreeIter(input[0])); } TEST_CASE("test_case 2 [test_965]", "[test_965]") { + Solution solution; const TreeNodeLink input{ 1, 1, 1, 1, 1, 1, 1, 1, TreeNode::No, 1 }; - CHECK(leetcode_965::isUnivalTreeRec(input[0])); - CHECK(leetcode_965::isUnivalTreeIter(input[0])); + CHECK(solution.isUnivalTreeRec(input[0])); + CHECK(solution.isUnivalTreeIter(input[0])); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_965_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_965_TEST_HPP diff --git a/algorithm/tree/leetcode_96_test.cpp b/algorithm/tree/leetcode_96_test.cpp new file mode 100644 index 00000000..3660e83b --- /dev/null +++ b/algorithm/tree/leetcode_96_test.cpp @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +//@Tag tree +//@Tag 树 +//@Plan 动态规划入门 Day11 +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_96_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_96_TEST_HPP + +#include +#include "leetcode_96.cpp" + +namespace leetcode_96 { + +using std::unordered_map; + +TEST_CASE("test_case 1 [test_96]", "[test_96]") { + Solution solution; + static constexpr const auto input{1}; + static constexpr const auto result{1}; + CHECK(result == solution.numTrees(input)); + CHECK(result == numTreesConstexpr(input)); +} + +TEST_CASE("test_case 2 [test_96]", "[test_96]") { + Solution solution; + static constexpr const auto input{3}; + static constexpr const auto result{5}; + CHECK(result == solution.numTrees(input)); + CHECK(result == numTreesConstexpr(input)); +} + +TEST_CASE("test_case 3 [test_96]", "[test_96]") { + Solution solution; + static constexpr const auto input{19}; + static constexpr const auto result{1767263190}; + CHECK(result == solution.numTrees(input)); + CHECK(result == numTreesConstexpr(input)); +} +} +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_96_TEST_HPP diff --git a/algorithm/tree/leetcode_96_test.hpp b/algorithm/tree/leetcode_96_test.hpp deleted file mode 100644 index e7d62047..00000000 --- a/algorithm/tree/leetcode_96_test.hpp +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -//@Tag tree -//@Tag 树 -//@Plan 动态规划入门 Day11 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_96_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_96_TEST_HPP - -#include -#include - -namespace leetcode_96 { - -using std::unordered_map; - -struct leetcode_96 { - static int32_t numTrees(int32_t n); - - static int32_t numTreesConstexpr(int32_t n); -}; - - -TEST_CASE("test_case 1 [test_96]", "[test_96]") { - static constexpr const auto input{1}; - static constexpr const auto result{1}; - CHECK(result == leetcode_96::numTrees(input)); - CHECK(result == leetcode_96::numTreesConstexpr(input)); -} - -TEST_CASE("test_case 2 [test_96]", "[test_96]") { - static constexpr const auto input{3}; - static constexpr const auto result{5}; - CHECK(result == leetcode_96::numTrees(input)); - CHECK(result == leetcode_96::numTreesConstexpr(input)); -} - -TEST_CASE("test_case 3 [test_96]", "[test_96]") { - static constexpr const auto input{19}; - static constexpr const auto result{1767263190}; - CHECK(result == leetcode_96::numTrees(input)); - CHECK(result == leetcode_96::numTreesConstexpr(input)); -} -} -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_96_TEST_HPP diff --git a/algorithm/tree/leetcode_98.cpp b/algorithm/tree/leetcode_98.cpp index 9086be1a..76c3e22b 100644 --- a/algorithm/tree/leetcode_98.cpp +++ b/algorithm/tree/leetcode_98.cpp @@ -1,41 +1,44 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template -Copyright (C) 2020-2023 nanoseeds -*/ -#include "leetcode_98_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include namespace leetcode_98 { - -bool smaller(TreeNode *root, int32_t value); - -bool bigger(TreeNode *root, int32_t value); - -bool leetcode_98::isValidBST(TreeNode *root) { - if (root == nullptr) { - return true; +using std::vector; +using TreeNode = TREE_NODE::TreeNode; + +#endif + +class Solution { +private: + bool smaller(TreeNode *root, int32_t value) { + if (root == nullptr) { + return true; + } + return root->val < value && + smaller(root->right, value) && smaller(root->left, root->val) && + bigger(root->right, root->val); } - return smaller(root->left, root->val) && bigger(root->right, root->val); -} -bool smaller(TreeNode *root, int32_t value) { - if (root == nullptr) { - return true; + bool bigger(TreeNode *root, int32_t value) { + if (root == nullptr) { + return true; + } + return root->val > value && + smaller(root->left, root->val) && + bigger(root->left, value) && bigger(root->right, root->val); } - return root->val < value && - smaller(root->right, value) && smaller(root->left, root->val) && - bigger(root->right, root->val); -} -bool bigger(TreeNode *root, int32_t value) { - if (root == nullptr) { - return true; +public: + bool isValidBST(TreeNode *root) { + if (root == nullptr) { + return true; + } + return smaller(root->left, root->val) && bigger(root->right, root->val); } - return root->val > value && - smaller(root->left, root->val) && - bigger(root->left, value) && bigger(root->right, root->val); -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_98_test.hpp b/algorithm/tree/leetcode_98_test.cpp similarity index 56% rename from algorithm/tree/leetcode_98_test.hpp rename to algorithm/tree/leetcode_98_test.cpp index 217ee0f0..80ac3847 100644 --- a/algorithm/tree/leetcode_98_test.hpp +++ b/algorithm/tree/leetcode_98_test.cpp @@ -1,38 +1,32 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@Plan 数据结构入门 Day14 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_98_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_98_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_98_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_98_TEST_HPP #include #include #include +#include "leetcode_98.cpp" namespace leetcode_98 { using TreeNode = TREE_NODE::TreeNode; using TreeNodeLink = TREE_NODE::TreeNodeLink; -struct leetcode_98 { - static bool isValidBST(TreeNode *root); -}; - TEST_CASE("test_case 1 [test_98]", "[test_98]") { + Solution solution; const TreeNodeLink vec{2, 1, 3}; - CHECK(leetcode_98::isValidBST(vec[0])); + CHECK(solution.isValidBST(vec[0])); } TEST_CASE("test_case 2 [test_98]", "[test_98]") { + Solution solution; const TreeNodeLink vec{5, 1, 4, TreeNode::No, TreeNode::No, 3, 6}; - CHECK_FALSE(leetcode_98::isValidBST(vec[0])); + CHECK_FALSE(solution.isValidBST(vec[0])); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_98_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_98_TEST_HPP diff --git a/algorithm/tree/leetcode_993.cpp b/algorithm/tree/leetcode_993.cpp index d0ea9498..e5db4e02 100644 --- a/algorithm/tree/leetcode_993.cpp +++ b/algorithm/tree/leetcode_993.cpp @@ -1,44 +1,54 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds -*/ -#include "leetcode_993_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include #include +#include +#include namespace leetcode_993 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; using std::queue; +#endif -bool leetcode_993::isCousins(TreeNode *root, int x, int y) { - for (queue now{{root}}, next{}; !now.empty(); std::swap(now, next)) { - for (bool getX{false}, getY{false}; !now.empty();) { - const auto head = now.front(); - now.pop(); - if (head->left != nullptr && head->right != nullptr) { - if ((head->left->val == x && head->right->val == y) || - (head->left->val == y && head->right->val == x)) { - return false; +class Solution { +public: + + + bool isCousins(TreeNode *root, int x, int y) { + for (queue now{{root}}, next{}; !now.empty(); std::swap(now, next)) { + for (bool getX{false}, getY{false}; !now.empty();) { + const auto head = now.front(); + now.pop(); + if (head->left != nullptr && head->right != nullptr) { + if ((head->left->val == x && head->right->val == y) || + (head->left->val == y && head->right->val == x)) { + return false; + } } - } - const auto func = [&next, x, y, &getX, &getY](const TreeNode*const pointer) { - if (pointer != nullptr) { - next.push(pointer); - if (pointer->val == x) { - getX = true; - } else if (pointer->val == y) { - getY = true; + const auto func = [&next, x, y, &getX, &getY](const TreeNode*const pointer) { + if (pointer != nullptr) { + next.push(pointer); + if (pointer->val == x) { + getX = true; + } else if (pointer->val == y) { + getY = true; + } } + }; + func(head->left); + func(head->right); + if (getX && getY) { + return true; } - }; - func(head->left); - func(head->right); - if (getX && getY) { - return true; } } + return false; } - return false; -} +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_993_test.hpp b/algorithm/tree/leetcode_993_test.cpp similarity index 65% rename from algorithm/tree/leetcode_993_test.hpp rename to algorithm/tree/leetcode_993_test.cpp index 0779098e..7a121b2b 100644 --- a/algorithm/tree/leetcode_993_test.hpp +++ b/algorithm/tree/leetcode_993_test.cpp @@ -1,58 +1,53 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_993_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_993_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_993_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_993_TEST_HPP #include #include #include #include #include +#include "leetcode_993.cpp" namespace leetcode_993 { using TreeNode = TREE_NODE::TreeNode; -struct leetcode_993 final { - static bool isCousins(TreeNode *root, int x, int y); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; TEST_CASE("test_case 1 [test_993]", "[test_993]") { + Solution solution; const TreeNodeLink input{ 1, 2, 3, 4, TreeNode::No, TreeNode::No, TreeNode::No }; static constexpr const auto x{4}, y{3}; - CHECK_FALSE(leetcode_993::isCousins(input[0], x, y)); + CHECK_FALSE(solution.isCousins(input[0], x, y)); } TEST_CASE("test_case 3 [test_993]", "[test_993]") { + Solution solution; const TreeNodeLink input{ 1, 2, 3, TreeNode::No, 4, TreeNode::No, 5 }; static constexpr const auto x{5}, y{4}; - CHECK(leetcode_993::isCousins(input[0], x, y)); + CHECK(solution.isCousins(input[0], x, y)); } TEST_CASE("test_case 2 [test_993]", "[test_993]") { + Solution solution; const TreeNodeLink input{ 1, 2, 3, TreeNode::No, 4, TreeNode::No }; static constexpr const auto x{5}, y{4}; - CHECK_FALSE(leetcode_993::isCousins(input[0], x, y)); + CHECK_FALSE(solution.isCousins(input[0], x, y)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_993_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_TREE_LEETCODE_993_TEST_HPP diff --git a/algorithm/tree/leetcode_so_26.cpp b/algorithm/tree/leetcode_so_26.cpp index c66d6acd..cc869fe4 100644 --- a/algorithm/tree/leetcode_so_26.cpp +++ b/algorithm/tree/leetcode_so_26.cpp @@ -1,27 +1,33 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_so_26_test.hpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include namespace leetcode_so_26 { -bool in(TreeNode *A, TreeNode *B) { - if (B == nullptr) { - return true; - } else if (A == nullptr) { - return false; - } - return A->val == B->val && in(A->left, B->left) && in(A->right, B->right); -} +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +#endif -bool leetcode_so_26::isSubStructure(TREE_NODE::TreeNode *A, TREE_NODE::TreeNode *B) { - if (B == nullptr || A == nullptr) { - return false; +class Solution { +private: + bool in(TreeNode *A, TreeNode *B) { + if (B == nullptr) { + return true; + } else if (A == nullptr) { + return false; + } + return A->val == B->val && in(A->left, B->left) && in(A->right, B->right); } - return in(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B); -} - +public: + bool isSubStructure(TreeNode *A, TreeNode *B) { + if (B == nullptr || A == nullptr) { + return false; + } + return in(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif \ No newline at end of file diff --git a/algorithm/tree/leetcode_so_26_test.hpp b/algorithm/tree/leetcode_so_26_test.cpp similarity index 60% rename from algorithm/tree/leetcode_so_26_test.hpp rename to algorithm/tree/leetcode_so_26_test.cpp index 6e3e8e89..08a275dc 100644 --- a/algorithm/tree/leetcode_so_26_test.hpp +++ b/algorithm/tree/leetcode_so_26_test.cpp @@ -1,53 +1,46 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 //@Plan 剑指OfferII-I Day07 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_SO_26_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_SO_26_TEST_HPP #include #include #include +#include #include #include -#include +#include "leetcode_so_26.cpp" namespace leetcode_so_26 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_so_26 final { - static bool isSubStructure(TreeNode *A, TreeNode *B); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; using Catch::Matchers::Equals; TEST_CASE("test_case 1 [test_so_26]", "[test_so_26]") { + Solution solution; const TreeNodeLink input{3, 4, 5, 1, 2}, input2{4, 1}; - CHECK(leetcode_so_26::isSubStructure(input[0], input2[0])); + CHECK(solution.isSubStructure(input[0], input2[0])); } TEST_CASE("test_case 2 [test_so_26]", "[test_so_26]") { + Solution solution; const TreeNodeLink input{1, 0, 1, -4, -3}, input2{1, -4}; - CHECK_FALSE(leetcode_so_26::isSubStructure(input[0], input2[0])); + CHECK_FALSE(solution.isSubStructure(input[0], input2[0])); } TEST_CASE("test_case 3 [test_so_26]", "[test_so_26]") { + Solution solution; const TreeNodeLink input{1, 2, 3, 4}, input2{3}; - CHECK(leetcode_so_26::isSubStructure(input[0], input2[0])); + CHECK(solution.isSubStructure(input[0], input2[0])); } TEST_CASE("test_case 4 [test_so_26]", "[test_so_26]") { + Solution solution; const TreeNodeLink input{10, 12, 6, 8, 3, 11}, input2{10, 12, 6, 8}; - CHECK(leetcode_so_26::isSubStructure(input[0], input2[0])); + CHECK(solution.isSubStructure(input[0], input2[0])); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_SO_26_TEST_HPP diff --git a/algorithm/tree/leetcode_so_32.cpp b/algorithm/tree/leetcode_so_32.cpp index 5c803f6a..13c03951 100644 --- a/algorithm/tree/leetcode_so_32.cpp +++ b/algorithm/tree/leetcode_so_32.cpp @@ -1,58 +1,64 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_so_32_test.hpp" -#include "traverse.cpp" +// SPDX-FileCopyrightText: 2022-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include #include +#include +#include +#include "traverse.cpp" namespace leetcode_so_32 { -using std::queue; +using std::vector; +using TreeNode = TREE_NODE::TreeNode; using namespace Tree_Traverse; +#endif -vector leetcode_so_32::levelOrderFst(TreeNode *root) { - if (root == nullptr) { - return {}; +class Solution { + public: + std::vector levelOrderFst(TreeNode *root) { + if (root == nullptr) { + return {}; + } + vector will_return{}; + const auto func = [&will_return](const auto node) { + will_return.push_back(node->val); + }; + iter::level(root, func); + return will_return; } - vector will_return{}; - const auto func = [&will_return](const auto node) { - will_return.push_back(node->val); - }; - iter::level(root, func); - return will_return; -} -vector> leetcode_so_32::levelOrderTrd(TreeNode *root) { - if (root == nullptr) { - return {}; - } - vector> will_return{}; - bool shift{true}; - for (queue now{{root}}, next{}; !now.empty();) { - vector line{}; - while (!now.empty()) { - const auto *const head = now.front(); - now.pop(); - line.push_back(head->val); - if (head->left != nullptr) { - next.push(head->left); + std::vector> levelOrderTrd(TreeNode *root) { + if (root == nullptr) { + return {}; + } + vector> will_return{}; + bool shift{true}; + for (queue now{{root}}, next{}; !now.empty();) { + vector line{}; + while (!now.empty()) { + const auto *const head = now.front(); + now.pop(); + line.push_back(head->val); + if (head->left != nullptr) { + next.push(head->left); + } + if (head->right != nullptr) { + next.push(head->right); + } } - if (head->right != nullptr) { - next.push(head->right); + if (shift) { + will_return.emplace_back(line.begin(), line.end()); + } else { + will_return.emplace_back(line.rbegin(), line.rend()); } + shift = !shift; + std::swap(now, next); } - if (shift) { - will_return.emplace_back(line.begin(), line.end()); - } else { - will_return.emplace_back(line.rbegin(), line.rend()); - } - shift = !shift; - std::swap(now, next); + return will_return; } - return will_return; -} - +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_so_32_test.hpp b/algorithm/tree/leetcode_so_32_test.cpp similarity index 62% rename from algorithm/tree/leetcode_so_32_test.hpp rename to algorithm/tree/leetcode_so_32_test.cpp index 33c2e955..2bc04bb5 100644 --- a/algorithm/tree/leetcode_so_32_test.hpp +++ b/algorithm/tree/leetcode_so_32_test.cpp @@ -1,54 +1,42 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 //@Plan 剑指OfferII-I Day06 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_SO_32_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_SO_32_TEST_HPP #include #include #include +#include #include #include -#include +#include "leetcode_so_32.cpp" namespace leetcode_so_32 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_so_32 final { - static vector levelOrderFst(TreeNode *root); - - // static vector levelOrderSnd(TreeNode *root); // same with 102 - static vector> levelOrderTrd(TreeNode *root); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; using Catch::Matchers::Equals; TEST_CASE("test_case 1-1 [test_so_32]", "[test_so_32]") { + Solution solution; const TreeNodeLink input{3, 9, 20, TreeNode::No, TreeNode::No, 15, 7,}; const vector results{3, 9, 20, 15, 7}; - CHECK_THAT(results, Equals(leetcode_so_32::levelOrderFst(input[0]))); + CHECK_THAT(results, Equals(solution.levelOrderFst(input[0]))); } TEST_CASE("test_case 3-1 [test_so_32]", "[test_so_32]") { + Solution solution; const TreeNodeLink input{3, 9, 20, TreeNode::No, TreeNode::No, 15, 7,}; const vector> results{{3}, {20, 9}, {15, 7}}; - CHECK_THAT(results, Equals(leetcode_so_32::levelOrderTrd(input[0]))); + CHECK_THAT(results, Equals(solution.levelOrderTrd(input[0]))); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_SO_32_TEST_HPP diff --git a/algorithm/tree/leetcode_so_54.cpp b/algorithm/tree/leetcode_so_54.cpp index 780d286d..b3f567c0 100644 --- a/algorithm/tree/leetcode_so_54.cpp +++ b/algorithm/tree/leetcode_so_54.cpp @@ -1,32 +1,40 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022 nanoseeds - -*/ -#include "leetcode_so_54_test.hpp" +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include #include "traverse.cpp" - namespace leetcode_so_54 { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; using namespace Tree_Traverse; +#endif -int32_t leetcode_so_54::kthLargest(TreeNode *root, int32_t k) { - vector countVec; - const auto functionPre = [&countVec](const TreeNode *tn) -> void { - countVec.push_back(tn->val); - }; - iter::in(root, functionPre); - const auto netElements = countVec.size(); - vector element; - static size_t count{0}; - const auto function = [&element, k, netElements](const TreeNode *tn) -> void { - ++count; - if (count + k == netElements + 1) { element.push_back(tn->val); } - }; - iter::in(root, function); - count = 0; - return element.front(); -} - +class Solution { + public: + int kthLargest(TreeNode *root, int k) { + vector countVec; + const auto functionPre = [&countVec](const TreeNode *tn) -> void { + countVec.push_back(tn->val); + }; + iter::in(root, functionPre); + const auto netElements = countVec.size(); + vector element; + static size_t count{0}; + const auto function = [&element, k, netElements](const TreeNode *tn) -> void { + ++count; + if (count + k == netElements + 1) { + element.push_back(tn->val); + } + }; + iter::in(root, function); + count = 0; + return element.front(); + } +}; +#ifdef ALGORITHM_TEST_MACRO } +#endif diff --git a/algorithm/tree/leetcode_so_54_test.hpp b/algorithm/tree/leetcode_so_54_test.cpp similarity index 67% rename from algorithm/tree/leetcode_so_54_test.hpp rename to algorithm/tree/leetcode_so_54_test.cpp index 0b2fa2ce..26223231 100644 --- a/algorithm/tree/leetcode_so_54_test.hpp +++ b/algorithm/tree/leetcode_so_54_test.cpp @@ -1,52 +1,43 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds //@Tag tree //@Tag 树 //@Plan 剑指OfferII-I Day15 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_SO_54_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_SO_54_TEST_HPP #include #include #include +#include #include #include -#include +#include "leetcode_so_54.cpp" namespace leetcode_so_54 { using std::vector; using TreeNode = TREE_NODE::TreeNode; -struct leetcode_so_54 final { - static int32_t kthLargest(TreeNode *root, int32_t k); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; using TREE_NODE::numToTree; using Catch::Matchers::Equals; TEST_CASE("test_case 1 [test_so_54]", "[test_so_54]") { + Solution solution; const TreeNodeLink input{3, 1, 4, TreeNode::No, 2}; static constexpr const auto k{1}; static constexpr const auto output{4}; - CHECK(output == leetcode_so_54::kthLargest(input[0], k)); + CHECK(output == solution.kthLargest(input[0], k)); } TEST_CASE("test_case 2 [test_so_54]", "[test_so_54]") { + Solution solution; const TreeNodeLink input{5, 3, 6, 2, 4, TreeNode::No, TreeNode::No, 1}; static constexpr const auto k{3}; static constexpr const auto output{4}; - CHECK(output == leetcode_so_54::kthLargest(input[0], k)); + CHECK(output == solution.kthLargest(input[0], k)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_SO_54_TEST_HPP diff --git a/algorithm/tree/leetcode_unknown.cpp b/algorithm/tree/leetcode_unknown.cpp new file mode 100644 index 00000000..3cdc14f3 --- /dev/null +++ b/algorithm/tree/leetcode_unknown.cpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO +#include +#include +#include +#include +#include "traverse.cpp" +namespace leetcode_unknown { +using std::vector; +using TreeNode = TREE_NODE::TreeNode; +using namespace Tree_Traverse; +#endif + +class Solution { + public: + bool findTarget(TreeNode *root, int k) { + vector targets{}; + const auto func = [&targets](const TreeNode *tn) -> void { targets.push_back(tn->val); }; + iter::in(root, func); + for (size_t ll{0}, rr{targets.size() - 1}; ll < rr;) { + const auto sum = targets[ll] + targets[rr]; + if (sum == k) { + return true; + } else if (sum > k) { + --rr; + } else if (sum < k) { + ++ll; + } + } + return false; + } +}; +#ifdef ALGORITHM_TEST_MACRO +} +#endif diff --git a/algorithm/tree/leetcode_235_test.hpp b/algorithm/tree/leetcode_unknown_test.cpp similarity index 60% rename from algorithm/tree/leetcode_235_test.hpp rename to algorithm/tree/leetcode_unknown_test.cpp index f312f55c..a14f51c2 100644 --- a/algorithm/tree/leetcode_235_test.hpp +++ b/algorithm/tree/leetcode_unknown_test.cpp @@ -1,41 +1,30 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag tree //@Tag 树 //@Plan 数据结构入门 Day14 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_235_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_235_TEST_HPP #include #include #include +#include #include #include -#include +#include "leetcode_unknown.cpp" -namespace leetcode_235 { +namespace leetcode_unknown { using TreeNode = TREE_NODE::TreeNode; - -struct leetcode_235 { - static bool findTarget(TreeNode *root, int k); -}; - using TreeNodeLink = TREE_NODE::TreeNodeLink; -TEST_CASE("test_case 1 [test_235]", "[test_235]") { +TEST_CASE("test_case 1 [test_unknown]", "[test_unknown]") { + Solution solution; const TreeNodeLink input{5, 3, 6, 2, 4, TreeNode::No, 7, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No, TreeNode::No}; static constexpr const auto target{9}; - CHECK(leetcode_235::findTarget(input[0], target)); + CHECK(solution.findTarget(input[0], target)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_TREE_LEETCODE_235_TEST_HPP diff --git a/algorithm/tree/traverse.cpp b/algorithm/tree/traverse.cpp index 192cec08..15aeb452 100644 --- a/algorithm/tree/traverse.cpp +++ b/algorithm/tree/traverse.cpp @@ -1,17 +1,11 @@ /* - * @Github: https://github.com/Certseeds/CS203_DSAA_template * @Author: nanoseeds * @Date: 2020-07-30 10:30:53 * @LastEditors: nanoseeds * @LastEditTime: 2020-07-30 18:18:53 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include diff --git a/algorithm/tree/traverse_test.cpp b/algorithm/tree/traverse_test.cpp index 5940b9e4..d1253daa 100644 --- a/algorithm/tree/traverse_test.cpp +++ b/algorithm/tree/traverse_test.cpp @@ -1,17 +1,11 @@ /* - * @Github: https://github.com/Certseeds/CS203_DSAA_template * @Author: nanoseeds * @Date: 2020-07-30 10:30:53 * @LastEditors: nanoseeds * @LastEditTime: 2020-07-30 18:18:53 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include "traverse.cpp" #include diff --git a/algorithm/trie/CMakeLists.txt b/algorithm/trie/CMakeLists.txt index 325f52ed..09aa3792 100644 --- a/algorithm/trie/CMakeLists.txt +++ b/algorithm/trie/CMakeLists.txt @@ -9,9 +9,10 @@ set(dependencies 208 212) LIST(TRANSFORM dependencies PREPEND leetcode_) foreach (elementName IN LISTS dependencies) - add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp) - target_link_libraries(${PROJECT_NAME}_${elementName} CS203_DSAA_template_INCLUDE) - MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}.cpp") + add_executable(${PROJECT_NAME}_${elementName} ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp) + target_link_libraries(${PROJECT_NAME}_${elementName} algorithm_template_INCLUDE) + target_compile_definitions(${PROJECT_NAME}_${elementName} PRIVATE ALGORITHM_TEST_MACRO) + MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${elementName}_test.cpp") add_test(${PROJECT_NAME}_${elementName}_CTEST ${PROJECT_NAME}_${elementName}) endforeach () unset(dependencies) diff --git a/algorithm/trie/leetcode_208.cpp b/algorithm/trie/leetcode_208.cpp index 165e74e8..fb377555 100644 --- a/algorithm/trie/leetcode_208.cpp +++ b/algorithm/trie/leetcode_208.cpp @@ -1,12 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#include "leetcode_208_test.hpp" - +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#include +// 这个显然没法直接提交, 要不就复制一份过来 namespace leetcode_208 { using trie = trie::trie; using trie2 = trieR::trie; diff --git a/algorithm/trie/leetcode_208_test.hpp b/algorithm/trie/leetcode_208_test.cpp similarity index 71% rename from algorithm/trie/leetcode_208_test.hpp rename to algorithm/trie/leetcode_208_test.cpp index 14af6337..921c7fa3 100644 --- a/algorithm/trie/leetcode_208_test.hpp +++ b/algorithm/trie/leetcode_208_test.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag string //@Tag 字符串 //@Tag HashMap @@ -12,21 +7,18 @@ Copyright (C) 2020-2023 nanoseeds //@Tag Trie //@Tag 字典树 //@Tag 模拟 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_208_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_208_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_208_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_208_TEST_HPP #include -#include +#include "leetcode_208.cpp" #include namespace leetcode_208 { -struct leetcode_208 { - using trie = trie::trie; - using trie2 = trieR::trie; -}; +using std::make_unique; TEST_CASE("1 [test_208]", "[test_208]") { - const auto leetcode_208_tire = std::make_unique(); + const auto leetcode_208_tire = make_unique(); leetcode_208_tire->insert("apple"); leetcode_208_tire->insert("apple"); CHECK(leetcode_208_tire->search("apple")); @@ -37,7 +29,7 @@ TEST_CASE("1 [test_208]", "[test_208]") { } TEST_CASE("2 [test_208]", "[test_208]") { - const auto leetcode_208_tire = std::make_unique(); + const auto leetcode_208_tire = make_unique(); leetcode_208_tire->insert("hello"); CHECK_FALSE(leetcode_208_tire->search("hell")); CHECK_FALSE(leetcode_208_tire->search("helloa")); @@ -48,7 +40,7 @@ TEST_CASE("2 [test_208]", "[test_208]") { } TEST_CASE("1-2 [test_208]", "[test_208]") { - const auto leetcode_208_tire2 = std::make_unique(); + const auto leetcode_208_tire2 = make_unique(); leetcode_208_tire2->insert("apple"); CHECK(leetcode_208_tire2->search("apple")); CHECK_FALSE(leetcode_208_tire2->search("app")); @@ -58,7 +50,7 @@ TEST_CASE("1-2 [test_208]", "[test_208]") { } TEST_CASE("2-2 [test_208]", "[test_208]") { - const auto leetcode_208_tire2 = std::make_unique(); + const auto leetcode_208_tire2 = make_unique(); leetcode_208_tire2->insert("hello"); CHECK_FALSE(leetcode_208_tire2->search("hell")); CHECK_FALSE(leetcode_208_tire2->search("helloa")); @@ -68,4 +60,4 @@ TEST_CASE("2-2 [test_208]", "[test_208]") { CHECK(leetcode_208_tire2->startsWith("hello")); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_208_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_208_TEST_HPP diff --git a/algorithm/trie/leetcode_212.cpp b/algorithm/trie/leetcode_212.cpp index f243f919..e1ce68cf 100644 --- a/algorithm/trie/leetcode_212.cpp +++ b/algorithm/trie/leetcode_212.cpp @@ -1,15 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO -Copyright (C) 2020-2023 nanoseeds - -*/ - -#include "leetcode_212_test.hpp" #include +#include +#include -#if 0 #pragma GCC optimize(2) #pragma GCC optimize("Ofast") #pragma GCC optimize("no-stack-protector") @@ -63,6 +59,8 @@ Copyright (C) 2020-2023 nanoseeds #endif namespace leetcode_212 { +using std::unordered_set; +using std::stack; class leetcode_208_Trie final { private: static constexpr const size_t array_size{26}; @@ -149,80 +147,83 @@ class leetcode_208_Trie final { } }; -vector leetcode_212::findWords(vector> &board, const vector &words) { - std::array chmap{0}; - for (auto &&boar: board) { - for (auto &&ch: boar) { - chmap[ch]++; - } - } - if (chmap['a'] == 144) { - return {"a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"}; - } - const auto m{board.size()}, n{board.front().size()}; - assert(1 <= m && m <= 12); - assert(1 <= n && n <= 12); - const auto pointer = std::make_unique(); - for (const auto &word: words) { - bool judge{true}; - for (char ch: word) { - if (chmap[ch] == 0) { - judge = false; - break; +class Solution { +public: + vector findWords(vector> &board, const vector &words) { + std::array chmap{0}; + for (auto &&boar: board) { + for (auto &&ch: boar) { + chmap[ch]++; } } - if (judge) { - pointer->insert(word); + if (chmap['a'] == 144) { + return {"a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"}; } - } - unordered_set uset{}; - const std::function dfs = [&board, &pointer, m, n, &uset](size_t x, size_t y) { - constexpr const static - //std::array, 4> ways - int32_t ways[4][2] - {{1, 0}, - {-1, 0}, - {0, 1}, - {0, -1}}; - - - constexpr const static char exp{'#'}; - stack> sta{{{x, y, ""}}}; - while (!sta.empty()) { - auto[first, second, result] = sta.top(); - sta.pop(); - if (result[0] != '#') { - result.push_back(board[first][second]); - board[first][second] = exp; - } - if (result[0] == '#' || !pointer->startsWith(result)) { - board[first][second] = result.back(); - continue; + const auto m{board.size()}, n{board.front().size()}; + assert(1 <= m && m <= 12); + assert(1 <= n && n <= 12); + const auto pointer = std::make_unique(); + for (const auto &word: words) { + bool judge{true}; + for (char ch: word) { + if (chmap[ch] == 0) { + judge = false; + break; + } } - if (result[0] != '#' && pointer->search(result)) { - board[first][second] = result.back(); - uset.insert(result); - pointer->dele_last(result); + if (judge) { + pointer->insert(word); } - sta.emplace(first, second, "#" + result); - for (const auto &way: ways) { - // 先判断是否越界,再判断是否已走过 - if (static_cast(first) + way[0] < 0 || first + way[0] >= m - || static_cast(second) + way[1] < 0 || second + way[1] >= n - || board[first + way[0]][second + way[1]] == exp) { + } + unordered_set uset{}; + const std::function dfs = [&board, &pointer, m, n, &uset](size_t x, size_t y) { + constexpr const static + //std::array, 4> ways + int32_t ways[4][2] + {{1, 0}, + {-1, 0}, + {0, 1}, + {0, -1}}; + + + constexpr const static char exp{'#'}; + stack> sta{{{x, y, ""}}}; + while (!sta.empty()) { + auto [first, second, result] = sta.top(); + sta.pop(); + if (result[0] != '#') { + result.push_back(board[first][second]); + board[first][second] = exp; + } + if (result[0] == '#' || !pointer->startsWith(result)) { + board[first][second] = result.back(); continue; } - sta.emplace(first + way[0], second + way[1], result); + if (result[0] != '#' && pointer->search(result)) { + board[first][second] = result.back(); + uset.insert(result); + pointer->dele_last(result); + } + sta.emplace(first, second, "#" + result); + for (const auto &way: ways) { + // 先判断是否越界,再判断是否已走过 + if (static_cast(first) + way[0] < 0 || first + way[0] >= m + || static_cast(second) + way[1] < 0 || second + way[1] >= n + || board[first + way[0]][second + way[1]] == exp) { + continue; + } + sta.emplace(first + way[0], second + way[1], result); + } + } + }; + for (size_t i{0}; i < m; i++) { + for (size_t j{0}; j < n; j++) { + dfs(i, j); } } - }; - for (size_t i{0}; i < m; i++) { - for (size_t j{0}; j < n; j++) { - dfs(i, j); - } + return {uset.cbegin(), uset.cend()}; } - return {uset.cbegin(), uset.cend()}; -} +}; static const auto faster_streams = [] { srand(time(nullptr)); diff --git a/algorithm/trie/leetcode_212_test.hpp b/algorithm/trie/leetcode_212_test.cpp similarity index 90% rename from algorithm/trie/leetcode_212_test.hpp rename to algorithm/trie/leetcode_212_test.cpp index d397f165..e04f3f80 100644 --- a/algorithm/trie/leetcode_212_test.hpp +++ b/algorithm/trie/leetcode_212_test.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds //@Tag string //@Tag 字符串 //@Tag HashMap @@ -13,11 +8,11 @@ Copyright (C) 2020-2023 nanoseeds //@Tag 字典树 //@Tag 模拟 //@Tag 偷鸡 -#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_212_TEST_HPP -#define CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_212_TEST_HPP +#ifndef ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_212_TEST_HPP +#define ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_212_TEST_HPP #include - +#include "leetcode_212.cpp" #include #include #include @@ -32,9 +27,6 @@ using Catch::Matchers::Equals; using Catch::Matchers::UnorderedEquals; using Catch::Matchers::Contains; -struct leetcode_212 { - static vector findWords(vector> &board, const vector &words); -}; TEST_CASE("test basic 1[test_212]", "[test_212]") { vector> board{{'o', 'a', 'b', 'n'}, @@ -43,7 +35,8 @@ TEST_CASE("test basic 1[test_212]", "[test_212]") { {'a', 'f', 'l', 'v'}}; const vector words{"oa", "oaa"}; const vector &results{words}; - CHECK_THAT(leetcode_212::findWords(board, words), UnorderedEquals(results)); + Solution solution; + CHECK_THAT(solution.findWords(board, words), UnorderedEquals(results)); } TEST_CASE("test basic 2[test_212]", "[test_212]") { @@ -53,7 +46,8 @@ TEST_CASE("test basic 2[test_212]", "[test_212]") { {'i', 'f', 'l', 'v'}}; const vector words{"oath", "pea", "eat", "rain"}; const vector results{"eat", "oath"}; - CHECK_THAT(leetcode_212::findWords(board, words), UnorderedEquals(results)); + Solution solution; + CHECK_THAT(solution.findWords(board, words), UnorderedEquals(results)); } TEST_CASE("test basic 3[test_212]", "[test_212]") { @@ -66,7 +60,8 @@ TEST_CASE("test basic 3[test_212]", "[test_212]") { {'a', 'a', 'a', 'a', 'a', 'a'}}; const vector words{"a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa"}; const vector results{"a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa"}; - CHECK_THAT(leetcode_212::findWords(board, words), UnorderedEquals(results)); + Solution solution; + CHECK_THAT(solution.findWords(board, words), UnorderedEquals(results)); } TEST_CASE("test basic 4[test_212]", "[test_212]") { @@ -87,7 +82,8 @@ TEST_CASE("test basic 4[test_212]", "[test_212]") { "aaaaaaaaaa"}; const vector results{"a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"}; - CHECK_THAT(leetcode_212::findWords(board, words), UnorderedEquals(results)); + Solution solution; + CHECK_THAT(solution.findWords(board, words), UnorderedEquals(results)); } TEST_CASE("test basic 5[test_212]", "[test_212]") { @@ -135,7 +131,8 @@ TEST_CASE("test basic 5[test_212]", "[test_212]") { "oooooooooo", "wwwwww", "ooooooooo", "zzzz", "k", "hhhhhhhh", "aaaaa", "mmmmm"}; const vector results{"a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"}; - CHECK_THAT(leetcode_212::findWords(board, words), UnorderedEquals(results)); + Solution solution; + CHECK_THAT(solution.findWords(board, words), UnorderedEquals(results)); } } -#endif //CS203_DSAA_TEMPLATE_ALGORITHM_STRING_LEETCODE_212_TEST_HPP +#endif //ALGORITHM_TEMPLATE_ALGORITHM_STRING_LEETCODE_212_TEST_HPP diff --git a/basic/cs205_c_cpp_2020s/Assignment_1/lib/assignment_1.cpp b/basic/cs205_c_cpp_2020s/Assignment_1/lib/assignment_1.cpp index e2054262..de9a38c3 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_1/lib/assignment_1.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_1/lib/assignment_1.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-08 22:04:31 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include "assignment_1.hpp" int sub_main() { diff --git a/basic/cs205_c_cpp_2020s/Assignment_1/lib/assignment_1.hpp b/basic/cs205_c_cpp_2020s/Assignment_1/lib/assignment_1.hpp index 7ab920cd..c7af1303 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_1/lib/assignment_1.hpp +++ b/basic/cs205_c_cpp_2020s/Assignment_1/lib/assignment_1.hpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-08 22:04:31 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include #include diff --git a/basic/cs205_c_cpp_2020s/Assignment_1/src/assignment_1_main.cpp b/basic/cs205_c_cpp_2020s/Assignment_1/src/assignment_1_main.cpp index 7c5edc27..69d19789 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_1/src/assignment_1_main.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_1/src/assignment_1_main.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-08 22:19:03 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include int main() { diff --git a/basic/cs205_c_cpp_2020s/Assignment_1/test/CMakeLists.txt b/basic/cs205_c_cpp_2020s/Assignment_1/test/CMakeLists.txt index b107fe0d..f8309f85 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_1/test/CMakeLists.txt +++ b/basic/cs205_c_cpp_2020s/Assignment_1/test/CMakeLists.txt @@ -2,4 +2,4 @@ add_executable(${PROJECT_NAME}_test test_assignment_1.cpp) target_link_libraries(${PROJECT_NAME}_test PUBLIC ${PROJECT_NAME}_lib - CS203_DSAA_template_INCLUDE) + algorithm_template_INCLUDE) diff --git a/basic/cs205_c_cpp_2020s/Assignment_1/test/test_assignment_1.cpp b/basic/cs205_c_cpp_2020s/Assignment_1/test/test_assignment_1.cpp index 82dd7a87..706d4edd 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_1/test/test_assignment_1.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_1/test/test_assignment_1.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-08 22:23:52 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #define UNIT_TESTING_ASSIGNMENT_1 #include diff --git a/basic/cs205_c_cpp_2020s/Assignment_2/lib/Assignment_2.cpp b/basic/cs205_c_cpp_2020s/Assignment_2/lib/Assignment_2.cpp index 7fa10515..748c289a 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_2/lib/Assignment_2.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_2/lib/Assignment_2.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-08 22:52:02 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include "Assignment_2.hpp" int sub_main_assignment_2() { diff --git a/basic/cs205_c_cpp_2020s/Assignment_2/lib/Assignment_2.hpp b/basic/cs205_c_cpp_2020s/Assignment_2/lib/Assignment_2.hpp index 9bf8e796..e2ef94b3 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_2/lib/Assignment_2.hpp +++ b/basic/cs205_c_cpp_2020s/Assignment_2/lib/Assignment_2.hpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-08 22:52:02 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include #include diff --git a/basic/cs205_c_cpp_2020s/Assignment_2/lib/city.cpp b/basic/cs205_c_cpp_2020s/Assignment_2/lib/city.cpp index ae494497..ab7d15b6 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_2/lib/city.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_2/lib/city.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-08 22:49:10 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include "city.hpp" city::city() { diff --git a/basic/cs205_c_cpp_2020s/Assignment_2/lib/city.hpp b/basic/cs205_c_cpp_2020s/Assignment_2/lib/city.hpp index 427ee340..1420c060 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_2/lib/city.hpp +++ b/basic/cs205_c_cpp_2020s/Assignment_2/lib/city.hpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-08 22:49:10 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #ifndef _ASSIGNMENT_2_CITY_ #define _ASSIGNMENT_2_CITY_ diff --git a/basic/cs205_c_cpp_2020s/Assignment_2/src/assignment_2_main.cpp b/basic/cs205_c_cpp_2020s/Assignment_2/src/assignment_2_main.cpp index 5930f331..08abfb78 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_2/src/assignment_2_main.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_2/src/assignment_2_main.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-08 22:19:03 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include int main() { diff --git a/basic/cs205_c_cpp_2020s/Assignment_2/test/CMakeLists.txt b/basic/cs205_c_cpp_2020s/Assignment_2/test/CMakeLists.txt index c663d4b5..98a5869c 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_2/test/CMakeLists.txt +++ b/basic/cs205_c_cpp_2020s/Assignment_2/test/CMakeLists.txt @@ -2,5 +2,5 @@ add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/test_assignment_ target_link_libraries(${PROJECT_NAME}_test PUBLIC ${PROJECT_NAME}_lib - CS203_DSAA_template_INCLUDE) + algorithm_template_INCLUDE) diff --git a/basic/cs205_c_cpp_2020s/Assignment_2/test/test_assignment_2.cpp b/basic/cs205_c_cpp_2020s/Assignment_2/test/test_assignment_2.cpp index cd4969d0..bef54755 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_2/test/test_assignment_2.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_2/test/test_assignment_2.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-08 23:13:27 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include #include diff --git a/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_01.cpp b/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_01.cpp index 9fa926b2..ca83bc00 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_01.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_02.cpp b/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_02.cpp index b8e70e8f..1b7dfeae 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_02.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_02.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_03.cpp b/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_03.cpp index d60f58c3..02d91f6d 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_03.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_3/src/Assignment_3_03.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds @@ -13,6 +11,7 @@ #include #include #include +#include #include "utf8.hpp" using std::cin; @@ -81,7 +80,7 @@ int32_t sub_main_assignment_3_03() { chars_count[find_alphabeta(blocks, block_count, code_point)]++; // 强制类型转换,search and count } - int32_t max_v = INT32_MIN / 2; + int32_t max_v = std::numeric_limits::min() / 2; int32_t max_posi = 0; for (int i = 0; i < unicode_part_number; ++i) { if (chars_count[i] > max_v) { diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_01.cpp b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_01.cpp index 73c47aa8..79763cd9 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_01.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_01.hpp b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_01.hpp index fa91ca30..011770c5 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_01.hpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_01.hpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_02.cpp b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_02.cpp index b4735dc2..b33e51ef 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_02.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_02.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_02.hpp b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_02.hpp index d495f39e..fd6c2f5f 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_02.hpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_02.hpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_03.cpp b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_03.cpp index b3236b5a..d9163670 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_03.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_03.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_03.hpp b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_03.hpp index c972a1f3..23d0967a 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_03.hpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_03.hpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_04.cpp b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_04.cpp index 19e4540d..5f5c4223 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_04.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_04.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_04.hpp b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_04.hpp index 09135c66..12d9cee5 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_04.hpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_04.hpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_05.cpp b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_05.cpp index 99cb7a6b..3c07358e 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_05.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_05.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_05.hpp b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_05.hpp index 69c74afe..e8e357b9 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_05.hpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/lib/Assignment_4_05.hpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_01.cpp b/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_01.cpp index 36c8e024..c8e82e6d 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_01.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_02.cpp b/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_02.cpp index 1b8aff85..f7cf78a5 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_02.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_02.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_03.cpp b/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_03.cpp index 1b62bca7..b5b6b64f 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_03.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_03.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_04.cpp b/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_04.cpp index 30f7e8ef..2100e504 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_04.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_04.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_05.cpp b/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_05.cpp index 6d7b329c..e0b77cbe 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_05.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_4/src/Assignment_4_05.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_5/lib/UTF8string.cpp b/basic/cs205_c_cpp_2020s/Assignment_5/lib/UTF8string.cpp index 4ba708e7..d0bfec02 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_5/lib/UTF8string.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_5/lib/UTF8string.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_5/lib/UTF8string.hpp b/basic/cs205_c_cpp_2020s/Assignment_5/lib/UTF8string.hpp index 15f74eb0..e8ec5091 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_5/lib/UTF8string.hpp +++ b/basic/cs205_c_cpp_2020s/Assignment_5/lib/UTF8string.hpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/Assignment_5/test/CMakeLists.txt b/basic/cs205_c_cpp_2020s/Assignment_5/test/CMakeLists.txt index c2cc11e9..d87536a6 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_5/test/CMakeLists.txt +++ b/basic/cs205_c_cpp_2020s/Assignment_5/test/CMakeLists.txt @@ -5,7 +5,7 @@ set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") add_executable(${PROJECT_NAME}_catch_test ${CMAKE_CURRENT_SOURCE_DIR}/test_catch_UTF8_String.cpp) -target_link_libraries(${PROJECT_NAME}_catch_test PUBLIC ${PROJECT_NAME} CS203_DSAA_template_INCLUDE) +target_link_libraries(${PROJECT_NAME}_catch_test PUBLIC ${PROJECT_NAME} algorithm_template_INCLUDE) add_executable(${PROJECT_NAME}_simple_test ${CMAKE_CURRENT_SOURCE_DIR}/testUTF8string.cpp) target_link_libraries(${PROJECT_NAME}_simple_test PUBLIC ${PROJECT_NAME}) diff --git a/basic/cs205_c_cpp_2020s/Assignment_5/test/test_catch_UTF8_String.cpp b/basic/cs205_c_cpp_2020s/Assignment_5/test/test_catch_UTF8_String.cpp index 490db1f4..93597d9d 100644 --- a/basic/cs205_c_cpp_2020s/Assignment_5/test/test_catch_UTF8_String.cpp +++ b/basic/cs205_c_cpp_2020s/Assignment_5/test/test_catch_UTF8_String.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab01/exercise/hello.cpp b/basic/cs205_c_cpp_2020s/lab01/exercise/hello.cpp index a268dd14..9e43afdd 100644 --- a/basic/cs205_c_cpp_2020s/lab01/exercise/hello.cpp +++ b/basic/cs205_c_cpp_2020s/lab01/exercise/hello.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2020-02-20 20:15:47 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include using std::cout; diff --git a/basic/cs205_c_cpp_2020s/lab01/exercise/smile.cpp b/basic/cs205_c_cpp_2020s/lab01/exercise/smile.cpp index f6ee7fc3..8dacaa41 100644 --- a/basic/cs205_c_cpp_2020s/lab01/exercise/smile.cpp +++ b/basic/cs205_c_cpp_2020s/lab01/exercise/smile.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2020-02-20 19:35:48 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include using std::cout; diff --git a/basic/cs205_c_cpp_2020s/lab02/exercise/CMakeLists.txt b/basic/cs205_c_cpp_2020s/lab02/exercise/CMakeLists.txt index 6c8ce4e5..b2beb610 100644 --- a/basic/cs205_c_cpp_2020s/lab02/exercise/CMakeLists.txt +++ b/basic/cs205_c_cpp_2020s/lab02/exercise/CMakeLists.txt @@ -6,4 +6,4 @@ add_executable(${PROJECT_NAME}_test test_lab02.cpp) add_executable(${PROJECT_NAME}_01 lab02_01.cpp) add_executable(${PROJECT_NAME}_02 lab02_02.cpp) add_executable(${PROJECT_NAME}_03 lab02_03.cpp) -target_link_libraries(${PROJECT_NAME}_test PUBLIC CS203_DSAA_template_INCLUDE) \ No newline at end of file +target_link_libraries(${PROJECT_NAME}_test PUBLIC algorithm_template_INCLUDE) \ No newline at end of file diff --git a/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_01.cpp b/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_01.cpp index 9001495b..93370265 100644 --- a/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_01.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2020-02-28 09:59:17 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include #include diff --git a/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_02.cpp b/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_02.cpp index 070eabef..e80d4f2e 100644 --- a/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_02.cpp +++ b/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_02.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2020-02-28 16:19:14 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include #include diff --git a/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_03.cpp b/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_03.cpp index 04ba2ca5..463b901d 100644 --- a/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_03.cpp +++ b/basic/cs205_c_cpp_2020s/lab02/exercise/lab02_03.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-09 08:50:49 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include diff --git a/basic/cs205_c_cpp_2020s/lab02/exercise/test_lab02.cpp b/basic/cs205_c_cpp_2020s/lab02/exercise/test_lab02.cpp index 3749b678..01d69748 100644 --- a/basic/cs205_c_cpp_2020s/lab02/exercise/test_lab02.cpp +++ b/basic/cs205_c_cpp_2020s/lab02/exercise/test_lab02.cpp @@ -5,9 +5,7 @@ * @LastEditors : nanoseeds */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #define UNIT_TESTING_LAB_02 #include diff --git a/basic/cs205_c_cpp_2020s/lab03/exercise/CMakeLists.txt b/basic/cs205_c_cpp_2020s/lab03/exercise/CMakeLists.txt index ba33e5f0..37c3ab72 100644 --- a/basic/cs205_c_cpp_2020s/lab03/exercise/CMakeLists.txt +++ b/basic/cs205_c_cpp_2020s/lab03/exercise/CMakeLists.txt @@ -6,5 +6,5 @@ add_executable(${PROJECT_NAME}_01 lab03_01.cpp) add_executable(${PROJECT_NAME}_02 lab03_02.cpp) add_executable(${PROJECT_NAME}_03 lab03_03.cpp) add_executable(${PROJECT_NAME}_test test_lab03.cpp) -target_link_libraries(${PROJECT_NAME}_test PUBLIC CS203_DSAA_template_INCLUDE) +target_link_libraries(${PROJECT_NAME}_test PUBLIC algorithm_template_INCLUDE) # target_link_libraries(lab03 catch) \ No newline at end of file diff --git a/basic/cs205_c_cpp_2020s/lab03/exercise/CandyBar.h b/basic/cs205_c_cpp_2020s/lab03/exercise/CandyBar.h index b798a5d8..5771106f 100644 --- a/basic/cs205_c_cpp_2020s/lab03/exercise/CandyBar.h +++ b/basic/cs205_c_cpp_2020s/lab03/exercise/CandyBar.h @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-09 08:50:49 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #ifndef _CANDYBAR_ #define _CANDYBAR_ diff --git a/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_01.cpp b/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_01.cpp index 459313ea..02941cc6 100644 --- a/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_01.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-09 08:50:49 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include "CandyBar.h" diff --git a/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_02.cpp b/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_02.cpp index 4f3129f0..7330b9d9 100644 --- a/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_02.cpp +++ b/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_02.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-09 08:50:49 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include "CandyBar.h" diff --git a/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_03.cpp b/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_03.cpp index 537e9c71..7263105e 100644 --- a/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_03.cpp +++ b/basic/cs205_c_cpp_2020s/lab03/exercise/lab03_03.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-09 08:50:49 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include "CandyBar.h" diff --git a/basic/cs205_c_cpp_2020s/lab03/exercise/test_lab03.cpp b/basic/cs205_c_cpp_2020s/lab03/exercise/test_lab03.cpp index b7adfffd..fea51167 100644 --- a/basic/cs205_c_cpp_2020s/lab03/exercise/test_lab03.cpp +++ b/basic/cs205_c_cpp_2020s/lab03/exercise/test_lab03.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-09 08:51:49 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #define UNIT_TESTING_LAB_03 diff --git a/basic/cs205_c_cpp_2020s/lab04/exercise/CMakeLists.txt b/basic/cs205_c_cpp_2020s/lab04/exercise/CMakeLists.txt index 37fc64b0..3a4d0802 100644 --- a/basic/cs205_c_cpp_2020s/lab04/exercise/CMakeLists.txt +++ b/basic/cs205_c_cpp_2020s/lab04/exercise/CMakeLists.txt @@ -11,7 +11,7 @@ add_executable(${PROJECT_NAME}_test test_lab04.cpp) target_link_libraries(${PROJECT_NAME}_01 PUBLIC ${PROJECT_NAME}_pizza) target_link_libraries(${PROJECT_NAME}_02 PUBLIC ${PROJECT_NAME}_CandyBar) -target_link_libraries(${PROJECT_NAME}_test PUBLIC CS203_DSAA_template_INCLUDE +target_link_libraries(${PROJECT_NAME}_test PUBLIC algorithm_template_INCLUDE ${PROJECT_NAME}_pizza ${PROJECT_NAME}_CandyBar) diff --git a/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_01.cpp b/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_01.cpp index c2f2a4f4..4350620e 100644 --- a/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include "pizza.hpp" diff --git a/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_02.cpp b/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_02.cpp index dcd2eb3d..b7f269c3 100644 --- a/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_02.cpp +++ b/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_02.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include "CandyBar.hpp" diff --git a/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_03.cpp b/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_03.cpp index 3d75d2c3..bd9a71e2 100644 --- a/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_03.cpp +++ b/basic/cs205_c_cpp_2020s/lab04/exercise/lab04_03.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include diff --git a/basic/cs205_c_cpp_2020s/lab04/exercise/lib/CandyBar.cpp b/basic/cs205_c_cpp_2020s/lab04/exercise/lib/CandyBar.cpp index 6ca65a5e..82358f21 100644 --- a/basic/cs205_c_cpp_2020s/lab04/exercise/lib/CandyBar.cpp +++ b/basic/cs205_c_cpp_2020s/lab04/exercise/lib/CandyBar.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include "CandyBar.hpp" diff --git a/basic/cs205_c_cpp_2020s/lab04/exercise/lib/CandyBar.hpp b/basic/cs205_c_cpp_2020s/lab04/exercise/lib/CandyBar.hpp index de8e9694..676ededc 100644 --- a/basic/cs205_c_cpp_2020s/lab04/exercise/lib/CandyBar.hpp +++ b/basic/cs205_c_cpp_2020s/lab04/exercise/lib/CandyBar.hpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #ifndef _LAB04_CANDYBAR_ #define _LAB04_CANDYBAR_ diff --git a/basic/cs205_c_cpp_2020s/lab04/exercise/lib/pizza.cpp b/basic/cs205_c_cpp_2020s/lab04/exercise/lib/pizza.cpp index 240b0470..a6875871 100644 --- a/basic/cs205_c_cpp_2020s/lab04/exercise/lib/pizza.cpp +++ b/basic/cs205_c_cpp_2020s/lab04/exercise/lib/pizza.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include "pizza.hpp" pizza::pizza() { diff --git a/basic/cs205_c_cpp_2020s/lab04/exercise/lib/pizza.hpp b/basic/cs205_c_cpp_2020s/lab04/exercise/lib/pizza.hpp index b234b85d..63e584cb 100644 --- a/basic/cs205_c_cpp_2020s/lab04/exercise/lib/pizza.hpp +++ b/basic/cs205_c_cpp_2020s/lab04/exercise/lib/pizza.hpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #ifndef _LAB04_PIZZA_ #define _LAB04_PIZZA_ diff --git a/basic/cs205_c_cpp_2020s/lab04/exercise/test_lab04.cpp b/basic/cs205_c_cpp_2020s/lab04/exercise/test_lab04.cpp index efba9e69..2d679411 100644 --- a/basic/cs205_c_cpp_2020s/lab04/exercise/test_lab04.cpp +++ b/basic/cs205_c_cpp_2020s/lab04/exercise/test_lab04.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #define UNIT_TESTING_LAB_04 diff --git a/basic/cs205_c_cpp_2020s/lab05/exercise/CMakeLists.txt b/basic/cs205_c_cpp_2020s/lab05/exercise/CMakeLists.txt index c295c2be..25a44920 100644 --- a/basic/cs205_c_cpp_2020s/lab05/exercise/CMakeLists.txt +++ b/basic/cs205_c_cpp_2020s/lab05/exercise/CMakeLists.txt @@ -8,6 +8,6 @@ add_executable(${PROJECT_NAME}_03 lab05_03.cpp) add_executable(${PROJECT_NAME}_04 lab05_04.cpp) add_executable(${PROJECT_NAME}_test test_lab05.cpp) -target_link_libraries(${PROJECT_NAME}_test PUBLIC CS203_DSAA_template_INCLUDE) +target_link_libraries(${PROJECT_NAME}_test PUBLIC algorithm_template_INCLUDE) # target_link_libraries(lab05) \ No newline at end of file diff --git a/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_01.cpp b/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_01.cpp index 4f658c82..04934cbb 100644 --- a/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_01.cpp @@ -1,13 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ -/** - * @Github: https://github.com/Certseeds - * @Author: nanoseeds - * @Date: 2020-03-26 21:28:07 - * @LastEditors : nanoseeds - */ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + #include #include diff --git a/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_02.cpp b/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_02.cpp index ec221b4f..55e017e2 100644 --- a/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_02.cpp +++ b/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_02.cpp @@ -1,13 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ -/** - * @Github: https://github.com/Certseeds - * @Author: nanoseeds - * @Date: 2020-03-26 22:02:50 - * @LastEditors : nanoseeds - */ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + #include #include diff --git a/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_03.cpp b/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_03.cpp index d538ec4a..8a0e75b5 100644 --- a/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_03.cpp +++ b/basic/cs205_c_cpp_2020s/lab06/exercise/lab06_03.cpp @@ -1,20 +1,6 @@ -/* - * @Github: https://github.com/Certseeds - * @Author: nanoseeds - * @Date: 2021-01-05 18:49:03 - * @LastEditors: nanoseeds - * @LastEditTime: 2021-06-22 13:33:24 - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ -/** - * @Github: https://github.com/Certseeds - * @Author: nanoseeds - * @Date: 2020-03-26 23:05:19 - * @LastEditors : nanoseeds - */ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + #include using std::cin; diff --git a/basic/cs205_c_cpp_2020s/lab06/exercise/lib/Book.cpp b/basic/cs205_c_cpp_2020s/lab06/exercise/lib/Book.cpp index 47314480..4838322f 100644 --- a/basic/cs205_c_cpp_2020s/lab06/exercise/lib/Book.cpp +++ b/basic/cs205_c_cpp_2020s/lab06/exercise/lib/Book.cpp @@ -1,13 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ -/** - * @Github: https://github.com/Certseeds - * @Author: nanoseeds - * @Date: 2020-03-26 18:10:42 - * @LastEditors : nanoseeds - */ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + #include "Book.hpp" diff --git a/basic/cs205_c_cpp_2020s/lab06/exercise/lib/Book.hpp b/basic/cs205_c_cpp_2020s/lab06/exercise/lib/Book.hpp index f08de68b..ccb3e946 100644 --- a/basic/cs205_c_cpp_2020s/lab06/exercise/lib/Book.hpp +++ b/basic/cs205_c_cpp_2020s/lab06/exercise/lib/Book.hpp @@ -1,14 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ -/* - * @Github: https://github.com/Certseeds - * @Author: nanoseeds - * @Date: 2021-01-05 18:49:03 - * @LastEditors: nanoseeds - * @LastEditTime: 2021-02-09 09:44:50 - */ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #ifndef CS205_C_CPP_LAB06_EXERCISE_INCLUDE_BOOK_H #define CS205_C_CPP_LAB06_EXERCISE_INCLUDE_BOOK_H diff --git a/basic/cs205_c_cpp_2020s/lab06/exercise/read_books.cpp b/basic/cs205_c_cpp_2020s/lab06/exercise/read_books.cpp index 34099a95..27c8c6d6 100644 --- a/basic/cs205_c_cpp_2020s/lab06/exercise/read_books.cpp +++ b/basic/cs205_c_cpp_2020s/lab06/exercise/read_books.cpp @@ -1,13 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ -/** - * @Github: https://github.com/Certseeds - * @Author: nanoseeds - * @Date: 2020-03-26 18:16:22 - * @LastEditors : nanoseeds - */ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds + #include "Book.hpp" #include diff --git a/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_01.cpp b/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_01.cpp index 4967a65e..29ce45f7 100644 --- a/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_02.cpp b/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_02.cpp index 8309a2b8..6670f35a 100644 --- a/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_02.cpp +++ b/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_02.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_03.cpp b/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_03.cpp index 4671c3ca..a8d8bb22 100644 --- a/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_03.cpp +++ b/basic/cs205_c_cpp_2020s/lab07/exercise/lab07_03.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab08/exercise/lab08_01.cpp b/basic/cs205_c_cpp_2020s/lab08/exercise/lab08_01.cpp index d1a307b7..c47b0396 100644 --- a/basic/cs205_c_cpp_2020s/lab08/exercise/lab08_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab08/exercise/lab08_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab08/exercise/lab08_02.cpp b/basic/cs205_c_cpp_2020s/lab08/exercise/lab08_02.cpp index 7585ad35..54b46d98 100644 --- a/basic/cs205_c_cpp_2020s/lab08/exercise/lab08_02.cpp +++ b/basic/cs205_c_cpp_2020s/lab08/exercise/lab08_02.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab09/exercise/CandyBar.h b/basic/cs205_c_cpp_2020s/lab09/exercise/CandyBar.h index 120ac8d4..1d7d7096 100644 --- a/basic/cs205_c_cpp_2020s/lab09/exercise/CandyBar.h +++ b/basic/cs205_c_cpp_2020s/lab09/exercise/CandyBar.h @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab09/exercise/candybar.cpp b/basic/cs205_c_cpp_2020s/lab09/exercise/candybar.cpp index ded6d79c..ac1b4331 100644 --- a/basic/cs205_c_cpp_2020s/lab09/exercise/candybar.cpp +++ b/basic/cs205_c_cpp_2020s/lab09/exercise/candybar.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab09/exercise/fun.cpp b/basic/cs205_c_cpp_2020s/lab09/exercise/fun.cpp index 87762c43..03361563 100644 --- a/basic/cs205_c_cpp_2020s/lab09/exercise/fun.cpp +++ b/basic/cs205_c_cpp_2020s/lab09/exercise/fun.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab09/exercise/fun.h b/basic/cs205_c_cpp_2020s/lab09/exercise/fun.h index fa1f98e3..ba207a0d 100644 --- a/basic/cs205_c_cpp_2020s/lab09/exercise/fun.h +++ b/basic/cs205_c_cpp_2020s/lab09/exercise/fun.h @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab09/exercise/main.cpp b/basic/cs205_c_cpp_2020s/lab09/exercise/main.cpp index 6a13ee9b..fd2b30a6 100644 --- a/basic/cs205_c_cpp_2020s/lab09/exercise/main.cpp +++ b/basic/cs205_c_cpp_2020s/lab09/exercise/main.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab09/exercise/main2.cpp b/basic/cs205_c_cpp_2020s/lab09/exercise/main2.cpp index 76928e2d..0fb68039 100644 --- a/basic/cs205_c_cpp_2020s/lab09/exercise/main2.cpp +++ b/basic/cs205_c_cpp_2020s/lab09/exercise/main2.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab11/exercise/lab11_01.cpp b/basic/cs205_c_cpp_2020s/lab11/exercise/lab11_01.cpp index 656e2f23..c159577d 100644 --- a/basic/cs205_c_cpp_2020s/lab11/exercise/lab11_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab11/exercise/lab11_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab11/exercise/lab11_02.cpp b/basic/cs205_c_cpp_2020s/lab11/exercise/lab11_02.cpp index cc9dde36..90c5b36f 100644 --- a/basic/cs205_c_cpp_2020s/lab11/exercise/lab11_02.cpp +++ b/basic/cs205_c_cpp_2020s/lab11/exercise/lab11_02.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab11/exercise/lib/candy_bar.cpp b/basic/cs205_c_cpp_2020s/lab11/exercise/lib/candy_bar.cpp index 43f2217d..49d4ca00 100644 --- a/basic/cs205_c_cpp_2020s/lab11/exercise/lib/candy_bar.cpp +++ b/basic/cs205_c_cpp_2020s/lab11/exercise/lib/candy_bar.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab11/exercise/lib/candy_bar.h b/basic/cs205_c_cpp_2020s/lab11/exercise/lib/candy_bar.h index e8a34a11..b8c97ea3 100644 --- a/basic/cs205_c_cpp_2020s/lab11/exercise/lib/candy_bar.h +++ b/basic/cs205_c_cpp_2020s/lab11/exercise/lib/candy_bar.h @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab11/exercise/lib/rectangle.cpp b/basic/cs205_c_cpp_2020s/lab11/exercise/lib/rectangle.cpp index 9c49580d..6a9ab5c5 100644 --- a/basic/cs205_c_cpp_2020s/lab11/exercise/lib/rectangle.cpp +++ b/basic/cs205_c_cpp_2020s/lab11/exercise/lib/rectangle.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab11/exercise/lib/rectangle.h b/basic/cs205_c_cpp_2020s/lab11/exercise/lib/rectangle.h index c39e6852..aea583ef 100644 --- a/basic/cs205_c_cpp_2020s/lab11/exercise/lib/rectangle.h +++ b/basic/cs205_c_cpp_2020s/lab11/exercise/lib/rectangle.h @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab11/rusrc/lib/rectangle.rs b/basic/cs205_c_cpp_2020s/lab11/rusrc/lib/rectangle.rs index 086614c7..8814baaa 100644 --- a/basic/cs205_c_cpp_2020s/lab11/rusrc/lib/rectangle.rs +++ b/basic/cs205_c_cpp_2020s/lab11/rusrc/lib/rectangle.rs @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds use std::fmt; pub struct Rectangle { diff --git a/basic/cs205_c_cpp_2020s/lab12/exercise/lab12_01.cpp b/basic/cs205_c_cpp_2020s/lab12/exercise/lab12_01.cpp index 33323158..9bdb0657 100644 --- a/basic/cs205_c_cpp_2020s/lab12/exercise/lab12_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab12/exercise/lab12_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab12/exercise/lab12_02.cpp b/basic/cs205_c_cpp_2020s/lab12/exercise/lab12_02.cpp index 898d95e4..7fb215d2 100644 --- a/basic/cs205_c_cpp_2020s/lab12/exercise/lab12_02.cpp +++ b/basic/cs205_c_cpp_2020s/lab12/exercise/lab12_02.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab12/exercise/lib/complex.cpp b/basic/cs205_c_cpp_2020s/lab12/exercise/lib/complex.cpp index a1dfb3ee..cef86ad2 100644 --- a/basic/cs205_c_cpp_2020s/lab12/exercise/lib/complex.cpp +++ b/basic/cs205_c_cpp_2020s/lab12/exercise/lib/complex.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab12/exercise/lib/complex.h b/basic/cs205_c_cpp_2020s/lab12/exercise/lib/complex.h index cdd5627a..585ea463 100644 --- a/basic/cs205_c_cpp_2020s/lab12/exercise/lib/complex.h +++ b/basic/cs205_c_cpp_2020s/lab12/exercise/lib/complex.h @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab12/exercise/lib/number.cpp b/basic/cs205_c_cpp_2020s/lab12/exercise/lib/number.cpp index 5888112f..0a52f193 100644 --- a/basic/cs205_c_cpp_2020s/lab12/exercise/lib/number.cpp +++ b/basic/cs205_c_cpp_2020s/lab12/exercise/lib/number.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab12/exercise/lib/number.h b/basic/cs205_c_cpp_2020s/lab12/exercise/lib/number.h index 788c8aa9..4bebd2bb 100644 --- a/basic/cs205_c_cpp_2020s/lab12/exercise/lib/number.h +++ b/basic/cs205_c_cpp_2020s/lab12/exercise/lib/number.h @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_01.cpp b/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_01.cpp index 2b733ed7..7a706910 100644 --- a/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_02.cpp b/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_02.cpp index a300cdeb..6e7c7e53 100644 --- a/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_02.cpp +++ b/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_02.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_04.cpp b/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_04.cpp index de18f2d8..2d74de63 100644 --- a/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_04.cpp +++ b/basic/cs205_c_cpp_2020s/lab13/exercise/lab13_04.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_cube_lab13_02.cpp b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_cube_lab13_02.cpp index 26fe6261..9f40610f 100644 --- a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_cube_lab13_02.cpp +++ b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_cube_lab13_02.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_cube_lab13_02.h b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_cube_lab13_02.h index bd928911..abbd420b 100644 --- a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_cube_lab13_02.h +++ b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_cube_lab13_02.h @@ -6,9 +6,7 @@ * @LastEditTime: 2021-02-09 09:57:28 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_sphere_lab13_03.cpp b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_sphere_lab13_03.cpp index d9eb6640..3a39ba32 100644 --- a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_sphere_lab13_03.cpp +++ b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_sphere_lab13_03.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_sphere_lab13_03.h b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_sphere_lab13_03.h index 85bfdd7f..f997d5bb 100644 --- a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_sphere_lab13_03.h +++ b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_sphere_lab13_03.h @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_stereoShape_lab13_01.cpp b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_stereoShape_lab13_01.cpp index d83af751..3e034488 100644 --- a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_stereoShape_lab13_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_stereoShape_lab13_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_stereoShape_lab13_01.h b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_stereoShape_lab13_01.h index a3f5fecd..f3a3ac63 100644 --- a/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_stereoShape_lab13_01.h +++ b/basic/cs205_c_cpp_2020s/lab13/exercise/lib/c_stereoShape_lab13_01.h @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab14/exercise/lab14_01.cpp b/basic/cs205_c_cpp_2020s/lab14/exercise/lab14_01.cpp index 1e75169f..55972c47 100644 --- a/basic/cs205_c_cpp_2020s/lab14/exercise/lab14_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab14/exercise/lab14_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab14/exercise/lab14_02.cpp b/basic/cs205_c_cpp_2020s/lab14/exercise/lab14_02.cpp index 0e9ef3a6..b721cfa4 100644 --- a/basic/cs205_c_cpp_2020s/lab14/exercise/lab14_02.cpp +++ b/basic/cs205_c_cpp_2020s/lab14/exercise/lab14_02.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab14/exercise/matrix.h b/basic/cs205_c_cpp_2020s/lab14/exercise/matrix.h index a14f7171..536b7128 100644 --- a/basic/cs205_c_cpp_2020s/lab14/exercise/matrix.h +++ b/basic/cs205_c_cpp_2020s/lab14/exercise/matrix.h @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/lab15/exercise/lab15_01.cpp b/basic/cs205_c_cpp_2020s/lab15/exercise/lab15_01.cpp index 020541c6..880f32fe 100644 --- a/basic/cs205_c_cpp_2020s/lab15/exercise/lab15_01.cpp +++ b/basic/cs205_c_cpp_2020s/lab15/exercise/lab15_01.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/midterm/2021Spring/CMakeLists.txt b/basic/cs205_c_cpp_2020s/midterm/2021Spring/CMakeLists.txt index d414a0a0..5686285b 100644 --- a/basic/cs205_c_cpp_2020s/midterm/2021Spring/CMakeLists.txt +++ b/basic/cs205_c_cpp_2020s/midterm/2021Spring/CMakeLists.txt @@ -10,4 +10,4 @@ foreach (element IN LISTS _List) ${CMAKE_CURRENT_SOURCE_DIR}/question${element}.cpp) endforeach () unset(_List) -target_link_libraries(${PROJECT_NAME}_test PUBLIC CS203_DSAA_template_INCLUDE) +target_link_libraries(${PROJECT_NAME}_test PUBLIC algorithm_template_INCLUDE) diff --git a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question1.cpp b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question1.cpp index 21004270..826cc909 100644 --- a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question1.cpp +++ b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question1.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-04-16 13:24:35 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include //look at // https://leetcode-cn.com/problems/factorial-trailing-zeroes/ diff --git a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question2.cpp b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question2.cpp index deceaa57..075fc920 100644 --- a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question2.cpp +++ b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question2.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-04-16 13:24:40 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include #include diff --git a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question3.cpp b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question3.cpp index a4b7e5d2..d5f32998 100644 --- a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question3.cpp +++ b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question3.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-04-16 13:24:45 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include #include diff --git a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question4.cpp b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question4.cpp index f027a238..bf22daf8 100644 --- a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question4.cpp +++ b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question4.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-04-16 13:24:50 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include #include diff --git a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question5.cpp b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question5.cpp index ae8d5636..01fc2dd5 100644 --- a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question5.cpp +++ b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question5.cpp @@ -5,9 +5,7 @@ * @LastEditTime: 2021-04-16 13:25:55 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include #include #include diff --git a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question_test.cpp b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question_test.cpp index 7245be50..6afce7bb 100644 --- a/basic/cs205_c_cpp_2020s/midterm/2021Spring/question_test.cpp +++ b/basic/cs205_c_cpp_2020s/midterm/2021Spring/question_test.cpp @@ -6,9 +6,7 @@ * @LastEditTime: 2021-04-16 13:24:31 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #ifndef CS205_C_CPP_MIDTERM_2021SPRING #define CS205_C_CPP_MIDTERM_2021SPRING diff --git a/basic/cs205_c_cpp_2020s/midterm/question1.cpp b/basic/cs205_c_cpp_2020s/midterm/question1.cpp index fe4959b8..65abeca0 100644 --- a/basic/cs205_c_cpp_2020s/midterm/question1.cpp +++ b/basic/cs205_c_cpp_2020s/midterm/question1.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/midterm/question2.cpp b/basic/cs205_c_cpp_2020s/midterm/question2.cpp index 490673b8..c566aae6 100644 --- a/basic/cs205_c_cpp_2020s/midterm/question2.cpp +++ b/basic/cs205_c_cpp_2020s/midterm/question2.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/cs205_c_cpp_2020s/midterm/question4.cpp b/basic/cs205_c_cpp_2020s/midterm/question4.cpp index a59f3cd1..de85ae54 100644 --- a/basic/cs205_c_cpp_2020s/midterm/question4.cpp +++ b/basic/cs205_c_cpp_2020s/midterm/question4.cpp @@ -1,7 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* CS205_C_CPP - Copyright (C) 2020-2023 nanoseeds -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds /** * @Github: https://github.com/Certseeds * @Author: nanoseeds diff --git a/basic/static_dynamic_libs/lib1.cpp b/basic/static_dynamic_libs/lib1.cpp index 621f0346..036030b4 100644 --- a/basic/static_dynamic_libs/lib1.cpp +++ b/basic/static_dynamic_libs/lib1.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include "lib1.hpp" #include diff --git a/basic/static_dynamic_libs/lib1.hpp b/basic/static_dynamic_libs/lib1.hpp index 088978bc..10d42ea3 100644 --- a/basic/static_dynamic_libs/lib1.hpp +++ b/basic/static_dynamic_libs/lib1.hpp @@ -1,16 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds - -*/ - -#ifndef CS203_DSAA_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB1_LIB1_HPP -#define CS203_DSAA_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB1_LIB1_HPP +#ifndef ALGORITHM_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB1_LIB1_HPP +#define ALGORITHM_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB1_LIB1_HPP #include int32_t function1(); -#endif //CS203_DSAA_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB1_LIB1_HPP +#endif //ALGORITHM_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB1_LIB1_HPP diff --git a/basic/static_dynamic_libs/lib2.cpp b/basic/static_dynamic_libs/lib2.cpp index bb8bf0f8..12f36dde 100644 --- a/basic/static_dynamic_libs/lib2.cpp +++ b/basic/static_dynamic_libs/lib2.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include "lib2.hpp" #include "lib1.hpp" #include diff --git a/basic/static_dynamic_libs/lib2.hpp b/basic/static_dynamic_libs/lib2.hpp index e0417d14..d5c01bed 100644 --- a/basic/static_dynamic_libs/lib2.hpp +++ b/basic/static_dynamic_libs/lib2.hpp @@ -1,16 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2022-2025 nanoseeds -Copyright (C) 2022-2023 nanoseeds - -*/ - -#ifndef CS203_DSAA_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB2_LIB2_HPP -#define CS203_DSAA_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB2_LIB2_HPP +#ifndef ALGORITHM_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB2_LIB2_HPP +#define ALGORITHM_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB2_LIB2_HPP #include int32_t function2(); -#endif //CS203_DSAA_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB2_LIB2_HPP +#endif //ALGORITHM_TEMPLATE_BASIC_INSTALL_PACKAGES_LIB2_LIB2_HPP diff --git a/basic/static_dynamic_libs/test1.cpp b/basic/static_dynamic_libs/test1.cpp index 858e25b3..fb3115b8 100644 --- a/basic/static_dynamic_libs/test1.cpp +++ b/basic/static_dynamic_libs/test1.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include "lib1.hpp" int32_t main() { diff --git a/basic/static_dynamic_libs/test2.cpp b/basic/static_dynamic_libs/test2.cpp index af7dbdc2..107d070b 100644 --- a/basic/static_dynamic_libs/test2.cpp +++ b/basic/static_dynamic_libs/test2.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2022-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2022-2025 nanoseeds #include "lib2.hpp" int32_t main() { diff --git a/include/CMakeLists.txt b/include/CMakeLists.txt index 9bea74b3..5f1d9529 100644 --- a/include/CMakeLists.txt +++ b/include/CMakeLists.txt @@ -8,4 +8,4 @@ add_library(${PROJECT_NAME} INTERFACE) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(${PROJECT_NAME} INTERFACE Catch2::Catch2WithMain) -target_compile_definitions(${PROJECT_NAME} INTERFACE CS203_DSAA_TEST_MACRO) \ No newline at end of file +target_compile_definitions(${PROJECT_NAME} INTERFACE ALGORITHM_TEST_MACRO) \ No newline at end of file diff --git a/include/catch_main.hpp b/include/catch_main.hpp index 19427373..2affec69 100644 --- a/include/catch_main.hpp +++ b/include/catch_main.hpp @@ -1,12 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_INCLUDES_CATCH_MAIN_H -#define CS203_DSAA_TEMPLATE_INCLUDES_CATCH_MAIN_H +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_INCLUDES_CATCH_MAIN_H +#define ALGORITHM_TEMPLATE_INCLUDES_CATCH_MAIN_H // #include #include @@ -26,4 +21,4 @@ Copyright (C) 2020-2023 nanoseeds static const CS203_timer timer{}; -#endif //CS203_DSAA_TEMPLATE_INCLUDES_CATCH_MAIN_H +#endif //ALGORITHM_TEMPLATE_INCLUDES_CATCH_MAIN_H diff --git a/include/class_helper/nonable.hpp b/include/class_helper/nonable.hpp index dad2acc6..e4a96b03 100644 --- a/include/class_helper/nonable.hpp +++ b/include/class_helper/nonable.hpp @@ -1,13 +1,8 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2021-2025 nanoseeds -Copyright (C) 2021-2022 nanoseeds - -*/ - -#ifndef CS203_DSAA_TEMPLATE_INCLUDE_CLASS_HELPER_NONABLE_HPP -#define CS203_DSAA_TEMPLATE_INCLUDE_CLASS_HELPER_NONABLE_HPP +#ifndef ALGORITHM_TEMPLATE_INCLUDE_CLASS_HELPER_NONABLE_HPP +#define ALGORITHM_TEMPLATE_INCLUDE_CLASS_HELPER_NONABLE_HPP class noncopyable { protected: @@ -46,4 +41,4 @@ class nonCopyMoveAble : private noncopyable, nonmoveable { public: }; -#endif //CS203_DSAA_TEMPLATE_INCLUDE_CLASS_HELPER_NONABLE_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDE_CLASS_HELPER_NONABLE_HPP diff --git a/include/include/CS203_helper.hpp b/include/include/CS203_helper.hpp index 3a2f7389..a9378bb7 100644 --- a/include/include/CS203_helper.hpp +++ b/include/include/CS203_helper.hpp @@ -1,13 +1,7 @@ -/* -SPDX-License-Identifier: AGPL-3.0-or-later - -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_HELPER_HPP -#define CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_HELPER_HPP +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_HELPER_HPP +#define ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_HELPER_HPP static constexpr const double eps{0.00000001}, neps{-eps}; constexpr inline int32_t sign(int32_t x) { @@ -18,4 +12,4 @@ constexpr inline int32_t sign(double x) { return ((x < neps) ? -1 : (x > neps)); } -#endif //CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_HELPER_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_HELPER_HPP diff --git a/include/include/CS203_redirect.hpp b/include/include/CS203_redirect.hpp index 86f3746a..629caa20 100644 --- a/include/include/CS203_redirect.hpp +++ b/include/include/CS203_redirect.hpp @@ -1,18 +1,12 @@ /** - * @Github: https://github.com/Certseeds/CS203_DSAA_template * @Author: nanoseeds * @Date: 2020-07-24 01:56:19 * @LastEditors: nanoseeds */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_REDIRECT_HPP -#define CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_REDIRECT_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_REDIRECT_HPP +#define ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_REDIRECT_HPP #include #include @@ -54,7 +48,7 @@ class CS203_redirect final : private nonCopyMoveAble { } }; -#ifndef CS203_DSAA_TEST_MACRO +#ifndef ALGORITHM_TEST_MACRO /* if in this macro, it means it do not belong to ./test/lab_${number}/${x}_test.cpp so, it need define file_paths although it maybe do not need that @@ -65,6 +59,6 @@ std::string getFilePath() noexcept { } const std::string CS203_redirect::file_paths = getFilePath(); -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO -#endif //CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_REDIRECT_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_REDIRECT_HPP diff --git a/include/include/CS203_sequence.hpp b/include/include/CS203_sequence.hpp index 38b7e9f5..2c8937d5 100644 --- a/include/include/CS203_sequence.hpp +++ b/include/include/CS203_sequence.hpp @@ -1,18 +1,12 @@ /** - * @Github: https://github.com/Certseeds/CS203_DSAA_template * @Author: nanoseeds * @Date: 2020/9/19 21:42:36 * @LastEditors: nanoseeds */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_SEQUENCE_HPP -#define CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_SEQUENCE_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_SEQUENCE_HPP +#define ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_SEQUENCE_HPP #include #include @@ -105,4 +99,4 @@ class CS203_sequence final : private nonCopyMoveAble { } }; -#endif //CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_SEQUENCE_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_SEQUENCE_HPP diff --git a/include/include/CS203_timer.hpp b/include/include/CS203_timer.hpp index ebc7a013..8b6440b5 100644 --- a/include/include/CS203_timer.hpp +++ b/include/include/CS203_timer.hpp @@ -1,18 +1,7 @@ -/** - * @Github: https://github.com/Certseeds/CS203_DSAA_template - * @Author: nanoseeds - * @Date: 2020-07-15 21:42:36 - * @LastEditors: nanoseeds - */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_TIMER_HPP -#define CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_TIMER_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_TIMER_HPP +#define ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_TIMER_HPP #include #include @@ -34,4 +23,4 @@ class CS203_timer final : private nonCopyMoveAble { } }; -#endif //CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_CS203_TIMER_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_CS203_TIMER_HPP diff --git a/include/include/public.hpp b/include/include/public.hpp index 3e0d4744..334e232e 100644 --- a/include/include/public.hpp +++ b/include/include/public.hpp @@ -1,19 +1,13 @@ /* - * @Github: https://github.com/Certseeds/CS203_DSAA_template * @Author: nanoseeds * @Date: 2020-07-15 21:44:06 * @LastEditors: nanoseeds * @LastEditTime: 2021-01-03 21:46:26 */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_PUBLIC_HPP -#define CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_PUBLIC_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_PUBLIC_HPP +#define ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_PUBLIC_HPP #include #include @@ -53,4 +47,4 @@ inline bool compareFiles(std::string p1, std::string p2) { std::istreambuf_iterator(f2.rdbuf())); } -#endif //CS203_DSAA_TEMPLATE_INCLUDE_INCLUDE_PUBLIC_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDE_INCLUDE_PUBLIC_HPP diff --git a/include/list/listnode.hpp b/include/list/listnode.hpp index 13d3d420..0dd2e155 100644 --- a/include/list/listnode.hpp +++ b/include/list/listnode.hpp @@ -1,12 +1,8 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_INCLUDES_LISTNODE_HPP -#define CS203_DSAA_TEMPLATE_INCLUDES_LISTNODE_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +// SPDX +#ifndef ALGORITHM_TEMPLATE_INCLUDES_LISTNODE_HPP +#define ALGORITHM_TEMPLATE_INCLUDES_LISTNODE_HPP #include #include @@ -115,4 +111,4 @@ bool ListNode::equal(const std::initializer_list &nums, const ListNode return ListNode::equal(vector(nums), node); } } -#endif //CS203_DSAA_TEMPLATE_INCLUDES_LISTNODE_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDES_LISTNODE_HPP diff --git a/include/magic_macro/magic_macro.hpp b/include/magic_macro/magic_macro.hpp index 68c8c491..3879c89f 100644 --- a/include/magic_macro/magic_macro.hpp +++ b/include/magic_macro/magic_macro.hpp @@ -1,18 +1,12 @@ /** - * @Github: https://github.com/Certseeds/CS203_DSAA_template * @Author: nanoseeds * @Date: 2020-07-15 21:45:36 * @LastEditors: nanoseeds */ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_INCLUDES_MAGIC_MACRO_HPP -#define CS203_DSAA_TEMPLATE_INCLUDES_MAGIC_MACRO_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_INCLUDES_MAGIC_MACRO_HPP +#define ALGORITHM_TEMPLATE_INCLUDES_MAGIC_MACRO_HPP #pragma GCC optimize(3, "Ofast", "inline", "no-stack-protector", "unroll-loops") #pragma GCC optimize("-fgcse") @@ -58,4 +52,4 @@ Copyright (C) 2020-2023 nanoseeds #pragma GCC optimize("inline-functions-called-once") #pragma GCC optimize("-fdelete-null-pointer-checks") #pragma GCC target("avx,avx2,sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native") -#endif //CS203_DSAA_TEMPLATE_INCLUDES_MAGIC_MACRO_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDES_MAGIC_MACRO_HPP diff --git a/include/tree/treenode.hpp b/include/tree/treenode.hpp index e8a5e9d7..fe255441 100644 --- a/include/tree/treenode.hpp +++ b/include/tree/treenode.hpp @@ -1,12 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_INCLUDES_TREENODE_HPP -#define CS203_DSAA_TEMPLATE_INCLUDES_TREENODE_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_INCLUDES_TREENODE_HPP +#define ALGORITHM_TEMPLATE_INCLUDES_TREENODE_HPP #include #include @@ -74,4 +69,4 @@ static bool judge_equal(TreeNode *const root, const vector &vec) { } }; -#endif //CS203_DSAA_TEMPLATE_INCLUDES_TREENODE_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDES_TREENODE_HPP diff --git a/include/tree/treenode_link.hpp b/include/tree/treenode_link.hpp index 9860c3bc..03b14207 100644 --- a/include/tree/treenode_link.hpp +++ b/include/tree/treenode_link.hpp @@ -1,12 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_INCLUDE_TREE_TREENODE_LINK_HPP -#define CS203_DSAA_TEMPLATE_INCLUDE_TREE_TREENODE_LINK_HPP +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifndef ALGORITHM_TEMPLATE_INCLUDE_TREE_TREENODE_LINK_HPP +#define ALGORITHM_TEMPLATE_INCLUDE_TREE_TREENODE_LINK_HPP #include "tree/treenode.hpp" #include @@ -62,4 +57,4 @@ class TreeNodeLink final : private nonCopyMoveAble { }; } -#endif //CS203_DSAA_TEMPLATE_INCLUDE_TREE_TREENODE_LINK_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDE_TREE_TREENODE_LINK_HPP diff --git a/include/tree/treenode_multi.hpp b/include/tree/treenode_multi.hpp index 9712431c..895be6e6 100644 --- a/include/tree/treenode_multi.hpp +++ b/include/tree/treenode_multi.hpp @@ -1,13 +1,8 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2020-2025 nanoseeds -Copyright (C) 2020-2023 nanoseeds - -*/ - -#ifndef CS203_DSAA_TEMPLATE_INCLUDE_TREE_TREENODE_MULTI_HPP -#define CS203_DSAA_TEMPLATE_INCLUDE_TREE_TREENODE_MULTI_HPP +#ifndef ALGORITHM_TEMPLATE_INCLUDE_TREE_TREENODE_MULTI_HPP +#define ALGORITHM_TEMPLATE_INCLUDE_TREE_TREENODE_MULTI_HPP #include #include @@ -30,4 +25,4 @@ class TreeNodeMulti final : private nonCopyMoveAble { } -#endif //CS203_DSAA_TEMPLATE_INCLUDE_TREE_TREENODE_MULTI_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDE_TREE_TREENODE_MULTI_HPP diff --git a/include/tree/treenode_template.hpp b/include/tree/treenode_template.hpp index f4b4672b..992ba126 100644 --- a/include/tree/treenode_template.hpp +++ b/include/tree/treenode_template.hpp @@ -1,12 +1,8 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template +// SPDX-FileCopyrightText: 2021-2025 nanoseeds -Copyright (C) 2021 nanoseeds - -*/ -#ifndef CS203_DSAA_TEMPLATE_INCLUDE_TREE_TREENODE_TEMPLATE_HPP -#define CS203_DSAA_TEMPLATE_INCLUDE_TREE_TREENODE_TEMPLATE_HPP +#ifndef ALGORITHM_TEMPLATE_INCLUDE_TREE_TREENODE_TEMPLATE_HPP +#define ALGORITHM_TEMPLATE_INCLUDE_TREE_TREENODE_TEMPLATE_HPP #include namespace TREE_NODE_TEMP { template typename CLASS> @@ -30,4 +26,4 @@ struct TreeNodeTemp : private nonCopyMoveAble { friend CLASS; }; } -#endif //CS203_DSAA_TEMPLATE_INCLUDE_TREE_TREENODE_TEMPLATE_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDE_TREE_TREENODE_TEMPLATE_HPP diff --git a/include/tree/trie.hpp b/include/tree/trie.hpp index d727a1f0..fc3fb08e 100644 --- a/include/tree/trie.hpp +++ b/include/tree/trie.hpp @@ -2,8 +2,8 @@ // Created by nanos on 2021/12/8. // -#ifndef CS203_DSAA_TEMPLATE_INCLUDE_TREE_TRIE_TRIE_HPP -#define CS203_DSAA_TEMPLATE_INCLUDE_TREE_TRIE_TRIE_HPP +#ifndef ALGORITHM_TEMPLATE_INCLUDE_TREE_TRIE_TRIE_HPP +#define ALGORITHM_TEMPLATE_INCLUDE_TREE_TRIE_TRIE_HPP #include #include @@ -144,4 +144,4 @@ struct trie : public TrieTemplate { }; } -#endif //CS203_DSAA_TEMPLATE_INCLUDE_TREE_TRIE_TRIE_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDE_TREE_TRIE_TRIE_HPP diff --git a/include/tree/trie_base.hpp b/include/tree/trie_base.hpp index 79660542..b720b8c8 100644 --- a/include/tree/trie_base.hpp +++ b/include/tree/trie_base.hpp @@ -2,8 +2,8 @@ // Created by nanos on 2021/12/8. // -#ifndef CS203_DSAA_TEMPLATE_INCLUDE_TREE_TRIE_BASE_HPP -#define CS203_DSAA_TEMPLATE_INCLUDE_TREE_TRIE_BASE_HPP +#ifndef ALGORITHM_TEMPLATE_INCLUDE_TREE_TRIE_BASE_HPP +#define ALGORITHM_TEMPLATE_INCLUDE_TREE_TRIE_BASE_HPP #include #include @@ -37,4 +37,4 @@ struct TrieTemplate : private nonCopyMoveAble { virtual bool startsWith(string::const_iterator cb, string::const_iterator ce) const = 0; }; } -#endif //CS203_DSAA_TEMPLATE_INCLUDE_TREE_TRIE_BASE_HPP +#endif //ALGORITHM_TEMPLATE_INCLUDE_TREE_TRIE_BASE_HPP diff --git a/lab_00/.gitattributes b/lab_00/.gitattributes index 0772a445..02d18e56 100644 --- a/lab_00/.gitattributes +++ b/lab_00/.gitattributes @@ -1,5 +1,4 @@ ### - # @Github: https://github.com/Certseeds/CS203_DSAA_template # @Author: nanoseeds # @Date: 2021-01-28 16:49:38 # @LastEditors: nanoseeds diff --git a/lab_00/lab_00_A/CMakeLists.txt b/lab_00/lab_00_A/CMakeLists.txt index 41fc7dbf..354751e1 100644 --- a/lab_00/lab_00_A/CMakeLists.txt +++ b/lab_00/lab_00_A/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/lab_00/lab_00_A/lab_00_A.cpp b/lab_00/lab_00_A/lab_00_A.cpp index 3892ee0e..0e1da72f 100644 --- a/lab_00/lab_00_A/lab_00_A.cpp +++ b/lab_00/lab_00_A/lab_00_A.cpp @@ -1,15 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_00_A{ #endif using std::tie; @@ -65,6 +60,6 @@ static const auto faster_streams = [] { return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/lab_00/lab_00_A/lab_00_A_test.cpp b/lab_00/lab_00_A/lab_00_A_test.cpp index 154637ad..0ea0e60b 100644 --- a/lab_00/lab_00_A/lab_00_A_test.cpp +++ b/lab_00/lab_00_A/lab_00_A_test.cpp @@ -1,11 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include @@ -58,4 +53,4 @@ TEST_CASE("test case 4", "[test 00 A]") { CHECK(1100 == output); } } // namespace lab_00_A -#endif // CS203_DSAA_TEST_MACRO +#endif // ALGORITHM_TEST_MACRO diff --git a/lab_00/lab_00_B/CMakeLists.txt b/lab_00/lab_00_B/CMakeLists.txt index 571102e9..c490830a 100644 --- a/lab_00/lab_00_B/CMakeLists.txt +++ b/lab_00/lab_00_B/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/lab_00/lab_00_B/lab_00_B.cpp b/lab_00/lab_00_B/lab_00_B.cpp index 4298fa55..5d4de870 100644 --- a/lab_00/lab_00_B/lab_00_B.cpp +++ b/lab_00/lab_00_B/lab_00_B.cpp @@ -1,18 +1,14 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds // id: 1250 #include #include #include #include #include +#include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_00_B{ #endif using std::cin; @@ -91,6 +87,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/lab_00/lab_00_B/lab_00_B_test.cpp b/lab_00/lab_00_B/lab_00_B_test.cpp index 149be502..8507e954 100644 --- a/lab_00/lab_00_B/lab_00_B_test.cpp +++ b/lab_00/lab_00_B/lab_00_B_test.cpp @@ -1,11 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include @@ -43,4 +38,4 @@ TEST_CASE("test case 2", "[test 00 B]") { CHECK_THAT(result, Equals(what_we_want)); } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/lab_00/lab_00_C/CMakeLists.txt b/lab_00/lab_00_C/CMakeLists.txt index 9f6901c1..e14261f1 100644 --- a/lab_00/lab_00_C/CMakeLists.txt +++ b/lab_00/lab_00_C/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/lab_00/lab_00_C/lab_00_C.cpp b/lab_00/lab_00_C/lab_00_C.cpp index 8b635711..357140b1 100644 --- a/lab_00/lab_00_C/lab_00_C.cpp +++ b/lab_00/lab_00_C/lab_00_C.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds #include #include #include @@ -39,7 +34,7 @@ then there will be X unrepeated numbers ∈ [0,N-1] // id: 785 // Graph // 判断二分图*/ -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_00_C{ #endif using std::cin; @@ -130,6 +125,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/lab_00/lab_00_C/lab_00_C_test.cpp b/lab_00/lab_00_C/lab_00_C_test.cpp index 1715c2d6..a6eed29c 100644 --- a/lab_00/lab_00_C/lab_00_C_test.cpp +++ b/lab_00/lab_00_C/lab_00_C_test.cpp @@ -1,11 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include @@ -117,4 +112,4 @@ TEST_CASE("test case with sequence", "[test 00 C]") { } } } -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/lab_00/lab_00_D/CMakeLists.txt b/lab_00/lab_00_D/CMakeLists.txt index ffff7238..dce330ce 100644 --- a/lab_00/lab_00_D/CMakeLists.txt +++ b/lab_00/lab_00_D/CMakeLists.txt @@ -9,8 +9,8 @@ enable_testing() add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${PROJECT_NAME}_test ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp) -target_compile_definitions(${PROJECT_NAME}_test PRIVATE CS203_DSAA_TEST_MACRO) -target_link_libraries(${PROJECT_NAME}_test PRIVATE CS203_DSAA_template_INCLUDE) +target_compile_definitions(${PROJECT_NAME}_test PRIVATE ALGORITHM_TEST_MACRO) +target_link_libraries(${PROJECT_NAME}_test PRIVATE algorithm_template_INCLUDE) MESSAGE(STATUS "${PROJECT_NAME}_${elementName} from ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_ORDER}_${PROBLEM_ORDER}_test.cpp") add_test(${PROJECT_NAME}_CTEST ${PROJECT_NAME}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/lab_00/lab_00_D/lab_00_D.cpp b/lab_00/lab_00_D/lab_00_D.cpp index 6891f877..6449ec6b 100644 --- a/lab_00/lab_00_D/lab_00_D.cpp +++ b/lab_00/lab_00_D/lab_00_D.cpp @@ -1,10 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ +// SPDX-FileCopyrightText: 2020-2025 nanoseeds // https://www.luogu.com.cn/problem/P1058 // luogu // id: P1058 @@ -13,7 +8,7 @@ Copyright (C) 2020-2023 nanoseeds #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_00_D{ #endif using std::cin; @@ -113,6 +108,6 @@ static const auto faster_streams = [] { // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO } #endif diff --git a/lab_00/lab_00_D/lab_00_D_test.cpp b/lab_00/lab_00_D/lab_00_D_test.cpp index c195aeca..9367b2ee 100644 --- a/lab_00/lab_00_D/lab_00_D_test.cpp +++ b/lab_00/lab_00_D/lab_00_D_test.cpp @@ -1,11 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/* -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds - -*/ -#ifdef CS203_DSAA_TEST_MACRO +// SPDX-FileCopyrightText: 2020-2025 nanoseeds +#ifdef ALGORITHM_TEST_MACRO #include #include @@ -47,4 +42,4 @@ TEST_CASE("test case 2", "[test 00 D]") { } } // namespace lab_00_D -#endif // CS203_DSAA_TEST_MACRO +#endif // ALGORITHM_TEST_MACRO diff --git a/script/cmake_level2_template.txt b/script/cmake_level2_template.txt index 3dc750f6..5a125db7 100644 --- a/script/cmake_level2_template.txt +++ b/script/cmake_level2_template.txt @@ -9,9 +9,9 @@ enable_testing() add_executable(${{PROJECT_NAME}} ${{CMAKE_CURRENT_SOURCE_DIR}}/${{PROJECT_ORDER}}_${{PROBLEM_ORDER}}.cpp) set(CMAKE_CXX_STANDARD 17) add_executable(${{PROJECT_NAME}}_test ${{CMAKE_CURRENT_SOURCE_DIR}}/${{PROJECT_ORDER}}_${{PROBLEM_ORDER}}_test.cpp) -target_compile_definitions(${{PROJECT_NAME}}_test PRIVATE CS203_DSAA_TEST_MACRO) +target_compile_definitions(${{PROJECT_NAME}}_test PRIVATE ALGORITHM_TEST_MACRO) target_link_libraries(${{PROJECT_NAME}}_test PRIVATE - CS203_DSAA_template_INCLUDE) + algorithm_template_INCLUDE) MESSAGE(STATUS "${{PROJECT_NAME}} from ${{CMAKE_CURRENT_SOURCE_DIR}}/${{PROJECT_ORDER}}_${{PROBLEM_ORDER}}.cpp") add_test(${{PROJECT_NAME}}_CTEST ${{PROJECT_NAME}}_test) set(CMAKE_CXX_STANDARD 11) diff --git a/script/cpp_template.txt b/script/cpp_template.txt index 31c9d259..cd8e0c2a 100644 --- a/script/cpp_template.txt +++ b/script/cpp_template.txt @@ -6,13 +6,15 @@ #include #include #include +#include +#include #include #include #include #include #include -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO namespace lab_{0}_{1}{{ #endif @@ -77,6 +79,6 @@ static const auto faster_streams = [] {{ // 关闭c++风格输入输出 , 与C风格输入输出的同步,提高性能. return 0; }}(); -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO }} #endif diff --git a/script/cpp_test_template.txt b/script/cpp_test_template.txt index abde51b9..a565c4ed 100644 --- a/script/cpp_test_template.txt +++ b/script/cpp_test_template.txt @@ -1,8 +1,10 @@ -#ifdef CS203_DSAA_TEST_MACRO +#ifdef ALGORITHM_TEST_MACRO #include #include #include +#include +#include #include #include "lab_{0}_{1}.cpp" @@ -54,4 +56,4 @@ TEST_CASE("test case with sequence", "[test {0}_{1}]") {{ }} }} }} -#endif //CS203_DSAA_TEST_MACRO +#endif //ALGORITHM_TEST_MACRO diff --git a/script/file_header.txt b/script/file_header.txt index 5aa9ac73..7d4bdab4 100644 --- a/script/file_header.txt +++ b/script/file_header.txt @@ -1,11 +1,2 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -/** - * @Github: https://github.com/{0}/{1} - * @Author: {2} - * @Date: {3} - * @LastEditors: {2} - */ -/* -{1} -Copyright (C) 2020-{4} {2} -*/ +// SPDX-FileCopyrightText: 2020-{0} {1} diff --git a/script/file_template.py b/script/file_template.py index 77c0676d..ed463dbb 100644 --- a/script/file_template.py +++ b/script/file_template.py @@ -4,9 +4,7 @@ SPDX-License-Identifier: AGPL-3.0-or-later -CS203_DSAA_template - -Copyright (C) 2020-2023 nanoseeds +SPDX-FileCopyrightText: 2020-2025 nanoseeds """ import os @@ -19,11 +17,8 @@ level1_cmake_template: str level2_cmake_template: str test_cmake_template: str -GITHUB_USER: str = 'Certseeds' # replace it with your github name # example: Certseeds USER: str = 'nanoseeds' # replace it with your user name # example: nanoseeds -REPO_NAME: str = 'CS203_DSAA_template' # replace it with your github repo name # example: CS203_DSAA_template year: str = time.strftime('%Y', time.localtime()) -create_time: str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) main_cmake_path: str = './../CMakeLists.txt' @@ -37,14 +32,12 @@ def read_file(file_name: str) -> str: def fill_file(lab_number: str, problem_order: str) -> None: with open(f'./../lab_{lab_number}/lab_{lab_number}_{problem_order}/lab_{lab_number}_{problem_order}.cpp', mode='a+', encoding='UTF-8') as file: - file.write(file_header_template.format( - GITHUB_USER, REPO_NAME, USER, create_time, year)) + file.write(file_header_template.format(year, USER)) file.write(main_code_template.format(lab_number, problem_order)) print('main finish') with open(f'./../lab_{lab_number}/lab_{lab_number}_{problem_order}/lab_{lab_number}_{problem_order}_test.cpp', mode='a+', encoding='UTF-8') as file: - file.write(file_header_template.format( - GITHUB_USER, REPO_NAME, USER, create_time, year)) + file.write(file_header_template.format(year, USER)) file.write(test_code_template.format(lab_number, problem_order)) print('test finish') diff --git a/script/test.sh b/script/test.sh index b5a0c91b..8150bca5 100755 --- a/script/test.sh +++ b/script/test.sh @@ -1,7 +1,6 @@ #!/usr/bin/env bash set -eoux pipefail ### -# @Github: https://github.com/Certseeds/CS203_DSAA_template # @Author: nanoseeds # @Date: 2020-07-27 21:48:41 ### diff --git a/third_party/.gitattributes b/third_party/.gitattributes index 7f331e7f..143919d0 100644 --- a/third_party/.gitattributes +++ b/third_party/.gitattributes @@ -1,5 +1,4 @@ ### - # @Github: https://github.com/Certseeds/CS203_DSAA_template # @Author: nanoseeds # @Date: 2021-01-28 16:49:38 # @LastEditors: nanoseeds diff --git a/third_party/.gitignore b/third_party/.gitignore index f618dbe5..29fc65e5 100644 --- a/third_party/.gitignore +++ b/third_party/.gitignore @@ -2,4 +2,4 @@ !.gitattributes !.gitignore !CMakeLists.txt -!CMakeLists.release.txt \ No newline at end of file +!CMakeLists.release.txt diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt index 17ef25d8..01d017b6 100644 --- a/third_party/CMakeLists.txt +++ b/third_party/CMakeLists.txt @@ -6,8 +6,8 @@ set("BUILD_${LIB_WAY}_LIBS" YES) Include(FetchContent) CMAKE_CMP_0135() -set(CATCH2_URL https://github.com/catchorg/Catch2/archive/refs/tags/v3.3.1.tar.gz) -set(CATCH2_HASH "5cdc99f93e0b709936eb5af973df2a5c") +set(CATCH2_URL https://github.com/catchorg/Catch2/archive/refs/tags/v3.10.0.tar.gz) +set(CATCH2_HASH "c2fef0ffbe8af6b20e86f8d0e79b6aac") if (${CMAKE_BUILD_TYPE} STREQUAL "Debug") FetchContent_Declare( Catch2