leetcode刷题——day3

645. 错误的集合

class Solution {
    public int[] findErrorNums(int[] nums) {
        int[] err = new int[2];
        int n = nums.length;
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int cur : nums) {
            map.put(cur, map.getOrDefault(cur, 0) + 1);
        }
        for(int i = 1; i <= n; i++) {
            int count = map.getOrDefault(i, 0);
            if(count == 2) err[0] = i;
            if(count == 0) err[1] = i;
        }
        return err;
    }
}

697. 数组的度

class Solution {
    public int findShortestSubArray(int[] nums) {
        int n = nums.length;
        Map<Integer, int[]> map = new HashMap<Integer, int[]>();
        for(int i = 0; i < n; i++) {
            if(map.containsKey(nums[i])) {
                map.get(nums[i])[0]++;
                map.get(nums[i])[2] = i;
            } else {
                map.put(nums[i], new int[]{1, i, i});
            }
        }
        int minLen = n;
        int maxDegree = 0;
        for(Map.Entry<Integer,int[]> entry : map.entrySet()) {
            int[] arr = entry.getValue();
            if(arr[0] > maxDegree) {
                maxDegree = arr[0];
                minLen = arr[2] - arr[1] + 1;
            } else if(arr[0] == maxDegree) {
                minLen = Math.min(minLen, arr[2] - arr[1] + 1);
            }
        }
        return minLen;
    }
}
posted @ 2021-09-13 22:00  来一块小饼干  阅读(33)  评论(0编辑  收藏  举报