用到hashmap解的一道算法題(meituan 筆試題):

思路:
  1. 建模:求子區(qū)間個數(shù),子區(qū)間的要求:存在某數(shù)出現(xiàn)過t次以上;
  2. 記錄某數(shù)出現(xiàn)次數(shù)用hashmap最佳;犧牲一定的空間復(fù)雜度換取時間復(fù)雜度。

代碼:

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;

    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容