Shortest subarray containing all elements without using arrays?

删除回忆录丶 提交于 2019-12-24 03:19:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!