Skip to content

Commit

Permalink
add 724.
Browse files Browse the repository at this point in the history
  • Loading branch information
tangs committed Jul 8, 2024
1 parent 0085543 commit a826aa8
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/724/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include <vector>
#include <numeric>

using namespace std;

//给你一个整数数组 nums ,请计算数组的 中心下标 。
//数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
//如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。
//如果数组有多个中心下标,应该返回 最靠近左边 的那一个。如果数组不存在中心下标,返回 -1 。

class Solution {
public:
int pivotIndex(vector<int>&& nums) {
const auto len = nums.size();
nums.push_back(0);

auto left = 0;
auto right = std::accumulate(nums.begin() + 1, nums.end(), 0);

if (left == right) return 0;

for (int i = 0; i < len; ++i) {
if (left == right) return i;

left += nums[i];
right -= nums[i + 1];
}

return -1;
}
};
37 changes: 37 additions & 0 deletions tests/724/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
cmake_minimum_required(VERSION 3.10)
project(dp_solution_pipeline)

set(CMAKE_CXX_STANDARD 17)

set(PROBLEM_NAME 724)

include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)

set(SRC_ROOT_PATH ${ROOT_PATH}/src)
set(SRC_PATH ${SRC_ROOT_PATH}/${PROBLEM_NAME})
set(TESTS_PATH ${ROOT_PATH}/tests/${PROBLEM_NAME})

include_directories(
${SRC_ROOT_PATH}
${SRC_PATH}
${TESTS_PATH}
)

# test.
enable_testing()

add_executable(
test_${PROBLEM_NAME}
${TESTS_PATH}/test.cc
)
target_link_libraries(test_${PROBLEM_NAME} GTest::gtest_main)


include(GoogleTest)
gtest_discover_tests(test_${PROBLEM_NAME})
13 changes: 13 additions & 0 deletions tests/724/test.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#include <gtest/gtest.h>

#include "utils/utils.h"
#include "solution.hpp"

TEST(testing, BasicAssertions) {
Solution solution;
EXPECT_EQ(solution.pivotIndex(std::vector{1, 7, 3, 6, 5, 6}), 3);
EXPECT_EQ(solution.pivotIndex({1, 2, 3}), -1);
EXPECT_EQ(solution.pivotIndex({2, 1, -1}), 0);
EXPECT_EQ(solution.pivotIndex({2, 1, -3}), -1);
EXPECT_EQ(solution.pivotIndex({-2, 2, -3}), 2);
}
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ add_subdirectory(221)
add_subdirectory(5)
add_subdirectory(139)
add_subdirectory(3303)
add_subdirectory(724)

0 comments on commit a826aa8

Please sign in to comment.