코린이의 소소한 공부노트

[LeetCode/Easy] 2190. Most Frequent Number Following Key In an Array 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 2190. Most Frequent Number Following Key In an Array

무지맘 2023. 4. 27. 19:56

1. Input

1) int[] nums

2) int key

 

2. Output

1) nums를 앞에서부터 확인하면서 key를 만날 때마다 key 다음에 나오는 정수가 몇번 나오는지 확인한 후, 빈도수가 가장 높은 정수를 반환

 

3. Constraint

1) 2 <= nums.length <= 1000

2) 1 <= nums[i] <= 1000

3) 정답은 반드시 1개가 나온다.

 

4. Example

Input: nums = [1,100,200,1,100], key = 1 -> Output: 100

설명: 1 다음에 나오는 정수는 100뿐이므로 100을 반환한다.

 

5. Code

1) 첫 코드(2023/04/27)

class Solution {
    public int mostFrequent(int[] nums, int key) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i=0 ; i<nums.length-1 ; i++)
            if(nums[i]==key)
                map.put(nums[i+1], map.getOrDefault(nums[i+1],0)+1);
        Iterator it = map.entrySet().iterator();
        Map.Entry e = (Map.Entry)it.next();
        int max = (int)e.getKey();
        while(it.hasNext()){
            e = (Map.Entry)it.next();
            if((int)map.get(max)<(int)e.getValue())
                max = (int)e.getKey();
        }
        return max;
    }
}