| 
 | 1 | +/**  | 
 | 2 | + * 排列组合  | 
 | 3 | + * 刚拿到这题第一个想法就是使用排列组合,很快写完。结果在遇到一个长3000的数组时,运行超时了,时间复杂度O(n!)。  | 
 | 4 | + * n!/m!(n-m)! 差不多就是 44.95501亿次运算循环,这不管使用何种语言都会遇到超时的问题  | 
 | 5 | + * 看了几个 Submission,他们的时间复杂度能做到 O(n^2)  | 
 | 6 | + * @time 2019.05.20 18:00  | 
 | 7 | + * @status Time Limit Exceeded  | 
 | 8 | + * @case [82597,-9243,62390,83030,-97960,-26521...] (3000)  | 
 | 9 | + */  | 
 | 10 | +var threeSum = (nums: number[]): number[][] => {  | 
 | 11 | + const result: { [T: string]: number[] } = {};  | 
 | 12 | + for (let a: number = 0; a < nums.length; a++) {  | 
 | 13 | + for (let b: number = a + 1; b < nums.length; b++) {  | 
 | 14 | + for (let c: number = b + 1; c < nums.length; c++) {  | 
 | 15 | + if (nums[a] + nums[b] + nums[c] === 0) {  | 
 | 16 | + const arr: number[] = [nums[a], nums[b], nums[c]].sort();  | 
 | 17 | + const arrStr: string = arr.toString();  | 
 | 18 | + if (!(arrStr in result)) {  | 
 | 19 | + result[arrStr] = arr;  | 
 | 20 | + }  | 
 | 21 | + }  | 
 | 22 | + }  | 
 | 23 | + }  | 
 | 24 | + }  | 
 | 25 | + return Object.values(result);  | 
 | 26 | +};  | 
 | 27 | + | 
 | 28 | +/**  | 
 | 29 | + * 排列组合  | 
 | 30 | + * @github https://github.com/guocaoyi/leetcode-ts  | 
 | 31 | + * @author yalda  | 
 | 32 | + */  | 
 | 33 | +var threeSum = (nums: number[]): number[][] => {  | 
 | 34 | + const result: { [T: string]: number[] } = {};  | 
 | 35 | + nums = nums.sort();  | 
 | 36 | + let left = 0;  | 
 | 37 | + let right = nums[nums.length - 1];  | 
 | 38 | + | 
 | 39 | + for (let a: number = 0; a < nums.length; a++) {  | 
 | 40 | + for (let b: number = a + 1; b < nums.length; b++) {  | 
 | 41 | + for (let c: number = b + 1; c < nums.length; c++) {  | 
 | 42 | + if (nums[a] + nums[b] + nums[c] === 0) {  | 
 | 43 | + const arr: number[] = [nums[a], nums[b], nums[c]].sort();  | 
 | 44 | + const arrStr: string = arr.toString();  | 
 | 45 | + if (!(arrStr in result)) {  | 
 | 46 | + result[arrStr] = arr;  | 
 | 47 | + }  | 
 | 48 | + }  | 
 | 49 | + }  | 
 | 50 | + }  | 
 | 51 | + }  | 
 | 52 | + | 
 | 53 | + return Object.values(result);  | 
 | 54 | +};  | 
0 commit comments