相关信息:
LeetCode链接:
https://leetcode-cn.com/problems/shortest-supersequence-lcci/
代码:
//作者:LeetCode-Solution
import java.util.HashMap;
import java.util.Map;
public class LF17_18 {
public static void main(String[] args) {
//Test
SolutionLF17_18 solutionLF17_18 = new SolutionLF17_18();
int[] big = {7, 5, 9, 0, 2, 1, 3, 5, 7, 9, 1, 1, 5, 8, 8, 9, 7};
int[] small = {1, 5, 9};
int[] ans = solutionLF17_18.shortestSeq(big, small);
System.out.println(ans);
}
}
class SolutionLF17_18 {
public int[] shortestSeq(int[] big, int[] small) {
/*default size of the shortest window
* big.length + 1 :It can detect whether the big array has all the values of the small array, and it conforms to human logic
* */
int minLength = big.length + 1;
// array and hash table record matching situation
/*the map maps the elements in the small array to consecutive values starting with 0
* for example small={1,5,9}in the format of [key,value],{[0,1],[1.5],[2,9]}
* */
Map<Integer, Integer> map = new HashMap<>();
/*record the number of small array elements in the window
* Record in the form of changing count [map.get(small element)]
* */
int[] count = new int[small.length];
//Corresponding the elements in the small array to consecutive values starting with 0
for (int i = 0; i < small.length; i++) {
map.put(small[i], i);
}
// window left and right boundary
int left = 0, right = 0;
// Use find to record whether the number of matches contains the elements of the small array
int find = 0;
/*
* rea[0] record maximum left boundary
* res[1] record minimum right boundary
* rea[0] < rea[1]
* */
int[] res = new int[2];
// extended right boundary
while (right < big.length) {
int rightNum = big[right];
//find the element in the small array
if (map.containsKey(rightNum)) {
count[map.get(rightNum)]++;
//when the element in small is found for the first time
if (count[map.get(rightNum)] == 1) {
find++;
}
}
// shrink left border
while (find == small.length) {
//update res
if (right - left + 1 < minLength) {
res[0] = left;
res[1] = right;
minLength = right - left + 1;
}
int leftNum = big[left];
if (map.containsKey(leftNum)) {
count[map.get(leftNum)]--;
if (count[map.get(leftNum)] == 0) {
find--;
}
}
left++;
}
right++;
}
return minLength <= big.length ? res : new int[0];
}
}