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

思路:
  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;

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、用C语言实现一个revert函数,它的功能是将输入的字符串在原串上倒序后返回。 2、用C语言实现函数void ...
    希崽家的小哲阅读 6,376评论 0 12
  • 孕妇高血压的症状主要表现为:1、头疼,部位多在后脑,并伴有恶心、呕吐等症状。2、眩晕,可能会在突然蹲下或起立时有所...
    聿淑阅读 295评论 0 0
  • 应该是从小学的时候开始便听FM电台,每周追本地的一个HiFi节目,不断的好奇什么是『前后级』,什么是『胆味』。 现...
    玩家翁伟阅读 830评论 0 3
  • 相关知识:js的三种编码解码方式的区别 转载原链接:http://www.cnblogs.com/chang...
    七里汀阅读 1,250评论 0 0
  • 很多事强求不来,做好自己该做的想做的,这辈子活的是自己的。
    我爱吃鱼吃火锅阅读 160评论 0 0