当前位置:网站首页>【C语言刷LeetCode】735. 行星碰撞(M)
【C语言刷LeetCode】735. 行星碰撞(M)
2022-07-19 01:34:00 【kinbo88】
【
给定一个整数数组 asteroids,表示在同一行的行星。
对于数组中的每一个元素,其绝对值表示行星的大小,正负表示行星的移动方向(正表示向右移动,负表示向左移动)。每一颗行星以相同的速度移动。
找出碰撞后剩下的所有行星。碰撞规则:两个行星相互碰撞,较小的行星会爆炸。如果两颗行星大小相同,则两颗行星都会爆炸。两颗移动方向相同的行星,永远不会发生碰撞。
示例 1:
输入:asteroids = [5,10,-5]
输出:[5,10]
解释:10 和 -5 碰撞后只剩下 10 。 5 和 10 永远不会发生碰撞。
示例 2:
输入:asteroids = [8,-8]
输出:[]
解释:8 和 -8 碰撞后,两者都发生爆炸。
示例 3:
输入:asteroids = [10,2,-5]
输出:[10]
解释:2 和 -5 发生碰撞后剩下 -5 。10 和 -5 发生碰撞后剩下 10 。
提示:
2 <= asteroids.length <= 104
-1000 <= asteroids[i] <= 1000
asteroids[i] != 0
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/asteroid-collision
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
】
看题意很容易想到单调栈,但却读错了题意两次,所以做题前先读三次题意,好好理解一下。
因为碰撞时要么消失要么不改变大小,所以栈中元素的处理idx索引要小心。
栈顶元素为右,当前为左才会碰撞。所以判断碰撞后的结果,可以用两个元素求和。
int* asteroidCollision(int* asteroids, int asteroidsSize, int* returnSize){
int *stack = NULL;
int idx = -1; // idx 指向存放元素的位置
int i;
int flag = 1; // 上一个元素的方向,1:右;-1:左
stack = (int *)malloc(sizeof(int) * asteroidsSize);
memset(stack, 0, sizeof(int) * asteroidsSize);
stack[++idx] = asteroids[0];
for (i = 1; i < asteroidsSize; i++) {
int comp = -1;
// 栈顶元素为右,当前为左才会碰撞
while (asteroids[i] < 0 && idx > -1 && stack[idx] > 0) {
comp = stack[idx] + asteroids[i]; // 和栈顶元素比较正负
if (comp < 0) {
idx--; // 栈顶元素爆炸了
continue;
} else if (comp == 0) {
idx--;
break;
} else {
break;
}
}
if (comp < 0) {
stack[++idx] = asteroids[i]; // 把当前元素放进去
}
}
*returnSize = idx + 1;
return stack;
}
/*
1. 又一次看错题意了,较小的会爆炸,而不是大减小,一些代码又要重新调了
2. 理解错题意了。以为第一个左,第二个右也会相撞,我理解[-2,-1,1,2] 的返回值是空,结果正确的返回值是[-2,-1,1,2],把题目搞复杂了
3. flag 判断时需要注意idx
这一次不把元素拿出来,直接比较
*/
边栏推荐
- 图像处理高手技能清单
- RMAN backup compression ratio? About 5 times
- Based on yarn1 Sharing of monorepo practice of X
- 【LeetCode每日一题】——108.将有序数组转换为二叉搜索树
- 特殊的二叉树及练习题
- Jenkins学习笔记详细
- 剑指 Offer 28. 对称的二叉树
- II - 01day: object index understanding, this point on the object, object conversion to string, function pre parsing, arguments The usage of callee,
- JS的DOM操作——事件类型
- WTO MC12 achieves "1+4" achievements to promote global post pandemic economic recovery
猜你喜欢
随机推荐
【活动早知道】LiveVideoStack近期活动一览
【C语言入门】ZZULIOJ 1006-1010
产品思维撬动研发管理工具建设
“蜂聚惠”电商购物平台线上线下齐发力,打造全域电商新秀崛起
El select and El tree tree structure drop-down single selection and multi selection
每日刷题记录 (二十七)
OGC WebGIS 常用服务标准(WMS/WMTS/TMS/WFS)速查
sql 请问如何在输入查询条件为空的情况下返回所有的数据
个人开发的解ctf usb的键盘流量的工具 KeyboardTraffic
React. The data cached by context and Redux cannot be shared across browser tabs. How to solve it?
高数 | 多元函数求极限 使用极坐标代换的条件与细节
Is the mobile account opening process of CITIC Securities safe? How to open a VIP account
Debezium同步之监测Debezium
C语言基础Day4-函数笔记
高数 | 【多元函数微分学】概念篇 —— 连续、可偏导及可微之间的关系
Award winning research | what does the perfect ar development platform look like to make virtual reality?
"Taige experiment" SLA linkage static routing experiment
DOM operation of JS - event type
The LAAS protocol elephant of defi 2.0 is the key to revitalizing the development of defi track
autojs云控源码+展示