Leetcode. Hash table .594 harmony longest sequence

1. Specific topics :

Harmony array means the difference between the maximum and minimum values ​​of the elements in an array exactly 1. Now, given an array of integers, you need to find the length of the longest sequence of harmony in all possible sub-sequences.

Example 1: 

Input: [1,3,2,2,5,2,3,7] Output: Reason 5: Harmony longest array is: [3,2,2,2,3]

Description: The maximum length of the input array does not exceed 20,000.

2. Analysis of ideas :

Since the subject is not required in the original sequence of elements in the array is continuous, requires only the sequence up to the elements. Therefore, considering the number of records of each element when traversing the array, which is recorded in a hash table (key-num, value-num number).

For a number "num", the sequence number harmonious composition may be in its "num +. 1" or "num-1", so that for the "num", this length is the longest sequence harmony "num number of" + " the number num + 1 ", or" num number of "+" the number "num-1, then at the same time through the array can be updated result value longest.

Note: If for the "num", no current map "num + 1" or "num-1", then the sequence length of 0 harmonious.

3. Code :

 1 public int findLHS(int[] nums) {
 2         HashMap<Integer,Integer> map = new HashMap<>();
 3         int longest = 0;
 4         for(int i = 0; i < nums.length; i++){
 5             if(map.containsKey(nums[i])){
 6                 int newValue = map.get(nums[i]) + 1;
 7                 map.put(nums[i], newValue);
 8             }else{
 9                 map.put(nums[i], 1);
10             }
11             int temp = 
12                 map.containsKey(nums[i] - 1) ? map.get(nums[i] - 1) + map.get(nums[i]) : 0;
13             longest = Math.max(longest, temp);
14             temp = 
15                 map.containsKey(nums[i] + 1) ? map.get(nums[i] + 1) + map.get(nums[i]) : 0;
16             longest = Math.max(longest, temp);
17         }
18         return longest;
19     }

4. Code Optimization :

//冗余,可以用一个方法代替
for(int i = 0; i < nums.length; i++){
            if(map.containsKey(nums[i])){
                int newValue = map.get(nums[i]) + 1;
                map.put(nums[i], newValue);
}else{
                map.put(nums[i], 1);
}

//HashMap api中方法getOrDefault()
 map.put(num, map.getOrDefault(num, 0) + 1);

 

 

Guess you like

Origin www.cnblogs.com/XRH2019/p/11824226.html
Recommended