Guest User

Untitled

a guest
Mar 19th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. /*
  2. Given a non-empty array of non-negative integers nums, the degree of this
  3. array is defined as the maximum frequency of any one of its elements.
  4. Your task is to find the smallest possible length of a (contiguous)
  5. subarray of nums, that has the same degree as nums.
  6. */
  7.  
  8. /**
  9. * @param {number[]} nums
  10. * @return {number}
  11. */
  12. var findShortestSubArray = function(nums) {
  13. var a = nums;
  14. var abc = [];
  15. //Fill hash
  16. var max = 0;
  17. for(var x = 0; x < a.length; x++) {
  18. if(abc[a[x]] === undefined) {
  19. abc[a[x]] = [];
  20. }
  21. abc[a[x]].push(x);
  22. if(!max) {
  23. max = abc[a[x]].length;
  24. }
  25. max = Math.max(abc[a[x]].length, max);
  26. }
  27.  
  28. var keys = Object.keys(abc);
  29.  
  30. //get largest subarray
  31. var min = null;
  32. var curr = 0;
  33. for(var y = 0; y < keys.length; y++) {
  34. var len = abc[keys[y]].length;
  35. if(len !== max) {
  36. continue;
  37. }
  38. curr = abc[keys[y]][len - 1] - abc[keys[y]][0];
  39. if(!min) {
  40. min = curr;
  41. }
  42. min = Math.min(min, curr);
  43. }
  44. return min + 1;
  45. };
Add Comment
Please, Sign In to add comment