From 2efe4074491c7e05c0b1298228c38151443d6ee4 Mon Sep 17 00:00:00 2001 From: keineahnung2345 Date: Wed, 21 Oct 2020 18:25:11 +0800 Subject: [PATCH] two pointer --- 735. Asteroid Collision.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/735. Asteroid Collision.cpp b/735. Asteroid Collision.cpp index 92e7b5b..fff3fc6 100644 --- a/735. Asteroid Collision.cpp +++ b/735. Asteroid Collision.cpp @@ -88,3 +88,39 @@ class Solution { } }; +//two pointer +//https://leetcode.com/problems/asteroid-collision/solution/131673 +//Runtime: 24 ms, faster than 81.17% of C++ online submissions for Asteroid Collision. +//Memory Usage: 17.9 MB, less than 95.21% of C++ online submissions for Asteroid Collision. +class Solution { +public: + vector asteroidCollision(vector& A) { + int n = A.size(); + + //slow: last filled asteroid's position + int slow = -1, fast = 0; + + for(fast = 0; fast < n; ++fast){ + bool exploded = false; + + while(slow >= 0 && A[slow] > 0 && A[fast] < 0){ + if(abs(A[slow]) > abs(A[fast])){ + exploded = true; + break; + }else if(abs(A[slow]) == abs(A[fast])){ + --slow; + exploded = true; + break; + }else{ + --slow; + } + } + + if(!exploded){ + A[++slow] = A[fast]; + } + } + + return vector(A.begin(), A.begin()+slow+1); + } +};