所以我试图完成Leetcode的3Sum问题。我的解决方案得到了正确的答案,但是对于更长的测试用例,我得到了“超过时间限制”。我猜这是因为我正在使用嵌套的for循环,但不确定如何从此处继续。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int x = 0;
int y = 0;
int z = 0;
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
Map<Integer,Integer> map = new HashMap();
for (int i = 0; i < nums.length; i++){
map.put(i, nums[i]);
}
for (int j = 0; j < nums.length - 2; j++){
x = map.get(j);
for(int k = j+1;k < nums.length - 1; k++){
y = map.get(k);
for(int l = k+1; l <nums.length; l++){
z = map.get(l);
if((x + y + z) == 0){
List<Integer> triplet = new ArrayList<Integer>();
triplet.add(x);
triplet.add(y);
triplet.add(z);
System.out.println(triplet);
if (!(res.contains(triplet))){
res.add(triplet);
}
}
}
}
}
return res;
}
有关如何优化此解决方案的任何提示?
答案 0 :(得分:2)
您的解是O(N ^ 3)。因此,超过了时间限制。
可以如下所示更有效地解决问题:
public List<List<Integer>> threeSum(int[] num) {
Arrays.sort(num);
List<List<Integer>> res = new LinkedList<>();
for (int i = 0; i < num.length-2; i++) {
if (i == 0 || (i > 0 && num[i] != num[i-1])) {
int lo = i+1, hi = num.length-1, sum = 0 - num[i];
while (lo < hi) {
if (num[lo] + num[hi] == sum) {
res.add(Arrays.asList(num[i], num[lo], num[hi]));
while (lo < hi && num[lo] == num[lo+1]) lo++;
while (lo < hi && num[hi] == num[hi-1]) hi--;
lo++; hi--;
} else if (num[lo] + num[hi] < sum) lo++;
else hi--;
}
}
}
return res;
}