leetcode每日一題 1672. 最富有客戶的資產總量
阿新 • • 發佈:2022-04-14
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;
}
}