做完twoSum顺手就想一下3Sum,发现做得一点都不顺手
虽然后面还是用各种vector和map<int,int>在自己的编译器上能运行出结果吗,但是提交到leetCode上去之后发现超时time limit exceeded,讲真,内心还是有一点点忧伤的。不过还好在本地各种补漏做出来了也是该给自己加个鸡腿的,毕竟熟悉了vector和map的操作。
嘤嘤嘤,怎么就不能撑过最后九个例子呢,哎~~
后面看了一下leetCode上面Discuss部分,用C++做的最好的答案,简直惊为天人啊啊啊啊,代码很简洁又容易懂,写得注释也很完备,这就是传说中的大神吧。看来做题目还是得先多思考,才能减少代码量和debug的时间。
觉得自己执迷不悟的地方在于觉得一定要用之前的twoSum的那个函数,而且没有去思考更好地处理重复数据的问题。单单只想着如何直接去实现,后来发现要补一个一个洞,绕一个一个弯才能完成任务,导致的结果就是超时。啥也不多说了,贴上大神思路的代码。(看完大神代码后,自己写了一遍)
题目:
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: 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] ] vector > threeSum(vector &nums) { vector > result; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); i++) { int front = i+1; int back = nums.size() - 1; int target = -nums[i]; while (front target) { back--; } else { vector triplet(3, 0); triplet[0] = nums[i]; triplet[1] = nums[front]; triplet[2] = nums[back]; result.push_back(triplet); while (front