LeetCode_697_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 length of a (contiguous) subarray of nums, that has the same degree as nums.

Example 1:

Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

代码实现

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Cser_W on 2017/10/16.
 */
class structOfnum {
    private int value;
    private int start;
    private int end;

    public structOfnum(int value, int start, int end) {
        this.value = value;
        this.start = start;
        this.end = end;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getEnd() {
        return end;
    }

    public void setEnd(int end) {
        this.end = end;
    }

}
public class DegreeofanArray697 {
    public static int findShortestSubArray(int[] nums) {
        if (nums.length == 0)
            return 0;
        Map<Integer,structOfnum> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                map.get(nums[i]).setValue( map.get(nums[i]).getValue() + 1 );
                map.get(nums[i]).setEnd(i);
            } else {
                map.put(nums[i],new structOfnum(1,i,i));
            }
        }
        int maxFrepuen = Integer.MIN_VALUE;
        int minLen = Integer.MAX_VALUE;
        for (Integer key : map.keySet()) {
            if (map.get(key).getValue() >= maxFrepuen) {

                if (map.get(key).getValue() == maxFrepuen) {
                    minLen =  Math.min(minLen, map.get(key).getEnd() - map.get(key).getStart() + 1);
                } else {
                    minLen = map.get(key).getEnd() - map.get(key).getStart() + 1;
                }
                maxFrepuen = map.get(key).getValue();

            }
        }
        return minLen;
    }
    public static void main(String[] args){
        int[] arr = new int[]{1,2,2,3,1,4,2};
        int result = findShortestSubArray(arr);
        System.out.println(result);

    }
}

猜你喜欢

转载自blog.csdn.net/u013310517/article/details/78254641