原题链接在这里:https://leetcode.com/problems/arithmetic-slices-ii-subsequence/
题目:
A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, these are arithmetic sequences:
1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9
The following sequence is not arithmetic.
1, 1, 2, 5, 7
A zero-indexed array A consisting of N numbers is given. A subsequence slice of that array is any sequence of integers (P0, P1, ..., Pk) such that 0 ≤ P0 < P1 < ... < Pk < N.
A subsequence slice (P0, P1, ..., Pk) of array A is called arithmetic if the sequence A[P0], A[P1], ..., A[Pk-1], A[Pk] is arithmetic. In particular, this means that k ≥ 2.
The function should return the number of arithmetic subsequence slices in the array A.
The input contains N integers. Every integer is in the range of -231 and 231-1 and 0 ≤ N ≤ 1000. The output is guaranteed to be less than 231-1.
Example:
Input: [2, 4, 6, 8, 10] Output: 7 Explanation: All arithmetic subsequence slices are: [2,4,6] [4,6,8] [6,8,10] [2,4,6,8] [4,6,8,10] [2,4,6,8,10] [2,6,10]
题解:
Following question: Arithmetic Slices.
The difference here is that subsequence doesn't need to be continuous. e.g. [2,6,10].
Thus when iterate to index i, it needs to go through all the j (j<i) from the beginning.
With A[i] and A[j], the diff = A[i] - A[j]. It needs to know the number of sequences(length doesn't need to be more than 2, 2 is okay) ending at A[j] with the same diff. Accumulate that to result.
Thus here, use an array of map to maintain the difference with frequency for each index.
There could be duplicate numbers in A. Thus at i, same diff may appear, get the original and add the new.
Time Complexity: O(n^2). n = A.length.
Space: O(n^2). Each map could be O(n), there are totally n maps.
AC Java:
1 class Solution { 2 public int numberOfArithmeticSlices(int[] A) { 3 int n = A.length; 4 Map<Integer, Integer> [] arrOfMap = new Map[n]; 5 int res = 0; 6 7 for(int i = 0; i<n; i++){ 8 arrOfMap[i] = new HashMap<>(); 9 10 for(int j = 0; j<i; j++){ 11 long diffLong = (long)A[i] - A[j]; 12 if(diffLong > Integer.MAX_VALUE || diffLong < Integer.MIN_VALUE){ 13 continue; 14 } 15 16 int diff = (int)diffLong; 17 int count = arrOfMap[j].getOrDefault(diff, 0); 18 res += count; 19 20 int original = arrOfMap[i].getOrDefault(diff, 0); 21 arrOfMap[i].put(diff, original+count+1); 22 } 23 } 24 25 return res; 26 } 27 }