LeetCode】No.1672. Richest Customer Wealth"/>
【LeetCode】No.1672. Richest Customer Wealth
题目链接: /
1. 题目介绍(最有钱的人)
You are given an m x n
integer grid accounts where accounts[i][j]
is the amount of money the i
customer has in the j
bank. Return the wealth that the richest customer has.
【Translate】: 你将获得一个m x n个整数网格accounts,其中accounts[i][j]是第i个客户在第j家银行的钱的数额。请你返回最富有的customer拥有的财富是多少。
A customer’s wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.
【Translate】: 一个customer的财富是指他所有银行账户上的钱的数量。最富有的customer是指拥有最多钱的客户。
测试用例:
约束:
2. 题解
2.1 普普通通小冒泡
这一题与之前的那道【No.1337. The K Weakest Rows in a Matrix】很相似,No.1337.要求的是在一个m × n的二进制矩阵中找出k个最weak行的索引。相比它,这一题更加简单,它只需要返回最有钱的customer即可,就少了全排序的过程,只需要找出最大的那一个即可。所以,普通的解法就非常简单了,首先遍历数组,将每一行数字的总和存入一个数组;然后对这个数组进行一轮冒泡排序选出最大的那个即可。
public int maximumWealth1(int[][] accounts) {int m = accounts.length;int n = accounts[0].length;int[] wealth = new int[m];// 遍历数组,并将每行的总和存入wealth[]for(int i = 0; i < m; i++){for(int j = 0; j < n; j++){wealth[i] += accounts[i][j]; }}// 一轮冒泡排序选最大for(int i = 0; i < m-1; i++){if(wealth[i] > wealth[i+1]){int tmp = wealth[i];wealth[i] = wealth[i+1];wealth[i+1] = tmp;}} return wealth[m-1]; }
2.2 官方题解(Solution)
官方题解就显得更加的简洁、高效;直接采用一个整形变量maxWealthSoFar用来记录最大值,然后整个大循环结束后返回即可。
public int maximumWealth2(int[][] accounts) {// Initialize the maximum wealth seen so far to 0 (the minimum wealth possible)int maxWealthSoFar = 0;// Iterate over accountsfor (int[] account : accounts) {// For each account, initialize the sum to 0int currCustomerWealth = 0;// Add the money in each bankfor (int money : account) {currCustomerWealth += money;}// Update the maximum wealth seen so far if the current wealth is greater// If it is less than the current summaxWealthSoFar = Math.max(maxWealthSoFar, currCustomerWealth);}// Return the maximum wealthreturn maxWealthSoFar;}
3. 可参考
[1] 冒泡排序
更多推荐
【LeetCode】No.1672. Richest Customer Wealth
发布评论