经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 其他 » 职业生涯 » 查看文章
3Sum(or k_Sum)
来源:cnblogs  作者:康托漫步  时间:2018/9/25 19:24:46  对本文有异议

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

  1. Given array nums = [-1, 0, 1, 2, -1, -4],
  2.  
  3. A solution set is:
  4. [
  5. [-1, 0, 1],
  6. [-1, -1, 2]
  7. ]
    (4Sum问题)
    C++:
  1. 1 class Solution {
  2. 2 public:
  3. 3 vector<vector<int>> threeSum(vector<int>& nums) {
  4. 4 vector<vector<int>> result;
  5. 5 if (nums.size() <= 2)return result;
  6. 6 sort(nums.begin(), nums.end());
  7. 7 for (int i = 0; i < nums.size() - 2; i++) {
  8. 8 int a = nums[i];
  9. 9 if (a > 0) break;
  10. 10 if (i > 0 && a == nums[i - 1]) continue;
  11. 11 for (long j = i + 1, k = nums.size() - 1; j < k;) {
  12. 12 int b = nums[j];
  13. 13 int c = nums[k];
  14. 14 int value = a + b + c;
  15. 15 if (value == 0) {
  16. 16 result.push_back(vector<int>({ a, b, c }));
  17. 17 while (b == nums[++j] && j<k);
  18. 18 while (c == nums[--k] && j<k);
  19. 19 }
  20. 20 else if (value > 0) {
  21. 21 k--;
  22. 22 }
  23. 23 else {
  24. 24 j++;
  25. 25 }
  26. 26 }
  27. 27 }
  28. 28 return result;
  29. 29 }
  30. 30 };

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号