Longest subarray whose elements form a continuous sequence

后端 未结 7 855
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 05:52

Given an unsorted array of positive integers, find the length of the longest subarray whose elements when sorted are continuous. Can you think of an O(n) solution?

Examp

7条回答
  •  温柔的废话
    2021-01-31 06:18

    here's another way to think of your problem: suppose you have an array composed only of 1s and 0s, you want to find the longest consecutive run of 1s. this can be done in linear time by run-length encoding the 1s (ignore the 0's). in order to transform your original problem into this new run length encoding problem, you compute a new array b[i] = (a[i] < a[i+1]). this doesn't have to be done explicitly, you can just do it implicitly to achieve an algorithm with constant memory requirement and linear complexity.

提交回复
热议问题