t**i 发帖数: 314 | 1 编译过了,运行出错,帮忙看看哪儿出了问题,多谢。
import java.util.*;
public class Solution {
public ArrayList> threeSum(int[] num) {
assert(num.length >= 3);
ArrayList> triplet = new
ArrayList>();
for(int i = 0; i < num.length - 2; i++) {
for(int j = i + 2; j < num.length; j++) {
for(int k = i + 1; k < j; k++) {
if((num[i] + num[j] + num[k]) == 0) {
int[] three = threeInOrder(num[i], num[j],
num[k]);
ArrayList newTriplet = new
ArrayList();
for(int m = 0; m < three.length; m++)
newTriplet.add(three[m]);
if(!triplet.contains(newTriplet))
triplet.add(newTriplet);
}
}
}
}
return triplet;
}
private int[] threeInOrder(int a, int b, int c) {
int[] three = new int[3];
three[0] = a;
three[1] = b;
three[2] = c;
if(three[0] > three[1]) swap(three, 0, 1);
if(three[1] > three[2]) swap(three, 1, 2);
if(three[0] > three[1]) swap(three, 0, 1);
return three;
}
private void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
} |
h****e 发帖数: 928 | 2 你可以用这个trick:
先在程序中直接返回一个空的结果:
ArrayList> result;
result = new ArrayList>();
return result;
Online Judge会告诉你程序的输入和期望的输出是什么,你把它拷贝
下来,自己写个script一个个试过去就知道哪里出错了。 |
t**i 发帖数: 314 | 3 哇,多谢这个trick。
在eclipse里试了试没有问题,不知道为什么网站上测试时报错
【在 h****e 的大作中提到】 : 你可以用这个trick: : 先在程序中直接返回一个空的结果: : ArrayList> result; : result = new ArrayList>(); : return result; : Online Judge会告诉你程序的输入和期望的输出是什么,你把它拷贝 : 下来,自己写个script一个个试过去就知道哪里出错了。
|
g*********e 发帖数: 14401 | 4 估计你的runtime太长了,leetcode表示无法接受。 |
i**********e 发帖数: 1145 | 5 把你那个 assert 那行 comment 掉,因为输入的数组长度有可能小于三。
【在 t**i 的大作中提到】 : 编译过了,运行出错,帮忙看看哪儿出了问题,多谢。 : import java.util.*; : public class Solution { : public ArrayList> threeSum(int[] num) { : assert(num.length >= 3); : ArrayList> triplet = new : ArrayList>(); : for(int i = 0; i < num.length - 2; i++) { : for(int j = i + 2; j < num.length; j++) { : for(int k = i + 1; k < j; k++) {
|
i**********e 发帖数: 1145 | 6 不是, runtime 太长会报 time limit exceeded (TLE).
runtime error 通常是 java 抛出异常了。这有可能是用户的 assertion fails,或者
数组越位等等问题。
【在 g*********e 的大作中提到】 : 估计你的runtime太长了,leetcode表示无法接受。
|
t**i 发帖数: 314 | 7 通过了,行家的眼光就是赞啊。
对了,这些题哪儿有答案不?写完以后好对照参考一下啊。
【在 i**********e 的大作中提到】 : 把你那个 assert 那行 comment 掉,因为输入的数组长度有可能小于三。
|
h****e 发帖数: 928 | |
r*****e 发帖数: 792 | 9 really nice. thanks for sharing
【在 h****e 的大作中提到】 : 部分答案: : http://dl.dropbox.com/u/19732851/LeetCode/ReadMe.html
|
t**i 发帖数: 314 | |