java—想知道下面两种解决方案的时间复杂度[增强的for loop解决方案vs for loop解决方案]

67up9zun  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(344)

问题:输入:帐户=[[1,5],[7,3],[3,5]]输出:10
说明:
第一个客户拥有财富=6
第二个客户拥有财富=10
第三个客户拥有财富=8
第二位客户是最富有的,拥有10英镑的财富下面是for循环的解决方案

public int maximumWealth(int[][] accounts) {
    int total_count = 0;
    for (int j = 0; j < accounts.length; j++) {
        int temp_count = 0;
        for (int i = 0; i < accounts[0].length; i++) {
            temp_count = accounts[j][i] + temp_count;
            System.out.println(accounts[j][i]);
            System.out.println("value of temp_count" + temp_count);
        }
        if (temp_count > total_count) {
            total_count = temp_count;
            System.out.println("value of total_count" + total_count)
        }
    }
    return total_count;
}

下面是增强for循环的解决方案

class Solution {
    public int maximumWealth(int[][] accounts) {
        int total_count = 0;
        for (int[] account: accounts) {
            int temp_count = 0;
            for (int item: account) {
                temp_count = item + temp_count;
            }
            if (temp_count > total_count) {
                total_count = temp_count;
            }
        }
        return total_count;
    }
}
zsohkypk

zsohkypk1#

两种形式的for循环都具有相同的时间复杂度,即o(n*m)。中引入了增强的for循环,作为遍历集合中所有元素的更简单方法。它也可以用于数组,但这不是最初的目的。增强for循环简单但不灵活。单词“enhanced”并不意味着enhanced for循环在时间复杂度方面得到了增强。和for loop一样。

相关问题