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
原创粉丝点击