From 5d4fec3a1153bec37be57d3a7a2f47eb63a2af56 Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Mon, 10 Feb 2025 23:58:08 +0800 Subject: [PATCH] feat: 1_two_sum --- 1_two_sum/main.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 1_two_sum/main.cpp diff --git a/1_two_sum/main.cpp b/1_two_sum/main.cpp new file mode 100644 index 0000000..7df0740 --- /dev/null +++ b/1_two_sum/main.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; + +class Solution { +public: + vector twoSum(vector& nums, int target) { + unordered_map> mp; + for (int i = 0; i < nums.size(); i++) { + if (mp.find(nums[i]) == mp.end()) { + mp[nums[i]] = vector(); + } + mp[nums[i]].emplace_back(i); + } + + for (auto &[x, y] : mp) { + } + + sort(nums.begin(), nums.end()); + + for (int i = nums.size() - 1; i >= 0; i--) { + int x = nums[i]; + int need = target - x; + + if (binary_search(nums.begin(), nums.begin() + i, need)) { + if (x == need) { + return {mp[x][0], mp[need][1]}; + } + return {mp[x][0], mp[need][0]}; + } + } + + return {}; + } +};