Find shortest subarray containing all elements

后端 未结 6 657
执念已碎
执念已碎 2020-12-13 04:42

Suppose you have an array of numbers, and another set of numbers. You have to find the shortest subarray containing all numbers with minimal complexity.

The array ca

6条回答
  •  情歌与酒
    2020-12-13 05:34

    Java solution

        List paragraph = Arrays.asList("a", "c", "d", "m", "b", "a");
        Set keywords = Arrays.asList("a","b");
    
        Subarray result = new Subarray(-1,-1);
    
        Map keyWordFreq = new HashMap<>();
    
        int numKeywords = keywords.size();
    
        // slide the window to contain the all the keywords**
        // starting with [0,0]
        for (int left = 0, right = 0 ; right < paragraph.size() ; right++){
    
          // expand right to contain all the keywords
          String currRight = paragraph.get(right);
    
          if (keywords.contains(currRight)){
            keyWordFreq.put(currRight, keyWordFreq.get(currRight) == null ? 1 : keyWordFreq.get(currRight) + 1);
          }
    
          // loop enters when all the keywords are present in the current window
          // contract left until the all the keywords are still present
          while (keyWordFreq.size() == numKeywords){
            String currLeft = paragraph.get(left);
    
            if (keywords.contains(currLeft)){
    
              // remove from the map if its the last available so that loop exists
              if (keyWordFreq.get(currLeft).equals(1)){
    
                // now check if current sub array is the smallest
                if((result.start == -1 && result.end == -1) || (right - left) < (result.end - result.start)){
                  result = new Subarray(left, right);
                }
                keyWordFreq.remove(currLeft);
              }else {
    
                // else reduce the frequcency
                keyWordFreq.put(currLeft, keyWordFreq.get(currLeft) - 1);
              }
            }
            left++;
          }
    
        }
    
        return result;
      }
    

提交回复
热议问题