[英]Difficulty finding time complexity
我刚刚解决了一个关于 leetcode 的问题,要求我找到对给定目标求和的数字组合。 我刚刚解决了它,但我很难找到它的时间复杂度。 请帮忙。
import java.util.*;
class Solution
{
List<List<Integer>> result=new ArrayList();
public List<List<Integer>> combinationSum2(int[] candidates, int target)
{
HashMap<List<Integer>,Integer> map=new HashMap();
List<Integer> temp=new ArrayList();
Arrays.sort(candidates);
help(candidates,0,target,map,temp);
return result;
}
private void help(int[] arr,int start,int target,HashMap<List<Integer>,Integer> storage,List<Integer> temp)
{
if(start>=arr.length)
return;
List<Integer> check=new ArrayList<>(temp);
check.add(arr[start]);
if(arr[start]==target)
{
if(storage.containsKey(check))
{
help(arr,start+1,target,storage,temp);
return;
}
else
{
temp.add(arr[start]);
result.add(temp);
storage.put(temp,1);
return;
}
}
if(arr[start]>target)
{
return;
}
help(arr,start+1,target,storage,temp);
help(arr,start+1,target-arr[start],storage,check);
}
}
您通常有 1 个Arrays.sort(candidates)
O(nlog(n))
。 您还有 2 个调用的 1 个递归,它应该是O(2^n)
。 因此,最坏的情况应该是O(2^n)
(O1) 算法被称为运行恒定时间,而不管我们称之为 O(1) 的输入大小。
int getFirst(int[] arr) {
return arr[0]; //O(1)
}
Map<Integer, Integer> map = new HashMap(){{
put(1, 10);
}};
map.get(1); //O(1)
O(n) 如果它运行线性时间。
int sum = 0;
for (int i = 0; i < n; i++) {
sum += n[i];
}
O(logN) 以对数时间运行
像二分查找https://en.wikipedia.org/wiki/Binary_search_algorithm
O(n^2) 2 嵌套循环。 更多的嵌套迭代将导致 O(n^3) O(n^4)...
for(int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
...
}
}
O(2^n) 它随着输入的每次添加而增长一倍。
public int fibo(int n) {
if (n < 2) return n;
return fibo(n - 2) + fibo(n - 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.