|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +/** |
| 9 | + * 697. Degree of an Array |
| 10 | + * |
| 11 | + * 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. |
| 12 | + * Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. |
| 13 | +
|
| 14 | + Example 1: |
| 15 | +
|
| 16 | + Input: [1, 2, 2, 3, 1] |
| 17 | + Output: 2 |
| 18 | + Explanation: |
| 19 | + The input array has a degree of 2 because both elements 1 and 2 appear twice. |
| 20 | + Of the subarrays that have the same degree: |
| 21 | + [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] |
| 22 | + The shortest length is 2. So return 2. |
| 23 | +
|
| 24 | + Example 2: |
| 25 | + Input: [1,2,2,3,1,4,2] |
| 26 | + Output: 6 |
| 27 | +
|
| 28 | + Note: |
| 29 | + nums.length will be between 1 and 50,000. |
| 30 | + nums[i] will be an integer between 0 and 49,999. |
| 31 | + */ |
| 32 | +public class _697 { |
| 33 | + public static class Solution1 { |
| 34 | + public int findShortestSubArray(int[] nums) { |
| 35 | + Map<Integer, Integer> map = new HashMap<>(); |
| 36 | + for (int i = 0; i < nums.length; i++) { |
| 37 | + if (map.containsKey(nums[i])) { |
| 38 | + map.put(nums[i], map.get(nums[i]) + 1); |
| 39 | + } else { |
| 40 | + map.put(nums[i], 1); |
| 41 | + } |
| 42 | + } |
| 43 | + int degree = -1; |
| 44 | + for (int key : map.keySet()) { |
| 45 | + degree = Math.max(degree, map.get(key)); |
| 46 | + } |
| 47 | + List<Integer> candidateNums = new ArrayList(); |
| 48 | + for (int key : map.keySet()) { |
| 49 | + if (map.get(key) == degree) { |
| 50 | + candidateNums.add(key); |
| 51 | + } |
| 52 | + } |
| 53 | + int shortest = Integer.MAX_VALUE; |
| 54 | + for (int candidate : candidateNums) { |
| 55 | + shortest = Math.min(shortest, findLength(nums, candidate)); |
| 56 | + } |
| 57 | + return shortest; |
| 58 | + } |
| 59 | + |
| 60 | + int findLength(int[] arr, int candidate) { |
| 61 | + { |
| 62 | + int firstAppearance = Integer.MAX_VALUE; |
| 63 | + for (int i = 0; i < arr.length; i++) { |
| 64 | + if (arr[i] == candidate) { |
| 65 | + firstAppearance = i; |
| 66 | + break; |
| 67 | + } |
| 68 | + } |
| 69 | + int lastAppearance = arr.length - 1; |
| 70 | + for (int i = arr.length - 1; i > firstAppearance; i--) { |
| 71 | + if (arr[i] == candidate) { |
| 72 | + lastAppearance = i; |
| 73 | + break; |
| 74 | + } |
| 75 | + } |
| 76 | + return (lastAppearance - firstAppearance) + 1; |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments