每日一题做题记录,参考官方和三叶的题解 |
文章目录
题目要求
思路:模拟
看到简单立即推,模拟……
过于简单就写两种实现思路的代码:
normal数组遍历
Java
class Solution {
public int maximumWealth(int[][] accounts) {
int m = accounts.length, n = accounts[0].length, res = 0;
for(int i = 0; i < m; i++) {
int cur = 0; //记录当前遍历客户的资产量
for(int j = 0; j < n; j++)
cur += accounts[i][j];
res = Math.max(res, cur);
}
return res;
}
}
- 时间复杂度: O ( m × n ) O(m\times n) O(m×n)
- 空间复杂度: O ( 1 ) O(1) O(1)
C++
class Solution {
public:
int maximumWealth(vector<vector<int>>& accounts) {
int m = accounts.size(), n = accounts[0].size(), res = 0;
for(int i = 0; i < m; i++) {
int cur = 0; //记录当前遍历客户的资产量
for(int j = 0; j < n; j++)
cur += accounts[i][j];
res = max(res, cur);
}
return res;
}
};
- 时间复杂度: O ( m × n ) O(m\times n) O(m×n)
- 空间复杂度: O ( 1 ) O(1) O(1)
调用数组内置函数
Java
class Solution {
public int maximumWealth(int[][] accounts) {
int res = 0;
for(int[] a : accounts)
res = Math.max(res, Arrays.stream(a).sum());
return res;
}
}
- 时间复杂度: O ( m × n ) O(m\times n) O(m×n)
- 空间复杂度: O ( 1 ) O(1) O(1)
Arrays stream
- 学习参考链接
- 将数组转换为其中元素构成的顺序流,可应用于String类等。
- 也可增加两个参数,自定义顺序流起止点。
C++
class Solution {
public:
int maximumWealth(vector<vector<int>>& accounts) {
int res = 0;
for(auto &a : accounts)
res = max(res, accumulate(a.begin(), a.end(), 0));
return res;
}
};
- 时间复杂度: O ( m × n ) O(m\times n) O(m×n)
- 空间复杂度: O ( 1 ) O(1) O(1)
accumulate
- 学习参考链接
accumulate(begin, end, init)
- 前两个参数定义序列范围(输入迭代器);
- 第三个值为累加和的初值,决定了返回值的类型;
- 最终返回前两个参数范围内所有元素的累加和,其类型同第三个元素,也可应用于string类。
总结
模拟题总是没什么好分析的,就是直接累加每个客户的资产量,不过倒是学了两个内置函数,Java的那个似乎效率不太高,但也没去看看源码。
最近要做小pre,打算把内容整理成几个小博客【立flag ing……】
欢迎指正与讨论! |