
解题思路:简单的题目,感觉对不起它的难度标识。栈结构的“消消乐”游戏。
注意栈顶和当前元素消除后会产生一个新数字,这个新数字可能产生新的消除。
为了清晰,使用了一个手写栈结构,其实这个题目直接vector就行了。
__gcd(x,y)是c++提供的函数。
class Solution
{
public:
vector<int> replaceNonCoprimes(vector<int>& nums)
{
int i,st[100005],top=0;/**< 手写栈结构 */
st[top++]=nums[0];
vector<int>ans;
for(i=1; i<nums.size(); i++)
{
int x=st[top-1],y=nums[i];
if(__gcd(x,y)==1) /**< 栈顶和当前公约数为1 */
{
st[top++]=y;
continue;
}
while(top>0&&__gcd(x,y)!=1) /**< y和栈顶公约数 */
{
top--; /**< 出栈,计算结果 */
y=1LL*x*y/__gcd(x,y);
if(top>0)
x=st[top-1];
else
break;
}
st[top++]=y;
}
for(i=0; i<top; i++)
ans.push_back(st[i]);
return ans;
}
};