题解 | #最大体重的牛#
最大体重的牛
https://www.nowcoder.com/practice/0333d46aec0b4711baebfeb4725cb4de
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param op string字符串一维数组
* @param vals int整型二维数组
* @return int整型一维数组
*/
public int[] max_weight_cow (String[] op, int[][] vals) {
int[] res = new int[op.length];
Stack<Integer> s = new Stack<>();
int[] v = new int[op.length];
int size = 0;
for (int i = 0; i < op.length; i++) {
if (op[i].equals("push")) {
s.push(vals[i][1]);
v[size] = vals[i][1];
size++;
Arrays.sort(v, 0, size);
res[i] = -1;
} else if (op[i].equals("pop")) {
int idx = 0;
for (int j = 0; j < size; j++) {
if (v[j] == s.peek()) {
idx = j;
break;
}
}
System.arraycopy(v, idx + 1, v, idx, size - idx - 1);
size--;
s.pop();
res[i] = -1;
} else if (op[i].equals("getMax")) {
res[i] = v[size - 1];
} else if (op[i].equals("top")) {
res[i] = s.peek();
} else {
res[i] = -1;
}
}
return res;
}
}
知识点
栈,动态维护
解题思路
用一个栈来保存每次push的数据,用一个maxStack来动态维护当前最大值。
如果当前添加的数据比maxStack栈顶的元素大,那么添加进当前添加的值,否则将maxStack栈顶元素再次添加进maxStack。
这就和使用动态规划维护一个最大值数组一个道理,当前最大值=上一个元素最大值和当前元素中的大值。
arr[i] = max(arr[i - 1],num)。
查看1道真题和解析