594. Longest Harmonious Subsequence

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].

从数组中找出一段子序列(不要求连续),要求子序列最大数和最小数之差为1,输出最长的长度。

C++(119ms):
 1 class Solution {
 2 public:
 3     int findLHS(vector<int>& nums) {
 4         unordered_map<int,int> Map ;
 5         int res = 0 ;
 6         for(int i : nums){
 7             Map[i]++ ;
 8         }
 9         for(auto it : Map){
10             if (Map.count(it.first -1)){
11                 res = max(res,it.second + Map[it.first -1]) ;
12             }
13         }
14         return res ;
15     }
16 };

 

 

 

java(79ms):
 1 class Solution {
 2     public int findLHS(int[] nums) {
 3         HashMap<Integer,Integer> map = new HashMap() ;
 4         int res = 0 ;
 5         for(int num :nums){
 6             map.put(num, map.getOrDefault(num,0)+1) ;
 7         }
 8         
 9         for(int num : map.keySet()){
10             if (map.containsKey(num + 1)){
11                 res = Math.max(res, map.get(num) + map.get(num+1)) ;
12             }
13         }
14         return res ;
15     }
16 }

 

 

Map.getOrDefault(Object, V)

Map的新方法getOrDefault(Object,V)允许调用者在代码语句中规定获得在map中符合提供的键的值,否则在没有找到提供的键的匹配项的时候返回一个“默认值”。

下一段代码列举对比了如何在JDK8之前检查一个map中匹配提供键的值是否找到,没找到匹配项就使用一个默认值是如何实现的,并且现在在JDK8中是如何实现的。

 1 /*
 2  * 示范Map.getOrDefault方法并和JDK8之前的实现方法做对比。JDK8
 3  * 中新增的Map.getOrDefault方法相比于传统的实现方法,所用的代码行数更少
 4  * 并且允许用一个final类型的变量来接收返回值。 
 5  */
 6 
 7 // JDK8之前的实现方法
 8 String capitalGeorgia = statesAndCapitals.get("Georgia");
 9 if (capitalGeorgia == null)
10 {
11    capitalGeorgia = "Unknown";
12 }
13 
14 // JDK8的实现方法
15 final String capitalWisconsin = statesAndCapitals.getOrDefault("Wisconsin", "Unknown");

Apache Commons包的DefaultedMap类提供了和新的Map.getOrDefault(Object, V)方法类似的功能。Groovy GDK中为Groovy包含了一个类似的方法,Map.get(Object,Object)

但是这个方法的行为有一点不同,因为它不仅仅在“键”没找到的时候返回提供的默认值,而且还会将键和默认值增加到调用的map中。

 
posted @ 2017-11-06 10:25  __Meng  阅读(147)  评论(0编辑  收藏  举报