目录题目要求思路一:暴力模拟Javac++Rust思路二:单调栈JavaC++Rust题目要求 思路一:暴力模拟 由于数据范围不算离谱,所以直接遍历解决可行。 Java class
class Solution {
public int[] finalPrices(int[] prices) {
int n = prices.length;
int[] res = new int[n];
for (int i = 0; i < n; i++) {
int discount = 0;
for (int j = i + 1; j < n && discount == 0; j++) {
if (prices[j] <= prices[i])
discount = prices[j];
}
res[i] = prices[i] - discount;
}
return res;
}
}
class Solution {
public:
vector<int> finalPrices(vector<int>& prices) {
int n = prices.size();
vector<int> res(n);
for (int i = 0; i < n; i++) {
int discount = 0;
for (int j = i + 1; j < n && discount == 0; j++) {
if (prices[j] <= prices[i])
discount = prices[j];
}
res[i] = prices[i] - discount;
}
return res;
}
};
impl Solution {
pub fn final_prices(prices: Vec<i32>) -> Vec<i32> {
let n = prices.len();
let mut res = vec![0;n];
(0..n).for_each(|i| {
res[i] = prices[i] - ((i + 1)..n).find(|&j| prices[j] <= prices[i]).map_or(0, |j| prices[j]);
});
res
}
}
impl Solution {
pub fn final_prices(prices: Vec<i32>) -> Vec<i32> {
let n = prices.len();
let mut discount = vec![0;n];
for j in 1..n {
for i in 0..j {
if discount[i] == 0 && prices[j] <= prices[i] {
discount[i] = prices[j];
}
}
}
prices.iter().zip(discount.iter()).map(|(&x, &y)| x - y).collect::<Vec<i32>>()
}
}
class Solution {
public int[] finalPrices(int[] prices) {
int n = prices.length;
int[] res = new int[n]; // 已打折价格
Deque<Integer> sta = new ArrayDeque<>(); // 待打折下标
for (int i = 0; i < n; i++) {
while (!sta.isEmpty() && prices[sta.peekLast()] >= prices[i]) {
int idx = sta.pollLast();
res[idx] = prices[idx] - prices[i];
}
sta.addLast(i); // 最高
res[i] = prices[i];
}
return res;
}
}
class Solution {
public:
vector<int> finalPrices(vector<int>& prices) {
int n = prices.size();
vector<int> res(n); // 已打折价格
stack<int> sta; // 待打折下标
for (int i = 0; i < n; i++) {
while (!sta.empty() && prices[sta.top()] >= prices[i]) {
int idx = sta.top();
sta.pop();
res[idx] = prices[idx] - prices[i];
}
sta.push(i); // 最高
res[i] = prices[i];
}
return res;
}
};
impl Solution {
pub fn final_prices(prices: Vec<i32>) -> Vec<i32> {
let n = prices.len();
let mut res = vec![0;n]; // 已打折价格
let mut sta = vec![]; // 待打折下标
for i in 0..n {
while let Some(&idx) = sta.last() {
if prices[idx] < prices[i] {
break;
}
sta.pop();
res[idx] = prices[idx] - prices[i];
}
sta.push(i); // 最高
res[i] = prices[i];
}
res
}
}
以上就是Java C++ 算法题解LeetCode145商品折扣后最终价格单调栈的详细内容,更多关于Java C++ 商品折扣后价格的资料请关注编程网其它相关文章!
--结束END--
本文标题: Java C++ 算法题解leetcode145商品折扣后最终价格单调栈
本文链接: https://lsjlt.com/news/167488.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0