C++ 0ms - O(N) speed O(1) space with iterator


  • 0
    Q
       class Solution {
          public:
            bool isSelfCrossing(vector<int>& x) {
                if (x.size() < 4) return false;
                for (auto it = x.begin() + 3; it != x.end(); ++it)
                {
        
                    if (*(it - 1) <= *(it - 3))
                    { // in
                        if (*it >= *(it - 2))
                            return true;
                        ++it;
                        while (it != x.end())
                        {
                            if (*it >= *(it - 2)) return true;
                            ++it;
                        }
                        return false;
                    }
                    else
                    { // out
                        if (*it <= *(it - 2))
                        {// in
                            ++it;
        
        
                            if (it != x.end() && it - 4 >= x.begin())
                            {
                                if (*(it - 1) == *(it - 3) && *(it - 2) <= *it + *(it - 4))
                                    return true;
                                if (it - 5 >= x.begin())
                                {
                                    if (*(it - 3) <= *(it - 5) + *(it - 1) &&
                                        *(it - 4) + *it >= *(it - 2))
                                        return true;
                                }
        
                            }
                            while (it != x.end())
                            {
                                if (*it >= *(it - 2)) return true;
                                ++it;
                            }
        
                            return false;
                        }
                    }
                }
        
                return false;
            }
        };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.