본문 바로가기
Problem Solving/LeetCode

[LeetCode] 697. Degree of an Array - Java

by graycode 2026. 9. 26.

• 문제 링크

 

Degree of an Array - LeetCode

Can you solve this real interview question? Degree of an Array - Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible leng

leetcode.com

 

• 풀이 코드

public class Solution {

    public int findShortestSubArray(int[] nums) {
        int n = 0;
        for (int num : nums) if (num > n) n = num;

        int[] cnt = new int[n + 1], anc = new int[n + 1];
        int max = 0, len = nums.length;
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (++cnt[num] == 1) anc[num] = i;

            if (cnt[num] > max) {
                max = cnt[num];
                len = i - anc[num] + 1;
            } else if (cnt[num] == max) len = Math.min(len, i - anc[num] + 1);
        }

        return len;
    }

}

댓글