Leetcode 001 Two Sum (Towpoint)

xiaoxiao2021-02-28  4

题目连接:Leetcode 001 Two Sum

解题思路:将数组排序,然后左指针从数组起始位置开始,右指针从数组终止位置开始。如果两个指针指向的值的和小于目标值,移动左指针,如果和大于目标值,移动右指针,直到和等于目标值。

class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); int l = 0, r = nums.size() - 1; while (l < r) { while (nums[l] + nums[r] < target) l++; if (nums[l] + nums[r] == target) break; r--; } vector<int> ans; ans.push_back(l); ans.push_back(r); return ans; } };
转载请注明原文地址: https://www.6miu.com/read-2400059.html

最新回复(0)