From 8e77a6ead023cd794cecdcd9fb063e925bc5df59 Mon Sep 17 00:00:00 2001 From: Kirito <1362050620@qq.com> Date: Tue, 19 Jun 2018 14:18:58 +0800 Subject: [PATCH] Create 1.cpp --- LeetCode-CN/1.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 LeetCode-CN/1.cpp diff --git a/LeetCode-CN/1.cpp b/LeetCode-CN/1.cpp new file mode 100644 index 0000000..a688b76 --- /dev/null +++ b/LeetCode-CN/1.cpp @@ -0,0 +1,41 @@ +#include + +bool cmp(const pair& a, const pair& b) +{ + return a.first < b.first; +} + +class Solution { +public: + vector twoSum(vector& nums, int target) { + int len = nums.size(); + vector< pair > vp; + for (int i = 0; i < len; i++) + { + vp.push_back(std::make_pair(nums[i], i)); + } + sort(vp.begin(), vp.end(), cmp); + + int L = 0; + int R = len - 1; + while (L < R) + { + int sum = vp[L].first + vp[R].first; + if (sum == target) + { + vector v; + v.push_back(vp[L].second); + v.push_back(vp[R].second); + return v; + } + else if (sum < target) + { + L++; + } + else if (sum > target) + { + R--; + } + } + } +};