先找到差值相等的連續數,大於2的話就能夠加,注意這裏加的是1+2+3+。。。+num-1的值,即num*(num-1)/2spa
1 public class Solution { 2 public int numberOfArithmeticSlices(int[] A) { 3 if (A.length < 3) return 0; 4 int[] diff = new int[A.length-1]; 5 for (int i = 0; i < diff.length; i++) { 6 diff[i] = A[i+1] - A[i]; 7 } 8 int num = 1; 9 int ans = 0; 10 int diffNum = diff[0]; 11 for (int i = 1; i < diff.length; i++) { 12 if (diff[i] == diffNum) num++; 13 else { 14 diffNum = diff[i]; 15 if (num > 1) { 16 ans += num * (num-1) / 2; 17 } 18 num = 1; 19 } 20 } 21 if (num > 1) { 22 ans += num * (num-1) / 2; 23 } 24 return ans; 25 } 26 }