diff --git a/cpp/more/0001.cpp b/cpp/more/0001.cpp new file mode 100644 index 0000000..bc3b79e --- /dev/null +++ b/cpp/more/0001.cpp @@ -0,0 +1,27 @@ +#include +#include + +/** + * 1. Two Sum + * Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. + * You may assume that each input would have exactly one solution, and you may not use the same element twice. + * You can return the answer in any order. + */ + +class Solution { +public: + static std::vector twoSum(const std::vector& nums, int target) { + std::unordered_multiset s(nums.begin(), nums.end()); + for (int i : s) { + if (s.count(target - i) > (i == target - i ? 1 : 0)) { + int x = 0, y = nums.size() - 1; + while (nums[x] != i) + ++x; + while (nums[y] != target - i) + --y; + return {x, y}; + } + } + return {}; + } +}; diff --git a/cpp/more/CMakeLists.txt b/cpp/more/CMakeLists.txt index 3dd6e05..7b4aa9b 100644 --- a/cpp/more/CMakeLists.txt +++ b/cpp/more/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(more) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(more 0021.cpp) +ADD_EXECUTABLE(more 0001.cpp)