LeetCode 1218. Longest Arithmetic Subsequence of Given Difference

[Med] LeetCode 1218. Longest Arithmetic Subsequence of Given Difference

链接: https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/

题目描述:
Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.

给你一个整数数组 arr 和一个整数 difference,请你找出 arr 中所有相邻元素之间的差等于给定 difference 的等差子序列,并返回其中最长的等差子序列的长度。

Example 1:

Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].

Example 2:

Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.

Example 3:

Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].

Note:

  • 1 <= arr.length <= 10^5
  • -10^4 <= arr[i], difference <= 10^4

Tag: Pre-Sum
解题思路
题目让我们找一个subsequence,使得这个subsequence前一个元素和后一个元素的差值为difference.我们只需要用hashmap就可以了。hashmap当中的key为数字本身,value为连上这个数字之后最长的序列长度。最终遍历一次map我们就可以知道最长的value是多长了。

解法一:

class Solution {
    public int longestSubsequence(int[] arr, int difference) {
        Map<Integer, Integer> map = new HashMap<>();
        int res = 1;
        for(int num:arr){
            if(map.containsKey(num-difference)){
                map.put(num, map.get(num-difference)+1);
                res = Math.max(res, map.get(num));
            }else{
                map.put(num, 1);
            }
        }
        return res;
    }
}

解法二:
一个更加精简的写法

class Solution {
    public int longestSubsequence(int[] arr, int diff) {
        Map<Integer, Integer> map = new HashMap<>();
        int res = 1;
        for (int num : arr) {
            int val = map.getOrDefault(num - diff, 0) + 1;
            map.put(num, val);
            res = Math.max(res, val);
        }
        return res;
    }
}

你可能感兴趣的:(leetcode解题思路)