首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >想知道以下两种解决方案的时间复杂度[增强的- for循环解决方案与循环解决方案]

想知道以下两种解决方案的时间复杂度[增强的- for循环解决方案与循环解决方案]
EN

Stack Overflow用户
提问于 2020-12-03 06:16:26
回答 1查看 103关注 0票数 0

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

  • Explanation:
  1. 1st客户拥有财富=6
  2. 第二客户财富=10
  3. 第三客户财富= 8

第二个客户是最富有的,财富为10. ** 是使用for-循环的解决方案。

代码语言:javascript
复制
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循环的解决方案

代码语言:javascript
复制
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;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-12-03 06:46:54

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65120784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档