Java solution 2ms


  • 0
    P
    boolean isLooping(int... numbers) {
        List<Integer> path = new ArrayList<>();
    
        for (int start = 0; start < numbers.length; ++start) {
            path.clear();
    
            int depth = 0;
            int index = start;
            do {
                index += numbers[index];
                if (index < 0) {
                    index += numbers.length;
                }
                index = index % numbers.length;
                depth++;
    
                if (path.contains(index)) {
                    path.add(index);
                    break;
                }
                path.add(index);
            } while (depth < numbers.length);
    
            // Loop was detected
            if (path.get(0) == path.get(path.size() - 1)) {
                // At least two elements
                if (path.size() - 1 <= 1) {
                    continue;
                }
    
                // Unidirectional
                boolean isUnidirectional = true;
                boolean forward = numbers[path.get(0)] > 0;
                for (int i = 1; i < path.size(); ++i) {
                    if ((numbers[path.get(i)] < 0 && forward) || (numbers[path.get(i)] > 0 && !forward)) {
                        isUnidirectional = false;
                        break;
                    }
                }
                if (!isUnidirectional) {
                    continue;
                }
    
                return true;
            }
        }
        return false;
    }

Log in to reply
 

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