力扣2751.机器人碰撞
-
栈模拟
- 按照位置排序,只处理左边往右和右边往左的
-
class Solution { public: vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) { int n = positions.size(),id[n]; iota(id,id+n,0); sort(id,id+n,[&](const int i,const int j){ return positions[i] < positions[j]; }); stack<int> st; for(int i:id) { if(directions[i] == 'R') { st.push(i); continue; } while(!st.empty()) { int top = st.top(); if(healths[top] > healths[i]) { healths[top] --; healths[i] = 0; break; } if (healths[top] == healths[i]) { // 健康度一样大 healths[top] = 0; st.pop(); // 移除栈顶 healths[i] = 0; break; } else { healths[top] = 0; st.pop(); healths[i]--; } } } healths.erase(remove(healths.begin(),healths.end(),0),healths.end()); return healths; } };