Java solution practice


  • 0
    D

    Learned from https://discuss.leetcode.com/topic/67413/detailed-explanation-for-java-o-n-2-solution

    public class Solution {
        public int numberOfArithmeticSlices(int[] A) {
            if (A == null || A.length < 3) {
                return 0;
            }
            int n = A.length;
            int totalSlices = 0;
            Map<Integer, Integer>[] geTwo = new Map[n];
            for (int i = 0; i < n; i++) {
                geTwo[i] = new HashMap<>();
                for (int j = 0; j < i; j++) {
                    long difflong = (long)A[i] - A[j];
                    if (difflong < Integer.MIN_VALUE || difflong > Integer.MAX_VALUE) {
                        continue;
                    }
                    int diff = (int)difflong;
                    int jgeTwo = geTwo[j].getOrDefault(diff, 0);
                    totalSlices += jgeTwo;
                    geTwo[i].put(diff, geTwo[i].getOrDefault(diff, 0) + jgeTwo + 1);
                }
            }
            return totalSlices;
        }
    }
    

Log in to reply
 

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