LeetCode 5214. predetermined maximum difference sequence (Java) HashMap

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/pfdvnah/article/details/102238311

Title: 5214. longest sequence given difference

Give you an integer array arrand an integer difference, you find arrbetween all adjacent elements equal to a given difference differenceof the arithmetic sequence, and returns the arithmetic longest sequence length.

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

Example 2:
Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The arithmetic sequence is the longest of any single element.

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

prompt:

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

answer:

Map<key, value>Save to keyend of the sequence of maximum length.

Through the array arr, the number of kpredecessor nodes is pre = k - difference, therefore ksequence length plus 1 end, updates the maximum (return value), and updates mapthe key = ktime of value.

time complexity: THE ( n ) O (n) , without regard toHashMapfind the time complexity
and space complexity:uncertain

Java:

class Solution {
    public int longestSubsequence(	int[] arr,
                                    int difference) {
        Map<Integer, Integer> map = new HashMap<>();
        int ret = 0;
        for (int k : arr) {
            int pre = k - difference;// 前驱
            // 序列增加数k,因此长度加1
            int len = map.getOrDefault(pre, 0) + 1;
            ret = Math.max(ret, len);
            map.put(k, len);// 更新map
        }
        return ret;
    }
}

Guess you like

Origin blog.csdn.net/pfdvnah/article/details/102238311