697. 数组的度

给定一个非空且只包含非负数的整数数组 nums, 数组的度的定义是指数组里任一元素出现频数的最大值。

你的任务是找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。

示例 1:

输入: [1, 2, 2, 3, 1]
输出: 2
解释: 
输入数组的度是2,因为元素1和2的出现频数最大,均为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.

示例 2:

输入: [1,2,2,3,1,4,2]
输出: 6
class Solution {
    public int findShortestSubArray(int[] nums) {
        HashMap<Integer,Integer> tj = new HashMap<>();
	        for(int i : nums){
	        	int num = 0;
	        	if(tj.containsKey(i)) {
	        		num = tj.get(i);
	        	}
	            
	            num +=1;
	            tj.put(i,num);
	        }
	        int max = 0;
	        int maxNum = 0;
	        for(int i : nums){
	            if(tj.get(i)>=max){
	                max = tj.get(i);
	                maxNum = i;
	            }
	        }
	        System.out.println(max);
	        Set<Integer> set = tj.keySet();
	        int minDis = Integer.MAX_VALUE;
	        for(int n:set){
	            int temp = Integer.MAX_VALUE;
	            if(tj.get(n) == max){
	                int i=0,j = nums.length-1;
	                while(nums[i] != n && i<j)
	                    i++;
	                while(nums[j] != n && i<j)
	                    j--;
	                temp = j - i + 1;
	            }
	            minDis = Math.min(temp,minDis);
	        }
        return minDis;
    } 
}

猜你喜欢

转载自blog.csdn.net/shuzishij/article/details/83796381