日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

leetcode 594. Longest Harmonious Subsequence | 594. 最长和谐子序列

發布時間:2024/2/28 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode 594. Longest Harmonious Subsequence | 594. 最长和谐子序列 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目

https://leetcode-cn.com/problems/longest-harmonious-subsequence/

題解

我的解法


測試用例

[1]
[1,2]
[2,1]
[3,1]
[3,1,1]
[3,5,5]
[1,3,5,7]
[2,2]
[1,2,1,2,1,2,1,2,1,2]
[3,3,3,2,2,2,1,1,1]
[3,3,2]
[1,3,2,2,5,2,3,7]

import java.util.Arrays;class Solution {public int findLHS(int[] nums) {if (nums.length == 1) return 0;Arrays.sort(nums);int maxSum = 0;int numPre = Integer.MAX_VALUE;int cntPre = 0;int cntCur = 1;for (int i = 0; i < nums.length - 1; i++) {if (nums[i] == nums[i + 1]) {cntCur++;} else {if (numPre + 1 == nums[i]) { // update maxSum only when it's continuousmaxSum = Math.max(maxSum, cntPre + cntCur);}cntPre = cntCur;cntCur = 1;numPre = nums[i];}}// boundary: the last numberif (nums[nums.length - 2] != nums[nums.length - 1]) {cntPre = cntCur;cntCur = 1;}if (numPre + 1 == nums[nums.length - 1]) { // update maxSum only when it's continuousmaxSum = Math.max(maxSum, cntPre + cntCur);}return maxSum;} }

評論區優雅解法

排序后,用兩個指針,類似于窗口

class Solution {public int findLHS(int[] nums) {Arrays.sort(nums);int begin = 0,res = 0;for(int end = 0;end < nums.length;end++){while(nums[end] - nums[begin] > 1)begin++;if(nums[end] - nums[begin] == 1)res = Math.max(res,end - begin + 1);}return res;} }

總結

以上是生活随笔為你收集整理的leetcode 594. Longest Harmonious Subsequence | 594. 最长和谐子序列的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。