由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - leetcode的3sum的运行时间问题
相关主题
请教下3sum为撒超时问个java小白问题
permutationII ,如果不用hashset,用迭代的方法,如何防止重复发个L家面经,攒rp
问个Java的HashSet.contains的问题怎么改List>的值?
3sum on LeetCode OJ如何add to 一个list of lists
请问如何去除结果里面的重复请教 print factors 这个题
问个fb onsite题目java的基本问题
问一个java generic的问题请教一道google面试题
这段word ladder II怎么改?F电面
相关话题的讨论汇总
话题: arraylist话题: integer话题: list话题: current话题: final
进入JobHunting版参与讨论
1 (共1页)
s*****9
发帖数: 93
1
用了DP,同时用了HashSet防止重复结果,运行时间无法通过Large Test. HashSet的查
找不是应该O(1)时间吗?怎样才能更快呢?请帮忙看一下:
import java.util.*;
public class Solution {
public ArrayList> threeSum(int[] num) {
HashSet> final_set = new HashSet Integer>>();
ArrayList current_list = new ArrayList();
threeSumRecur(num, 0, current_list, final_set);

ArrayList> final_lists = new ArrayList Integer>>();
for(ArrayList element : final_set) {
final_lists.add(element);
}
return final_lists;
}

public void threeSumRecur(int[] num, int index, ArrayList
current_list, HashSet> final_set) {
if(index >= num.length) {
return;
}

current_list.add(num[index]);

if(current_list.size() >= 3) {
if(current_list.get(0) + current_list.get(1) + current_list.get(
2) == 0) {
ArrayList new_list = new ArrayList();
new_list.addAll(current_list);
Collections.sort(new_list);
if(!final_set.contains(new_list)) {
final_set.add(new_list);
}
}
}
else {
threeSumRecur(num, index + 1, current_list, final_set);
}

current_list.remove(current_list.size() - 1);

threeSumRecur(num, index + 1, current_list, final_set);
}
}
Z*****Z
发帖数: 723
2
你这是O(N3)的算法

ArrayList<

【在 s*****9 的大作中提到】
: 用了DP,同时用了HashSet防止重复结果,运行时间无法通过Large Test. HashSet的查
: 找不是应该O(1)时间吗?怎样才能更快呢?请帮忙看一下:
: import java.util.*;
: public class Solution {
: public ArrayList> threeSum(int[] num) {
: HashSet> final_set = new HashSet: Integer>>();
: ArrayList current_list = new ArrayList();
: threeSumRecur(num, 0, current_list, final_set);
:

s*****9
发帖数: 93
3
多谢点拨!我根本就没使用DP,纯递归啊!

【在 Z*****Z 的大作中提到】
: 你这是O(N3)的算法
:
: ArrayList<

1 (共1页)
进入JobHunting版参与讨论
相关主题
F电面请问如何去除结果里面的重复
LC 4-sum相当麻烦啊问个fb onsite题目
问道leetcode的题:Combination Sum II问一个java generic的问题
问一下,这种洋灰三角形的解法是o(n)还是o(n2)这段word ladder II怎么改?
请教下3sum为撒超时问个java小白问题
permutationII ,如果不用hashset,用迭代的方法,如何防止重复发个L家面经,攒rp
问个Java的HashSet.contains的问题怎么改List>的值?
3sum on LeetCode OJ如何add to 一个list of lists
相关话题的讨论汇总
话题: arraylist话题: integer话题: list话题: current话题: final