LeetCode-594. Longest Harmonious Subsequence(Java)

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: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
------------------------------------------------------------------------------------------------------------------------------------------------------------------------

题意

从一个数组中找到一个harmonious array,这个harmonious array定义为数组的最大值和最小值之差等于1,现在需要找到最长的这种数组。

思路

找到最长的就是要找到出现次数最多的,然后可以利用hashmap来统计某个数字的出现次数,然后再循环数组,找每个数字n的次数,以及每个数字加1(n+1)后的数字出现次数,

然后比较结果,找到最大的即可。不需要找n-1的出现次数。

代码

public static int findLHS(int[] nums){
	Map<Long, Integer> map = new HashMap<>();
   	for (long num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
    	}
    	int result = 0;
    	for (long key : map.keySet()) {
       	    if (map.containsKey(key + 1)) {
            	result = Math.max(result, map.get(key + 1) + map.get(key));
            }
    	}
    	return result;
}

这里有用到map.getOrDefault(args,default)方法,这个方法的作用是在map中找key等于args,如果找到返回value,如果没找到则返回默认值default。

相似的方法putIfAbsent方法,这个方法也是在map中根据key找,如果找到,返回value,如果没找到,插入这个key,返回null;

putIfAbsent

If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.


getOrDefault

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.


If your goal is only to retrieve the value, then use getOrDefault. Else, if you want to set the value when it does not exist, use putIfAbsent.

我写的另外一个方法

public static int findLHS(int[] nums) {
        int length = nums.length;
        if(nums == null || nums.length <=0)
        	return 0;
        int firstValue = nums[0];
        int i=1;
        int maxCount=0;
        while(i<length){
        	int count=0;
        	int j=0;
        	boolean flag = false;
        	while(j<length){
        		if( nums[j] == firstValue+1){        			        		
        			flag = true;
        			count++;
        		}
        		if(nums[j] == firstValue){
        			count++;
        		}
        		j++;
        	}
        	firstValue = nums[i];
        	if(count > maxCount && flag){
        		maxCount = count;
        	}        	
        	i++;        
        }
        	return maxCount;	                
    }
运行了几个测试用例,返回值都是对的,但是leetCode提示超时

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值