Leetcode 015 3Sum(Twopoint)

题目连接:Leetcode 015 3Sum

解题思路:将数组排序,枚举一个数,剩下两个数在数组中用 Leetcode 001 中的方法找到,移动指针的时候需要注意相同数字的情况。

class Solution {
	public:
		vector<vector<int>> threeSum(vector<int>& nums) {
			vector<vector<int>> ret;
			sort(nums.begin(), nums.end());

			int n = nums.size(), i = 0;
			while (i < n) {
				int a = nums[i];
				int j = i + 1, k = n - 1;; 

				while (j < k) {
					int b = nums[j], c = nums[k];
					int s = a + b + c;

					if (s == 0) ret.push_back({a, b, c});
					if (s <= 0) while (j < k && nums[j] == b) j++;
					if (s >= 0) while (j < k && nums[k] == c) k--;
				}
				while (nums[i] == a && i < n) i++;
			}
			return ret;
		}
};

猜你喜欢

转载自blog.csdn.net/u011328934/article/details/80601584