add: 0001 [cpp]
This commit is contained in:
parent
7ffcac9824
commit
2ba7f554d7
|
|
@ -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 {};
|
||||
}
|
||||
};
|
||||
|
|
@ -3,4 +3,4 @@ PROJECT(more)
|
|||
|
||||
SET(CMAKE_CXX_STANDARD 23)
|
||||
|
||||
ADD_EXECUTABLE(more 0021.cpp)
|
||||
ADD_EXECUTABLE(more 0001.cpp)
|
||||
|
|
|
|||
Loading…
Reference in New Issue