avatar
m*1
1
写了一个平方复杂度的,但是一直超时。请大家帮忙看看。
public ArrayList> fourSum(int[] num, int target) {
Map cache = new HashMap();
Map> previous = new HashMapInteger>>();
ArrayList> result = new ArrayListInteger>>();
Set nima = new HashSet();
if (num.length < 4) {
return result;
}
Arrays.sort(num);
for (int i = 0; i < num.length; i++) {
for (int j = i+1; j < num.length; j++) {
List lastTwo = new ArrayList();
lastTwo.add(num[i]);
lastTwo.add(num[j]);
previous.put(i+"+"+j, lastTwo);
cache.put(i+"+"+j, num[i]+num[j]);
}
}

for (String start : cache.keySet()) {
int c = target-cache.get(start);
String[] numbers = start.split("\+");
int left = Integer.valueOf(numbers[1])+1;
int right = num.length-1;

while (left < right) {
int sum = num[left] + num[right];
if (sum < c) {
left++;
} else if (sum > c) {
right--;
} else {
List lastTwo = previous.get(start);
String key = start+"+" +left+ "+"+right;
if (!nima.contains(key)) {
ArrayList list = new ArrayList();
list.addAll(lastTwo);
list.add(num[left]);
list.add(num[right]);
result.add(list);
nima.add(key);
}
right--;
left++;
}
}
}

return result;
}
avatar
m*1
2
自顶
avatar
g*4
3
4 sum最快也只能到n^3吧,再检查下算法吧
avatar
c*2
4
Set nima....
avatar
b*c
5
o(n^2) ok.
avatar
m*1
6
可是为什么总是超时,哪里有问题?
avatar
b*h
7
因为你写的 twoSum 部分不是平方复杂度 你的 keySet 就平方级了

【在 m*******1 的大作中提到】
: 可是为什么总是超时,哪里有问题?
avatar
m*1
8
明白了,多谢
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。