leetcode 16 3Sum
阿新 • • 發佈:2018-08-29
gin end 相同 i++ tco sort num leet else
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> result; std::sort(nums.begin(),nums.end()); for(int i = 0;i < nums.size();i++){ int target = 0 - nums[i]; int first = i+1; int end = nums.size() - 1; while(first < end){ if(nums[first] + nums[end] == target){ vector<int> res; int num1 = nums[first]; int num2 = nums[end]; res.push_back(nums[i]); res.push_back(num1); res.push_back(num2); result.push_back(res);while(first < end && nums[first] == num1) first++; 相同的數字過濾掉 while(first < end && nums[end] == num2) end--; 相同的數字過濾掉 } else if(nums[first] + nums[end] < target) first++; else end--; } while (i + 1 < nums.size() && nums[i + 1] == nums[i]) i++; 相同的數字過濾掉 } return result; } };
leetcode 16 3Sum