三指针
C++
| vector<vector<int>> threeSum(vector<int>& nums) |
| { |
| vector<vector<int>> ans; |
| int n = nums.size(); |
| sort(nums.begin(), nums.end()); |
| for (int first = 0; first < n; first++) |
| { |
| if (first > 0 && nums[first] == nums[first - 1]) |
| continue; |
| int third = n - 1; |
| int target = -nums[first]; |
| for (int second = first + 1; second < n; ++second) |
| { |
| if (second > first + 1 && nums[second] == nums[second - 1]) |
| continue; |
| while (second < third && nums[second] + nums[third] > target) { |
| --third; |
| } |
| if (third == second) |
| break; |
| if (nums[second] + nums[third] == target) |
| { |
| ans.push_back({ nums[first],nums[second],nums[third] }); |
| |
| } |
| |
| } |
| |
| |
| } |
| return ans; |
| } |
C
| |
| |
| |
| |
| |
| int compInt(const void *a, const void *b) |
| { |
| return *(int*)a - *(int*)b; |
| } |
| int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){ |
| *returnSize = 0; |
| |
| if(nums == NULL || numsSize < 3) |
| { |
| return NULL; |
| } |
| |
| |
| qsort(nums,numsSize, sizeof(int),compInt); |
| |
| |
| int **ans = (int**)malloc(sizeof(int*) * (numsSize) * (numsSize)); |
| *returnColumnSizes = (int*)malloc(sizeof(int) * (numsSize) * (numsSize)); |
| |
| |
| |
| int cur = 0; |
| int low = cur + 1; |
| int high = numsSize - 1; |
| |
| |
| while (nums[cur] <= 0 && (cur + 1) < (numsSize - 1) ) |
| { |
| low = cur + 1; |
| high = numsSize - 1; |
| |
| |
| while (low < high) |
| { |
| int sum = nums[low] + nums[cur] + nums[high]; |
| if( 0 == sum ) |
| { |
| ans[*returnSize] = (int*)malloc(sizeof(int)*3); |
| ans[*returnSize][0] = nums[cur]; |
| ans[*returnSize][1] = nums[low]; |
| ans[*returnSize][2] = nums[high]; |
| |
| (*returnColumnSizes)[*returnSize] = 3; |
| (*returnSize)++; |
| |
| |
| while( (nums[low] == nums[++low]) && (low < high)); |
| while( (nums[high] == nums[--high]) && (low < high)); |
| } |
| else if (0 < sum) |
| { |
| high--; |
| } |
| else |
| { |
| low++; |
| } |
| |
| } |
| |
| while (nums[cur] == nums[++cur] && (cur + 1 < numsSize - 1) ); |
| } |
| |
| return ans; |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步