LeetCode.594 Longest Harmonious Subsequence

来源:互联网 发布:梦里花落知多少网王txt 编辑:程序博客网 时间:2024/06/06 23:52

题目:

We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.

Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

Example 1:

Input: [1,3,2,2,5,2,3,7]Output: 5Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Note: The length of the input array will not exceed 20,000.

分析(参考答案-推荐):

class Solution {    public int findLHS(int[] nums) {        //给定一个数组,找出其中长度最长的子队列(由其中元素有序组成)的和谐数组(最大值和最小值差值恰好为1)        //思路:求出各个数的出现的次数,最后对相邻的两个数出现的次数求和,最大的即使结果                //参考答案:先对数组排序,之后进行判断前后是否相差1,统计前后相同元素的次数        Arrays.sort(nums);        //前一个元素的次数        int lastCount=0;        int maxCount=0;        for(int i=0;i<nums.length;i++){            int count=1;            if(i>0&&nums[i]-nums[i-1]==1){                //求相同元素个数                while(i<nums.length-1&&nums[i]==nums[i+1]){                    count++;                    i++;                }                maxCount=Math.max(maxCount,lastCount+count);                //给相同元素赋值给lastCount                lastCount=count;            }else{                //统计相同个数                while(i<nums.length-1&&nums[i]==nums[i+1]){                    count++;                    i++;                }                lastCount=count;            }        }        return maxCount;    }}

分析2(原创-HashMap):

class Solution {    public int findLHS(int[] nums) {        //给定一个数组,找出其中长度最长的子队列(由其中元素有序组成)的和谐数组(最大值和最小值差值恰好为1)        //思路:求出各个数的出现的次数,最后对相邻的两个数出现的次数求和,最大的即使结果        //防止负数        HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();        int maxCount=0;        //求各个数出现的次数        for(int i=0;i<nums.length;i++){            hm.put(nums[i],hm.getOrDefault(nums[i],0)+1);        }                //求相邻数之和        for(int key:hm.keySet()){            if(hm.get(key-1)!=null&&hm.get(key+1)!=null){                maxCount=Math.max(maxCount,hm.get(key)+Math.max(hm.get(key-1),hm.get(key+1)));            }else if(hm.get(key-1)!=null&&hm.get(key+1)==null){                //只有前面                maxCount=Math.max(maxCount,hm.get(key)+hm.get(key-1));            }else if(hm.get(key+1)!=null&&hm.get(key-1)==null){                //只有后面                maxCount=Math.max(maxCount,hm.get(key)+hm.get(key+1));            }        }                return maxCount;    }}



原创粉丝点击