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

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

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

  1. public int maximumWealth(int[][] accounts) {
  2. int total_count = 0;
  3. for (int j = 0; j < accounts.length; j++) {
  4. int temp_count = 0;
  5. for (int i = 0; i < accounts[0].length; i++) {
  6. temp_count = accounts[j][i] + temp_count;
  7. System.out.println(accounts[j][i]);
  8. System.out.println("value of temp_count" + temp_count);
  9. }
  10. if (temp_count > total_count) {
  11. total_count = temp_count;
  12. System.out.println("value of total_count" + total_count)
  13. }
  14. }
  15. return total_count;
  16. }

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

  1. class Solution {
  2. public int maximumWealth(int[][] accounts) {
  3. int total_count = 0;
  4. for (int[] account: accounts) {
  5. int temp_count = 0;
  6. for (int item: account) {
  7. temp_count = item + temp_count;
  8. }
  9. if (temp_count > total_count) {
  10. total_count = temp_count;
  11. }
  12. }
  13. return total_count;
  14. }
  15. }
zsohkypk

zsohkypk1#

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

相关问题