https://leetcode.com/problems/two-sum/
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> index(2,0); vector<int> n2; int numsSize = nums.size(); int f = -1; for(int i = 0;i < numsSize;i++){ n2.push_back(nums[i]); if(nums[i] == target/2 && target%2 ==0){ if(f != -1){ index[0] = min(f,i + 1); index[1] = max(f,i + 1); return index; } else f = i + 1; } } sort(nums.begin(),nums.end()); for(int i = 0;i < numsSize;i++){ int j = lower_bound(nums.begin(),nums.end(),target - nums[i]) - nums.begin(); int a,b; if(nums[i] + nums[j] == target && j < numsSize){ for(int k = 0;k < numsSize;k++){ if(nums[i] == n2[k]) a = k + 1; if(nums[j] == n2[k]) b = k + 1; } index[0] = min(a,b); index[1] = max(a,b); } } return index; } };
时间: 2024-09-16 09:42:51