美文网首页安卓集中营代码笔记程序员
用到hashmap解的一道算法题(meituan 笔试题):

用到hashmap解的一道算法题(meituan 笔试题):

作者: _VITA | 来源:发表于2018-09-08 18:59 被阅读7次
    思路:
    1. 建模:求子区间个数,子区间的要求:存在某数出现过t次以上;
    2. 记录某数出现次数用hashmap最佳;牺牲一定的空间复杂度换取时间复杂度。

    代码:

    import java.util.Collection;
    
    import java.util.HashMap;
    
    import java.util.Map;
    
    import java.util.Scanner;
    
    public class solution {
    
        public static void main(String[] args) {
    
            Scanner sc = new Scanner(System.in);
    
            int n = sc.nextInt();
    
            int k = sc.nextInt();
    
            int t = sc.nextInt();
    
            int[] array = new int[n];
    
            for (int i = 0; i < n; i++) {
    
                array[i] = sc.nextInt();
    
            }
    
            int result = 0;
    
            for (int i = 0; i <= array.length - k; i++) {
    
                HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    
                recordinfo(map, array, i, i + k);
    
                result += isAppearThanT(map, t);
    
            }
    
            System.out.println(result);
    
        }
    
        private static void recordinfo(HashMap<Integer, Integer> map, int[] array, int low, int high) {
    
            for (int i = low; i < high; i++) {
    
                if (map.containsKey(array[i])) {
    
                    int temp = map.get(array[i]);
    
                    map.put(array[i], temp + 1);
    
                } else {
    
                    map.put(array[i], 1);
    
                }
    
            }
    
        }
    
        private static int isAppearThanT(HashMap<Integer, Integer> map, int t) {
            int a = 0;
    
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    
                if (entry.getValue() >= t) {
    
                    a++;
                }
    
            }
            return a;
    
        }
    
    }
    
    

    相关文章

      网友评论

        本文标题:用到hashmap解的一道算法题(meituan 笔试题):

        本文链接:https://www.haomeiwen.com/subject/zkdlgftx.html