413. Arithmetic Slices

我自己的写法觉得有点蠢……先把每个相邻数之间差算出来,然后再走一遍,如果有n(n>=2)连续的相等的数,那么可以组成的组合就是(n-2)+(n-3)+..+1

 1     public int numberOfArithmeticSlices(int[] A) {
 2         if(A.length < 3) {
 3             return 0;
 4         }
 5         int len = A.length;
 6         int[] dif = new int[len - 1];
 7         for(int i = 0; i < len - 1; i++) {
 8             dif[i] = A[i + 1] - A[i];
 9         }
10         int cnt = 1;
11         int res = 0;
12         for(int i = 1; i < len - 1; i++) {
13             if(dif[i-1] == dif[i]) {
14                 cnt++;
15             } else {
16                 if(cnt >= 2) {
17                     for(int j = cnt - 1; j >= 1; j--) {
18                         res += j;
19                     }
20                 }
21                 cnt = 1;
22             }
23         }
24         if(cnt >= 2) {
25             for(int j = cnt - 1; j >= 1; j--) {
26                 res += j;
27             }
28         }
29         return res;
30     }

看了下别人的,其实道理倒是一样的,不过写起来好看多了

 

 1 public int numberOfArithmeticSlices(int[] A) {
 2     int curr = 0, sum = 0;
 3     for (int i=2; i<A.length; i++)
 4         if (A[i]-A[i-1] == A[i-1]-A[i-2]) {
 5             curr += 1;
 6             sum += curr;
 7         } else {
 8             curr = 0;
 9         }
10     return sum;
11 }

 

posted @ 2016-10-24 08:24  warmland  阅读(245)  评论(0编辑  收藏  举报