Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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.
- */
- /**
- * @param {number[]} nums
- * @return {number}
- */
- var findShortestSubArray = function(nums) {
- var a = nums;
- var abc = [];
- //Fill hash
- var max = 0;
- for(var x = 0; x < a.length; x++) {
- if(abc[a[x]] === undefined) {
- abc[a[x]] = [];
- }
- abc[a[x]].push(x);
- if(!max) {
- max = abc[a[x]].length;
- }
- max = Math.max(abc[a[x]].length, max);
- }
- var keys = Object.keys(abc);
- //get largest subarray
- var min = null;
- var curr = 0;
- for(var y = 0; y < keys.length; y++) {
- var len = abc[keys[y]].length;
- if(len !== max) {
- continue;
- }
- curr = abc[keys[y]][len - 1] - abc[keys[y]][0];
- if(!min) {
- min = curr;
- }
- min = Math.min(min, curr);
- }
- return min + 1;
- };
Add Comment
Please, Sign In to add comment