【问题标题】:Want to Know the time complexity of below two solution [enhanced - for loop solution vs for loop solution]想知道以下两种解决方案的时间复杂度 [增强 - for 循环解决方案与 for 循环解决方案]
【发布时间】:2021-03-15 03:53:26
【问题描述】:

问题: 输入: 帐户 = [[1,5],[7,3],[3,5]] 输出:10

  • 说明:
  1. 第一个客户拥有财富 = 6
  2. 第二位客户拥有财富 = 10
  3. 第三位客户拥有财富 = 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;
    }
}

【问题讨论】:

  • 为什么这两个会有不同的时间复杂度?这是相同的操作 - 二维数组上的两个嵌套循环。他们都是O(n*m)

标签: java foreach time-complexity


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    相关资源
    最近更新 更多