这种方法的时间复杂度和辅助空间是多少?

时间:2019-01-06 16:06:31

标签: java time-complexity space-complexity

此方法的时间复杂度和辅助空间是多少?有人可以告诉我并解释结果吗?

SELECT * ,
(select sum(sell) from product_details where product_details.product_id = products.id) as total ,
(select sell from product_details where product_details.product_id = products.id order by product_details.id desc limit 1) as ysell ,
(select sum(sell) as wsell FROM (select sell from product_details where product_details.product_id = products.id order by product_details.id desc limit 2 ) as weeksell) as wsell
FROM `products`

如果我像下面那样测试我的代码怎么办?

#1054 - Unknown column 'products.id' in 'where clause'

2 个答案:

答案 0 :(得分:1)

时间复杂度

您的代码的时间复杂度为 O(n) ,其中其中nlist 中元素的数量。原因:

for (T i : list) { // iterates through all the 'n' elements
    if (!set.add(i)) {
        repeatedValues.add(i);
    }
}

空间复杂度

另一方面,由于您使用的是Set来临时存储值,因此在最坏情况下使用的Set所需的空间为:

Set<T> set = new HashSet<>(list.size()); // all elements are unique

因此,解决方案的空间复杂度也将为 O(n) 。当然,n是作为列表大小的值。如果列表的大小增加,则所需的空间也会增加。

输出

public void printRepeatedStrings(){
    List<String> stringList = Arrays.asList("ali","mahdi","hadi","mahdi","mojtaba","mohammad","mojtaba");
    RepeatedValues<String> repeatedValues = new RepeatedValues<>(); // type 'T' bound 
    repeatedValues.findRepeatedValues(stringList)
                  .forEach(System.out::println); // prints ["mahdi","mojtaba"]
}

答案 1 :(得分:0)

复杂度

  • 时间复杂度为 O(n)
  • 空间复杂度为 O(n)

说明

public Set<T> findRepeatedValues(List<T> list){
    // both sets contains n elements: hence space complexity is O(n)
    Set<T> set = new HashSet<>();
    Set<T> repeatedValues = new HashSet<>();

    // iterate over list only once: hence time complexity is O(n)
    for (T i: list) {
        // HashSet add has O(1) time complexity
        if (!set.add(i)) {
            repeatedValues.add(i);
        }
    }

    return repeatedValues;
}

测试

您的测试不正确。您必须检查返回的Set是否包含必需的数据。看起来很冷:

public static void findRepeatedStrings() {
    List<String> list = Arrays.asList("ali", "mahdi", "hadi", "mahdi", "mojtaba", "mohammad", "mojtaba");
    Set<String> values = new RepeatedValues<String>().findRepeatedValues(list);

    MatcherAssert.assertThat(values, IsCollectionWithSize.hasSize(2));
    MatcherAssert.assertThat(values, IsIterableContainingInOrder.contains("mahdi", "mojtaba"));
}