very clear c++


  • 2
    Y

    The key is to determine whether the circles are growing bigger or smaller. If it keeps growing bigger, then return false and if it keeps growing smaller, then return false. The only case when return true is when it converts from growing bigger to growing smaller, which is x[i] <= x[i-2]. Then whether it self-cross depends on x[i+1].

    bool isSelfCrossing(vector<int>& x){
    
    	if (x.size() < 4) return false;
    
    	int n = x.size();
    
    	bool larger = x[2] > x[0];
    	for (int i = 3; i < n;){
    		if (!larger){
    			if (x[i] >= x[i - 2]) return true;
    		}
    		else {
    			if (x[i] <= x[i - 2]){
    				larger = false;
    				if (x[i] == x[i - 2]) {
    					x[i - 1] = x[i - 1] - x[i - 3];
    				}else if ( i-4>=0 && x[i] >= x[i-2] - x[i - 4]){
    					x[i - 1] = x[i - 1] - x[i - 3];
    				}
    			}
    		}
    		++i;
    	}
    	return false;
    }
    

Log in to reply
 

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