对于k-sum的时间复杂度,最坏是O(n^k),最好的是O(n^(k-1)),对于时间复杂度的分析可以参考这篇文章http://blog.youkuaiyun.com/doc_sgl/article/details/12462151
这篇博客的时间复杂度是O(n^(k-1)),写的特别好和精炼
http://www.programcreek.com/2013/02/leetcode-4sum-java/
我写了一个时间复杂度是O(n^(k-1)logn),发现网上早已经就有实现的了,http://www.cnblogs.com/Azhu/p/4154528.html
我的代码如下:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class Solution {
public List<List<Integer>> fourSum(int[] num, int target) {
Arrays.sort(num);
List<List<Integer>> result = new ArrayList();
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
for(int k=j+1;k<num.length;k++){
if(k+1<num.length&&Arrays.binarySearch(num,k+1,num.length,(target-num[i]-num[j]-num[k]))>=0){
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(num[i]);
temp.add(num[j]);
temp.add(num[k]);
temp.add(target-num[i]-num[j]-num[k]);
result.add(temp) ;
}
while(k+1 < num.length&&num[k]==num[k+1]){
k++;
}
}
while(j+1 < num.length&&num[j]==num[j+1]){
j++;
}
}
while(i+1 < num.length&&num[i]==num[i+1]){
i++;
}
}
return result;
}
public static void main(String args[]){
Solution s = new Solution() ;
int[] candidates = {-3,-2,-1,0,0,1,2,3};
List<List<Integer>> list = s.fourSum(candidates, 0) ;
for(List<Integer> l : list){
for(Integer i : l){
System.out.print(i+" ");
}
System.out.println();
}
}
}

本文深入探讨了四数之和问题的时间复杂度优化,从O(n^3)降低到O(n^2logn),并详细介绍了算法实现步骤及优化策略。
9477

被折叠的 条评论
为什么被折叠?



