Longest subarray whose elements form a continuous sequence

后端 未结 7 856
没有蜡笔的小新
没有蜡笔的小新 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:22

    Here are 3 acceptable solutions:

    The first is O(nlog(n)) in time and O(n) space, the second is O(n) in time and O(n) in space, and the third is O(n) in time and O(1) in space.

    1. build a binary search tree then traverse it in order.
      keep 2 pointers one for the start of max subset and one for the end. keep the max_size value while iterating the tree. it is a O(n*log(n)) time and space complexity.

    2. you can always sort numbers set using counting sort in a linear time and run through the array, which means O(n) time and space complexity.

    3. Assuming there isn't overflow or a big integer data type. Assuming the array is a mathematical set (no duplicate values). You can do it in O(1) of memory:

      • calculate the sum of the array and the product of the array
      • figure out what numbers you have in it assuming you have the min and max of the original set. Totally it is O(n) time complexity.

提交回复
热议问题