fix: using l, r index to find target
This commit is contained in:
parent
9c470bd055
commit
c6ffc0f727
@ -2,30 +2,26 @@
|
|||||||
using namespace std;
|
using namespace std;
|
||||||
|
|
||||||
class Solution {
|
class Solution {
|
||||||
public:
|
public:
|
||||||
vector<int> twoSum(vector<int>& nums, int target) {
|
vector<int> twoSum(vector<int>& nums, int target) {
|
||||||
unordered_map<int, vector<int>> mp;
|
unordered_multimap<int, int> mp;
|
||||||
for (int i = 0; i < nums.size(); i++) {
|
for (int i = 0; i < nums.size(); i++) {
|
||||||
if (mp.find(nums[i]) == mp.end()) {
|
mp.insert({nums[i], i});
|
||||||
mp[nums[i]] = vector<int>();
|
|
||||||
}
|
|
||||||
mp[nums[i]].emplace_back(i);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (auto &[x, y] : mp) {
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sort(nums.begin(), nums.end());
|
sort(nums.begin(), nums.end());
|
||||||
|
|
||||||
for (int i = nums.size() - 1; i >= 0; i--) {
|
int l = 0, r = nums.size() - 1;
|
||||||
int x = nums[i];
|
while (l < r) {
|
||||||
int need = target - x;
|
if (nums[l] + nums[r] < target) {
|
||||||
|
l++;
|
||||||
if (binary_search(nums.begin(), nums.begin() + i, need)) {
|
} else if (nums[l] + nums[r] > target) {
|
||||||
if (x == need) {
|
r--;
|
||||||
return {mp[x][0], mp[need][1]};
|
} else {
|
||||||
|
if (nums[l] == nums[r]) {
|
||||||
|
return {mp.find(nums[l])->second, (++mp.find(nums[r]))->second};
|
||||||
}
|
}
|
||||||
return {mp[x][0], mp[need][0]};
|
return {mp.find(nums[l])->second, mp.find(nums[r])->second};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user