public class DayCode {
public static void main(String[] args) {
int[] nums = new int[]{1,2,2,3,1,4,2};
int ans = new DayCode().findShortestSubArray(nums);
System.out.println("ans is " + ans);
}
/**
* https://leetcode-cn.com/problems/degree-of-an-array/
* 时间复杂度是O(n),空间复杂度是O(n)
* @param nums
* @return
*/
public int findShortestSubArray(int[] nums) {
int ans = Integer.MAX_VALUE;
Map<Integer, DegreeNode> numDegreeMap = new HashMap<>();
int maxDegree = 0;
for (int i = 0 ; i < nums.length; i++) {
DegreeNode node = new DegreeNode();
if (numDegreeMap.containsKey(nums[i])) {
node = numDegreeMap.get(nums[i]);
node.degree += 1;
} else {
node.degree = 1;
node.beginIdx = i;
}
node.endIdx = i;
maxDegree = Math.max(maxDegree, node.degree);
numDegreeMap.put(nums[i], node);
}
for (DegreeNode item : numDegreeMap.values()) {
if (item.degree == maxDegree) {
ans = Math.min(ans, item.endIdx - item.beginIdx + 1);
}
}
return ans;
}
class DegreeNode {
int degree;
int beginIdx;
int endIdx;
public DegreeNode () {
this.degree = 0;
this.beginIdx = 0;
this.endIdx = 0;
}
}
}
评论