日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

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

發(fā)布時(shí)間:2024/2/28 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode 594. Longest Harmonious Subsequence | 594. 最长和谐子序列 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目

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

題解

我的解法


測(cè)試用例

[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;} }

評(píng)論區(qū)優(yōu)雅解法

排序后,用兩個(gè)指針,類似于窗口

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;} }

總結(jié)

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

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。