LeetCode Daily Question 697. Degree of Array

697. Array Degree

Given a non-empty integer array containing only non-negative numbers nums, the degree of the array is defined as the maximum value of any element in the exponent group.

Your task is to numsfind and in numsthe shortest of have the same size of consecutive sub-array and returns its length.

Example 1:

输入:[1, 2, 2, 3, 1]
输出:2
解释:
输入数组的度是2,因为元素12的出现频数最大,均为2.
连续子数组里面拥有相同度的有如下所示:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
最短连续子数组[2, 2]的长度为2,所以返回2.

Example 2:

输入:[1,2,2,3,1,4,2]
输出:6

prompt:

  • nums.length is in the range of 1 to 50,000.
  • nums[i] is an integer in the range of 0 to 49,999.

Method one: sliding window

Problem-solving ideas

The description of the title is rather obscure, especially Example 1.

Translation : the degree of the array -> the number of occurrences of each element in the array, the maximum value; find the shortest sub-array length that contains this value.

  • The first step, of course, is to find the "degree of the array". Here, an array is used instead of the hash table to count, and the efficiency of the hash table is far inferior to that of the array.
  • Analog double sliding window pointer [left, right], rightthe pointer to the right traverse, when there are equal number of occurrences of an element 数组的度, the moving leftpointer to the nums[right]element first appears is local, and the calculation section size. Until the array is traversed.

Reference Code

public int findShortestSubArray(int[] nums) {
    
    
	// 计算“数组的度”
    int deg = 0;
    int[] counts = new int[50000];
    for(int num : nums) {
    
    
        counts[num]++;
        deg = Math.max(deg, counts[num]);
    }
	// 复原数组
    Arrays.fill(counts, 0);
    
    int n = nums.length;
    int ret = n;
    int left = 0, right = 0;
    while (right < n) {
    
    
        counts[nums[right]]++;
        if (counts[nums[right]] == deg) {
    
    
            while (nums[left] != nums[right]) {
    
    
                counts[nums[left]]--;
                left++;
            }
            ret = Math.min(ret, right - left + 1);
        }
        right++;
    }
    return ret;
}

Results of the
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_27007509/article/details/113878718