LeetCode 446. Arithmetic Slices II

来源:互联网 发布:淘宝卖家如何改支付宝 编辑:程序博客网 时间:2024/06/05 03:21
**问题描述:**

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, 97, 7, 7, 73, -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: 7Explanation: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]


这道题是之前那道Arithmetic Slices的延伸,但是比较简单是因为要求等差数列是连续的,而这道题让我们求是等差数列的子序列,可以跳过某些数字,不一定非得连续,那么难度就加大了,但还是需要用DP来做。我们建立一个一维数组dp,数组里的元素不是数字,而是放一个哈希表,建立等差数列的差值和其长度之间的映射。我们遍历数组中的所有数字,对于当前遍历到的数字,又从开头遍历到当前数字,计算两个数字之差diff,如果越界了不做任何处理,如果没越界,我们看dp[i]中diff的差值映射自增1,然后我们看dp[j]中是否有diff的映射,如果有的话,说明此时已经能构成等差数列了,将dp[j][d]加入结果res中,然后再更新dp[i][d],这样等遍历完数组,res即为所求。即,对第i个体计算其与前面(j

public int numberOfArithmeticSlices(int[] A) {        int n=A.length;        int MAX=1001;        ArrayList<HashMap<Integer,Integer>>dp=new ArrayList<HashMap<Integer,Integer>>(n);        int result=0;        for(int i=0;i<n;i++){            dp.add(i,new HashMap<Integer,Integer>());            for(int j=0;j<i;j++){                long temp=(long)A[i]-A[j];                if(temp>Integer.MAX_VALUE||temp<Integer.MIN_VALUE)                    continue;                int diff=(int)temp;                HashMap<Integer,Integer> mapi=dp.get(i);                HashMap<Integer,Integer>mapj=dp.get(j);                if(mapi.get(diff)==null)                    mapi.put(diff,0);                mapi.put(diff,mapi.get(diff)+1);                if(mapj.get(diff)!=null){                    mapi.put(diff,mapi.get(diff)+mapj.get(diff));                    result+=mapj.get(diff);                }            }        }        return result;    }

原分析链接:http://www.cnblogs.com/grandyang/p/6057934.html