题目
算法思路
思路一(暴力)
思路分析
题目的数据量只有500,所以O(n*n)可以,可以直接双重for枚举两个下标
源码
class Solution {
public int[] finalPrices(int[] prices) {
for(int i=0;i<prices.length;i++){
//j=i+1既可以满足最小下标
for(int j=i+1;j<prices.length;j++){
if(prices[i] >= prices[j]){
prices[i]=prices[i]-prices[j];
break;
}
}
}
return prices;
}
}
时间和空间复杂度
思路二(栈)
思路分析
源码
class Solution {
public int[] finalPrices(int[] prices) {
Stack<Integer> st = new Stack<>();
for(int i = 0 ; i < prices.length; i++){
while(!st.isEmpty() && prices[i] <= prices[st.peek()]){
int idx = st.pop();
prices[idx] = prices[idx] - prices[i];
}
st.push(i);
}
return prices;
}
}
时间和空间复杂度
所用API
- push( num) //入栈
- pop() //栈顶元素出栈
- empty() //判定栈是否为空
- peek() //获取栈顶元素