问题
Problem: Find the length of the shortest subarray that contains all elements Example : 1 2 2 3 2 2 1 3 Answer : 3
I have read that the best approach to this problem is by using the sliding window approach. But this approach requires using arrays. Is there any other efficient approach that does not require to use arrays by storing the number of appearances of each element? ( I would like to use this approach without arrays by writing it in ML )
回答1:
I assume that the reason you want to avoid an array is that you want to write idiomatic ML code, and so would prefer to use a purely functional data structure rather than a mutable array?
If so, then you can use a purely functional red-black tree for the "sliding-window" approach in almost exactly the same way as you would use an array; the only differences are:
- Instead of O(1) lookups, you have O(log m) lookups, where m is the number of distinct elements.
- Instead of O(1) mutations, you have O(log m) transformations, where a transformation returns a modified copy of the map (sharing most of its nodes).
回答2:
I don't understand your problem with arrays. You don't specify which ML-family language you are using but Ocaml (my favorite one) certainly has arrays. If you really don't like arrays for some religious reason, you can always use a Map with integer keys which does the same thing as an array but a lot slower.
来源:https://stackoverflow.com/questions/55379954/shortest-subarray-containing-all-elements-without-using-arrays