LeetCode 446. 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]
Subscribe to see which companies asked this question

题意解析

这道题的含义就是找出数列中所有3个数以上的等差数列的数量。

解法分析

使用动态规划来解这道题。假设dp[i][j]表示以A[i]结尾的子序列(P0, P1, …, Pi)构成的数列,序列中的元素之差为j。而dp[i][j]=dp[k][j]>0?dp[k][j]+1:1,0<=i

解题代码

    public int numberOfArithmeticSlices(int[] A) {
        int re = 0;
        HashMap<Integer, HashMap<Long, Integer>> diffMaps = new HashMap<>();
        for (int i = 0; i < A.length; i++) {
            HashMap<Long, Integer> diffMap = new HashMap<>();
            diffMaps.put(i, diffMap);
            int num = A[i];
            for (int j = 0; j < i; j++) {
                if ((long) num - A[j] > Integer.MAX_VALUE)
                    continue;
                if ((long) num - A[j] < Integer.MIN_VALUE)
                    continue;
                long diff = (long) num - A[j];
                int count = diffMaps.get(j).getOrDefault(diff, 0);
                diffMaps.get(i).put(diff, diffMaps.get(i).getOrDefault(diff, 0) + count + 1);
                re += count;
            }
        }
        return re;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值