Exercise(11):3Sum和
来源:互联网 发布:java date 时间戳 编辑:程序博客网 时间:2024/06/05 06:20
/* 郑志昭 ThreeSum 给定一个数组, a、b、c均为数组元素,要求找出不同的序列,其中a + b + c = 0。(a<=b<=c) 输入: -1 0 1 2 -1 -4 输出: -1 0 1 -1 -1 2 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)*/#include <iostream>using namespace std;// 用于存放a,b,c class SubArray{ public: int a,b,c; void operator=(const SubArray& arr) // 用于对象间的=赋值 { a = arr.a; b = arr.b; c = arr.c; } bool operator==(const SubArray& arr) // 用于判断2个对象是否相同 { if(arr.a==a && arr.b==b && arr.c==c) return true; return false; }};void Swap(int& a,int& b) // 交换2个数的值 { int temp; temp = a; a = b; b = temp;}void Sort(SubArray& arr) // 将a,b,c进行排序 { if(arr.a>arr.b) swap(arr.a,arr.b); if(arr.a>arr.c) swap(arr.a,arr.c); if(arr.b>arr.c) swap(arr.b,arr.c);}SubArray Mark[1000]; // 储存所有出现的结果 int count = 0; // 记录a,b,c的种数 void Print(SubArray& arr) // 输出结果 { for(int i=0;i<count;i++) // 判断当前的a,b,c是否已经输出过 { if(arr == Mark[i]) // 是 则结束函数 return; } Mark[count++] = arr; // 否 则将当前情况记录在Mark中 cout<<arr.a<<ends<<arr.b<<ends<<arr.c<<endl;// 输出结果 }int main(){ int i,j,k,num = 0; // i,j,k循环变量 num记录输入的数的个输 SubArray temp; // 临时储存a,b,c char ch; // 输入的数据变量 bool flag = false; // 判断输入是否为负号 int arr[1000] = {0}; // 存放输入的数据 // 输入 while((ch=getchar())!='\n') { if(ch==' ') // 输入若为空格,则计数器加1,进入下次循环 { num++; continue; } if(flag) // 前一个符号为负号,则将本次输入的值更改为负数 { arr[num] = (-1)*int(ch-'0'); flag = false; } else if(ch=='-') // 输入为负号,将标志flag置为true,进入下次循环 { flag = true; } else // 输入为正数,将数存入数组 { arr[num] = arr[num]*10 + int(ch-'0'); } } num++; // 暴力破解所有 for(i=0;i<num-2;i++) for(j=i+1;j<num-1;j++) for(k=j+1;k<num;k++) if(arr[i]+arr[j]+arr[k]==0) { temp.a = arr[i]; // 找到并将数据存入temp中 temp.b = arr[j]; temp.c = arr[k]; Sort(temp); // 排序a,b,c Print(temp); // 输出结果 } return 0;}
0 0
- Exercise(11):3Sum和
- Leetcode Exercise 1:Two Sum + Three Sum
- LeetCode Exercise 9: Minimum Path Sum
- LeetCode Exercise 12:Minimum Size Subarray Sum
- Exercise 4.2 E2(a)和Exercise4.3E2
- 作业 Exercise 4.2 E2(a)和Exercise4.3E2
- Python Exercise #11
- Exercise 11:提出问题
- python exercise 11
- Exercise of Thread(3)
- Exercise 2.1-3
- Exercise 2-3
- Python Exercise #3
- Chapter 3-exercise
- Exercise #3: Past Simple
- Android exercise 3
- Exercise
- exercise
- C语言(结构体)
- java 使用自定义元组
- 关于QT的正则表达式类QRegExp的细节问题
- C# Winform中无焦点状态下获取键盘输入或者USB扫描枪数据
- 买开 、卖平、卖开、买平
- Exercise(11):3Sum和
- JVM内存管理简介
- UESTC 491 Tricks in Bits
- <<=与>>=运算的意义
- C++primer plus 第五章习题!
- iOS--Quartz2D使用(自定义UIImageView控件、绘制基本图形)
- 回朔——关于产生01数组
- 查询表结构信息
- C++ 给出一个链表的头结点,倒序打印链表