zoukankan      html  css  js  c++  java
  • [Swift]LeetCode1218. 最长定差子序列 | Longest Arithmetic Subsequence of Given Difference

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(let_us_code)
    ➤博主域名:https://www.zengqiang.org
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/11626365.html
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    Given an integer array arr and an integer difference, return the length of the longest arithmetic subsequence in arr such that the difference between adjacent elements in the subsequence equals 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].
    

    Constraints:

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

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

    示例 1:

    输入:arr = [1,2,3,4], difference = 1
    输出:4
    解释:最长的等差子序列是 [1,2,3,4]。

    示例 2:

    输入:arr = [1,3,5,7], difference = 1
    输出:1
    解释:最长的等差子序列是任意单个元素。
    

    示例 3:

    输入:arr = [1,5,7,8,5,3,4,2,1], difference = -2
    输出:4
    解释:最长的等差子序列是 [7,5,3,1]。
    

    提示:

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

    Runtime: 748 ms
    Memory Usage: 23.9 MB
     1 class Solution {
     2     func longestSubsequence(_ arr: [Int], _ difference: Int) -> Int {
     3         var dp:[Int:Int] = [Int:Int]()
     4         var longest:Int = 0
     5         for i in 0..<arr.count
     6         {
     7             dp[arr[i]] = dp[arr[i]-difference,default:0] + 1
     8             longest = max(longest, dp[arr[i],default:0])
     9         }
    10         return longest
    11     }
    12 }
  • 相关阅读:
    常用模块汇总
    day 16 常用模块 time 和 datetime(1)
    二分法 函数式 模块
    day 15 模块 (3)
    vue require.context 检索文件夹内文件路径
    Node.js搭建本地服务,读取css/js/img/html等各种格式文件
    Nodejs搭建web服务器
    el-table横向滚动条固定在屏幕最下方显示
    IE浏览器 backspace键使浏览器回退
    vue ElementUI el-input 键盘enter事件 导致刷新表单问题
  • 原文地址:https://www.cnblogs.com/strengthen/p/11626365.html
Copyright © 2011-2022 走看看