Leet Code知识点总结 - 594

LeetCode 594. Longest Harmonious Subsequence

考点 难度
Array Easy
题目

Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor.

The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor’s advice.

Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.

思路

看到题首先想到计算每个数字出现的次数,从次数最多的数字n往下排,找n-1或者n+1有没有出现,选出现次数更多的一个,以此类推。
solution里面的【Approach 4: Using HashMap】和这种方法很像,但是码更简单。主要区别在最后一步。
另外在建map的时候可以用getOrDefault( )快速查找。

答案

按照solution的方法改之后答案和solution提供的很像

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

猜你喜欢

转载自blog.csdn.net/m0_59773145/article/details/120024174