Leet Code OJ 15. 3Sum[Difficulty: Medium]
来源:互联网 发布:网络都市小说大纲模板 编辑:程序博客网 时间:2024/06/05 19:28
Leet Code OJ 15. 3Sum[Difficulty: Medium]
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
翻译:
给定一个数组S,它包含n个整数,它是否存在3个元素a,b,c,满足a+b+c=0?找出所有满足条件的元素数组。
提示:a,b,c三个元素必须是升序排列(也就是满足a ≤ b ≤ c),最终的结果不能包含重复的元素数组。例如给定S为{-1 0 1 2 -1 -4},返回结果是(-1, 0, 1)和(-1, -1, 2)。
思路分析:
直接想到的方法就是多重循环遍历所有可能的元素,进行判断是否等于0。
先把我的代码贴出来,后面在写优化的算法
#include <stdio.h>#include <stdlib.h>#include <string>int main(){ int buf[] = { -1, 0, 1, 2, -1, -4 }; int lenth = sizeof(buf) / sizeof(buf[0]); int space[10][3] = {0}; int num = 0; bool flag = true; for (int i = 0; i < lenth - 1; i++) { for (int j = i + 1; j < lenth; j++) { for (int k = j + 1; k < lenth; k++) { int result = buf[i] + buf[j] + buf[k]; if (result == 0) { int t; if (buf[i] > buf[j]) { t = buf[i]; buf[i] = buf[j]; buf[j] = t; } if (buf[i] > buf[k]) { t = buf[i]; buf[i] = buf[k]; buf[k] = t; } if (buf[j] > buf[k]) { t = buf[j]; buf[j] = buf[k]; buf[k] = t; } for (int z = 0; z < 10; z++) { if ((buf[i] == space[z][0]) && (buf[j] == space[z][1]) && (buf[k] == space[z][2])) { flag = false; break; } else { flag = true; } } if (flag) { space[num][0] = buf[i]; space[num][1] = buf[j]; space[num][2] = buf[k]; num++; } } } } } for (int i = 0; i < num; i++) { printf("(%d, %d, %d)\n", space[i][0], space[i][1], space[i][2]); } system("pause"); return 0;}
1 0
- Leet Code OJ 15. 3Sum[Difficulty: Medium]
- Leet Code OJ 15. 3Sum[Difficulty: Medium]
- Leet Code OJ 136. Single Number [Difficulty: Medium]
- Leet Code OJ 268. Missing Number [Difficulty: Medium]
- Leet Code OJ 260. Single Number III [Difficulty: Medium]
- Leet Code OJ 338. Counting Bits [Difficulty: Medium]
- Leet Code OJ 2. Add Two Numbers [Difficulty: Medium]
- Leet Code OJ 91. Decode Ways [Difficulty: Medium]
- Leet Code OJ 482. License Key Formatting [Difficulty: Medium]
- Leet Code OJ 388. Longest Absolute File Path [Difficulty: Medium]
- Leet Code OJ 112. Path Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code Medium 15 3Sum
- Leet Code Medium 16 3Sum Closest
- Leet Code Medium 1 two sum
- Intellij IDEA 自动生成 serialVersionUID
- 20 个强大的 Sublime Text 插件
- 天线设计(4)
- 51nod_1066 Bash游戏
- 让你彻底明白JAVA中堆与栈的区别
- Leet Code OJ 15. 3Sum[Difficulty: Medium]
- iOS 10.3 改进后的App Review机制
- List To Map的转换
- awk与sed
- SSD( Single Shot MultiBox Detector)关键源码解析
- studio小技巧
- 深入浅出Mybatis系列(七)---mapper映射文件配置之insert、update、delete
- java学习(9)
- IE 浏览器js 中文传参出现乱码问题的解决办法