Frequency of each element of an array considering all contiguos subarrays

前端 未结 4 2030
别跟我提以往
别跟我提以往 2020-12-17 04:14

Consider an array A = [5,1,7,2,3]

All contiguos subarrays = { [5], [1], [7], [2], [3], [5,1], [1,7], [7,2], [2,3], [5,1,7], [1,7,2], [7,2,3], [5,1,7,2], [1,7,2,3],

4条回答
  •  忘掉有多难
    2020-12-17 05:04

    I doubt your code runs in O(n^2). Anyways, one way to solve this in a more efficient way would be to map each number to the number of items to the left/right which are smaller than the given item. For example:

    input = [2 , 3 , 1 , 5 , 4 , 8 , 0]
    for number n = 5
    leftctsmaller(n) = 3
    rightctsmaller(n) = 1
    

    This map will require O(n^2) to generate. The rest is straightforward. Given the space to the left and to the right, we can easily determine the number of subarrays that only contains smaller numbers than n, except for n itself.

提交回复
热议问题