记录每日LeetCode 1027.最长最差数列 Java实现

题目描述:

给你一个整数数组 nums,返回 nums 中最长等差子序列的长度。

回想一下,nums 的子序列是一个列表 nums[i1], nums[i2], ..., nums[ik] ,且 0 <= i1 < i2 < ... < ik <= nums.length - 1。并且如果 seq[i+1] - seq[i]( 0 <= i < seq.length - 1) 的值都相同,那么序列 seq 是等差的。

初始代码:

class Solution {
    public int longestArithSeqLength(int[] nums) {
        
    }
}

示例1:

输入:nums = [3,6,9,12]
输出:4
解释: 
整个数组是公差为 3 的等差数列。

示例2:

输入:nums = [9,4,7,2,10]
输出:3
解释:
最长的等差子序列是 [4,7,10]。

示例3:

输入:nums = [20,1,15,3,10,5,8]
输出:4
解释:
最长的等差子序列是 [20,15,10,5]。

参考答案:

class Solution {
    public int longestArithSeqLength(int[] nums) {
        int count = 0;
        //定义存放公差的数组:由于最大数为500 所以下标最大到1000
        int[][] arr = new int[nums.length][1001];
        for(int i = 1; i < nums.length; ++i){
            for(int j = i - 1; j >= 0; --j){
                //因为最小为0,最大为500,为了防止出现负数导致数组下标错误所以加500
                int d = nums[i] - nums[j] + 500;
                //在第i个一维数组的公差d位置处赋值
                if(arr[i][d] == 0){
                    arr[i][d] = arr[j][d] + 1;
                    count = Math.max(count,arr[i][d]);
                }
            }
        }
        return count + 1;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_65563175/article/details/130304253