假设你有两个数组,一个长一个短,短的元素均不相同。找到长数组中包含短数组所有的元素的最短子数组,其出现顺序无关紧要。
返回最短子数组的左端点和右端点,如有多个满足条件的子数组,返回左端点最小的一个。若不存在,返回空数组。
示例 1:
输入:
big = [7,5,9,0,2,1,3,5,7,9,1,1,5,8,8,9,7]
small = [1,5,9]
输出: [7,10]
示例 2:
输入:
big = [1,2,3]
small = [4]
输出: []
java代码:
class Solution {
public int[] shortestSeq(int[] big, int[] small) {
if(big==null || big.length==0) return new int[0];
HashSet<Integer> smallSet = new HashSet<Integer>();
for(int i=0;i<small.length;i++)smallSet.add(small[i]);
HashMap<Integer, Integer> startMap = new HashMap<Integer, Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0;i<big.length;i++)if(smallSet.contains(big[i])){startMap.put(big[i], i);list.add(i);}
if(list.isEmpty()) return new int[0];
int startEnd = -1;
for(Integer value:startMap.values())if(startEnd == -1 || value<startEnd)startEnd = value;
int start = 0,end = 0,length = -1;
for(int i=0;i<list.size() && list.get(i)<=startEnd;i++){
HashSet<Integer> tempSet = new HashSet<Integer>();
for(int j=i;j<list.size();j++){
int value = big[list.get(j)];
if(!tempSet.contains(value))tempSet.add(value);
if(tempSet.size()==small.length){
if(length == -1 || list.get(j)-list.get(i)<length){
start = list.get(i);end = list.get(j);length = list.get(j)-list.get(i);
}
break;
}
}
if(length==-1) return new int[0];
}
return new int[]{start, end};
}
}