leetcode 992. Subarrays with K Different Integers

题目内容

Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.

(For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)

Return the number of good subarrays of A.

Example:
Input: A = [1,2,1,2,3], K = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].
Example 2:

Input: A = [1,2,1,3,4], K = 3
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

分析过程

  • 题目归类:
    array
  • 题目分析:
    ij 为字串首和尾
    那hashmap 来保存每一个结果,对于hashmap的key数不能超过K个,设置flag 来保存当前k的值
      添加string.charAt(j)hashmap中,并判断目前的flag 和 K 的关系
      1. 小于K
      j右移
      2. 等于k
      sum ++;
      j++;
      3.大于k
      hashmap中的s.charAt(i++)减一,如果减到0了,则直接删除这个key/value;
    
  • 边界分析:
    • 空值分析
    • 循环边界分析
      j == s.length()时停止
  • 方法分析:
    • 数据结构分析
      hashmap就是比较适合做这种题目
    • 状态机
    • 状态转移方程
    • 最优解
  • 测试用例构建
    [] 0,
    [aaa],

代码实现 大数据会超时,所以学习别人的方法

import java.util.*;
class Solution {
    public int subarraysWithKDistinct(int[] A, int K) {
         
        HashMap<Integer,Integer> map = new HashMap<>();
        int flag = 0;
        int sum  = 0;
        int i = 0,j = 0;
        int addFlag = 0;
        while(j<A.length){
            if(map.containsKey(A[j])&&addFlag == 0)
                map.put(A[j],map.get(A[j])+1);
            else if(addFlag == 0){
                map.put(A[j],1);
                flag++;
            }
                
            if(flag < K) {
                j++;
                addFlag=0;
            }else if (flag == K){
                sum++;
                int m = i + 1;
                while(m<=j){
                    int n = m;
                    HashMap<Integer,Integer> map1 = new HashMap<>();
                    while(n<=j){
                        if(map1.containsKey(A[n]))
                        map1.put(A[n],map.get(A[n])+1);
                    else{
                        map1.put(A[n],1);
                        }
                         n++;
                    }
                    if(map1.size()==K)
                        sum++; 
                    m++;
                }
                j++;
                addFlag=0;
            }else{
                map.put(A[i],map.get(A[i])-1);
                if(map.containsKey(A[i])&&map.get(A[i])==0){
                    map.remove(A[i]);
                    flag--;
                }
                i++;
                addFlag=1;
            }
        }
        return sum;
    }
}

学习待续

拓展问题

posted @ 2020-02-07 15:58  clnsx  阅读(132)  评论(0编辑  收藏  举报