2023每日刷题(四十一)
Leetcode—18.四数之和
实现代码
class Solution {
public:vector<vector<int>> fourSum(vector<int>& nums, int target) {vector<vector<int>> ans;sort(nums.begin(), nums.end());int n = nums.size();int i, j, k, h;long long s, x, y;for(i = 0; i < n - 3; i++) {x = nums[i];// 除重if(i > 0 && x == nums[i - 1]) {continue;}if(x + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {break;}if(x + nums[n - 1] + nums[n - 2] + nums[n - 3] < target) {continue;}// 除重for(h = i + 1; h < n - 2; h++) {y = nums[h];if(h > i + 1 && y == nums[h - 1]) {continue;}if(x + y + nums[h + 1] + nums[h + 2] > target) {break;}if(x + y + nums[n - 1] + nums[n - 2] < target) {continue;}j = h + 1;k = n - 1;while(j < k) {s = x + y + nums[j] + nums[k];if(s > target) {k--;} else if(s < target) {j++;} else {vector<int> res;res.push_back((int)x);res.push_back((int)y);res.push_back(nums[j]);res.push_back(nums[k]);ans.push_back(res);j++;while(j < k && nums[j] == nums[j - 1]) {j++;}k--;while(j < k && nums[k] == nums[k + 1]) {k--;}}}}}return ans;}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!