原题目
原题输入的数组是无序的,使用双指针来解题的时候遇到了问题。如果修改题目条件为输入的数组都是降序或者升序排列,那么就可以使用双指针法
code
#include#include #include using namespace std; class Solution { public: vector twoSum(vector & nums, int target) { vector ress; int left; int right; sort(nums.begin(), nums.end()); for (int left = 0; left < nums.size(); left++) { if (nums[left] > target) { return ress; } right = nums.size() - 1; while (right > left) { while (right > left && nums[left] + nums[right] > target) { right--; } while (right > left && nums[left] + nums[right] < target) { left++; } if (nums[right] + nums[left] == target) { ress = { left,right }; return ress; } else { continue; } } } return ress; } }; int main() { vector A{ 2,3,4 }; Solution SS; vector res = SS.twoSum(A, 5); cout << "[" << res[0] << "," << res[1] << "]" << endl; return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)