add: 0001 [cpp]

This commit is contained in:
Lam Haoyin 2022-03-30 21:00:50 +08:00
parent 7ffcac9824
commit 2ba7f554d7
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 28 additions and 1 deletions

27
cpp/more/0001.cpp Normal file
View File

@ -0,0 +1,27 @@
#include <vector>
#include <unordered_set>
/**
* 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<int> twoSum(const std::vector<int>& nums, int target) {
std::unordered_multiset<int> 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 {};
}
};

View File

@ -3,4 +3,4 @@ PROJECT(more)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(more 0021.cpp) ADD_EXECUTABLE(more 0001.cpp)