leetcode每日一题 1672. 最富有客户的资产总量

leetcode每日一题 1672. 最富有客户的资产总量

java8 解决 流比for循环慢,所以性能较低,int转Integer也存在性能损耗

class Solution {
  public int maximumWealth(int[][] accounts) {
      int[] max = new int[1];
      Arrays.stream(accounts).forEach(x->{
          max[0] = Math.max(Arrays.stream(x).sum(),max[0]);
      });
      return max[0];
  }
}

 

 

开多线程,提高性能 ,可是因为并发引发了线程安全问题,解决线程安全问题反而损耗了性能

class Solution {
  public int maximumWealth(int[][] accounts) {
      AtomicInteger max = new AtomicInteger();
      Arrays.stream(accounts).parallel().forEach(x->{
          int sum = Arrays.stream(x).parallel().sum();
          int i;
          do{
              i = max.get();
          } while (!max.compareAndSet(i,Math.max(i,sum)));
      });
      return max.get();
  }
}

 

 

用原始for循环

class Solution {
  public int maximumWealth(int[][] accounts) {
      int max = 0;
      for (int i = 0; i < accounts.length; i++) {
          int sum = 0;
          for (int j = 0; j < accounts[i].length; j++) {
              sum += accounts[i][j];
          }
          max = Math.max(sum,max);
      }
      return max;
  }
}

 

 

posted @ 2022-04-14 09:57  java架构师1  阅读(40)  评论(0)    收藏  举报