用数组模拟栈的过程,当加入数字时,重复与栈顶尝试合并直到无法合并为止。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
const int maxn=1e5+10;
int n;
int s[maxn],top;
int main() {
std::ios::sync_with_stdio(false);
cin>>n;
for(int i=1,x;i<=n;++i){
cin>>x;
s[++top]=x;
while(top>=2&&s[top]==s[top-1]){
top--;
s[top]++;
}
}
for(int i=1;i<=top;++i){
cout<<s[i]<<" ";
}
return 0;
}
import java.util.*;
class Solution {
public List<Integer> func(int[] nums, int n) {
Deque<Integer> stack = new ArrayDeque<>();
stack.offerFirst(nums[0]);
for (int i = 1; i < n; i++) {
int val = nums[i];
while (!stack.isEmpty() && stack.peekFirst() == val) {
stack.pollFirst();
val++;
}
stack.offerFirst(val);
}
List<Integer> res = new ArrayList<>();
while (!stack.isEmpty()) {
res.add(stack.pollFirst());
}
Collections.reverse(res);
return res;
}
}
public class Main {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}
List<Integer> res = new Solution().func(nums, n);
// System.out.println(res);
for (Integer val : res) {
System.out.print(val + " ");
}
}
}
m = int(input())
stack = []
data = list(map(int, input().split()))
while data:
stack.append(data.pop(0))
while len(stack) >= 2:
if stack[-1] == stack[-2]:
stack.pop()
stack[-1] += 1
else:
break
print(*stack)
给定一个栈,初始时栈中为空。有m次操作,每次操作向栈口压入一个数字。在一次操作之后,如果栈中有两个连续的相同数字x,则它们会合并成数字x+1。如果仍有,则重复此过程(可以证明同一时刻最多只有一组两个连续的相同数字)。问m次操作之后栈中的数字自底向上是多少?
第一行正整数m,接下来一行m个正整数,表示按顺序压入的数字。
1≤m≤105,压入数字为[1,m]中的整数
一行若干个数字,表示最后剩下的数字(自栈底至栈顶)
输入
6
1 1 2 3 4 5
输出
6
说明
在这个样例中,每次压入的数字都和栈中唯一的数字相间,故会合并成x+1
输入
7
1 1 2 2 3 2 1
输出
3 2 3 2 1