【问题标题】:What is the time complexity of the Java code below下面Java代码的时间复杂度是多少
【发布时间】:2017-11-19 07:23:19
【问题描述】:

这是一个简单的 java 代码,用于查找数组中的不同三元组的总数,其和可被 targetNum 整除。代码工作正常,但我需要确保它的时间复杂度不超过 O(n^2)。

public static void main(String [] args){

    int totalNum = 10;
    int targetNum = 5;
    int inputArray[] = { 1,10,4,3,2,5,0,1,9,5 };


    HashMap<Integer,int[]> tempMap = new HashMap<>();
    int tempCount=1;
    for(int i=0; i<totalNum-2; i++){
        for(int j=i+1; j<totalNum; j++){

            int num1 = inputArray[i];
            int num2 = inputArray[j];
            int [] tempArr = new int[2];
            tempArr[0] = num1+num2;
            tempArr[1] = j;
            tempMap.put(tempCount,tempArr);
            tempCount++;
        }
    }
    int finalCount=0;
    for(int i=1; i<tempCount; i++){
        int [] tempArr = tempMap.get(i);
        int val1 = tempArr[0];
        int startIndex = tempArr[1]+1;

        for(int j=startIndex; j<totalNum; j++){
            int val2 = inputArray[j];
            if((val1+val2)%targetNum == 0){
                finalCount++;
            }
        }

    }
    System.out.print(finalCount);
}

【问题讨论】:

    标签: java data-structures time-complexity


    【解决方案1】:

    发布代码的时间复杂度为 O(n^3)。

    第一个循环是 O(n^2):它是一个嵌套循环,其中两个循环的范围与 O(n) 成正比。

    第二个循环是O(n^3):虽然看起来很像第一个(一个循环嵌套在另一个循环中),外循环的范围与O(n^2)成正比,内循环为 O(n)。这给出了总 O(n^3)。

    【讨论】:

    • 感谢您的 cmets。我需要把它降低到 n^2,
    • @RohanJain,尝试在 O(n) 中为 2 个数字解决此任务,这样会更容易看到该方法,然后将其扩展到您的案例。
    • 这是一个实际的问题:如果三个数字的总和可以被一个神秘的常数 M 整除,那么它们是特殊的 找出有多少不同的三元组数字的总和可以被 M 整除。不幸的是,这个问题是他很难破解,他需要你的帮助 Input 输入两个整数,N 和 M,分别代表序列中的整数个数和神话常数。接下来,将 N 个整数作为输入(允许重复整数)。输出应仅包含一个整数,即其和可被 M 整除的不同三元组的数量
    猜你喜欢
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    相关资源
    最近更新 更多