How can I fix the Time Limit Exceeded on my solution?


  • 0
    S
    public class Solution {
        
        public int numberOfArithmeticSlices(int[] A) {
            Set<Pair> seen = new HashSet<>(A.length);
            return isSeq(A, 0, 2, seen);
        }
    
        private int isSeq(int[] a, int start, int end, Set<Pair> seen) {
            if (end >= a.length || start < 0) {
                return 0;
            }
    
            Pair p = new Pair(start, end);
    
            if (seen.contains(p)){
                return 0;
            }
    
            seen.add(p);
            int diff = a[start + 1] - a[start];
    
            boolean f = true;
            for (int i = start; i < end; ++i) {
                if (a[i + 1] - a[i] != diff) {
                    f = false;
                    break;
                }
            }
    
            return (f ? 1 : 0) +
                    isSeq(a, start + 1, end + 1, seen) +
                    isSeq(a, start, end + 1, seen);
        }
        
        private static class Pair {
            final int x;
            final int y;
    
            private Pair(int x, int y) {
                this.x = x;
                this.y = y;
            }
    
            @Override
            public boolean equals(Object o) {
                if (this == o) return true;
                if (o == null || getClass() != o.getClass()) return false;
                Pair pair = (Pair) o;
                return x == pair.x &&
                        y == pair.y;
            }
    
            @Override
            public int hashCode() {
                return Objects.hash(x, y);
            }
        }
    }
    

Log in to reply
 

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