Number of occurences of each term

后端 未结 1 1881
-上瘾入骨i
-上瘾入骨i 2021-01-29 03:22

I\'m given an array a[n][2], where n can be 10^5 at max. There are n subjects and n students. All numbered 1, 2, ..., n.

a[i

1条回答
  •  抹茶落季
    2021-01-29 04:07

    Didn't quite understand your code, here is an alternative approach. This is similar to an interval problem. Let's take your example:

    • n = 5
    • a = [ [1,3], [1,3], [1,5], [1,5], [1,5] ]

    We first make an array of size as no. of subjects + 1 (for the sake of simplicity in computation).

    1   2   3   4   5   6
    
    • Now, let's go through intervals one by one. Whenever we come across an interval, we add +1 to the starting point and -1 to the ending point + 1th location.

    Array representation:(after the entire above process).

     1          2          3          4         5         6
    
    +1                               -1                           [1,3]
    +1                               -1                           [1,3]
    +1                                                   -1       [1,5]
    +1                                                   -1       [1,5]
    +1                                                   -1       [1,5]
    
    • All is pending is to just start summing from left to right and you get your answers for each student. The above process works because we negate( as in do a -1) the addition after the last student for each interval since the further students didn't pass that particular subject. So, while summing, we are bound to get the right total for each student.

    Summing looks like:

     1          2          3          4         5         6
    
    +1                               -1                           [1,3]
    +1                               -1                           [1,3]
    +1                                                   -1       [1,5]
    +1                                                   -1       [1,5]
    +1                                                   -1       [1,5]
    
     5          5          5          3         3         0(not considered anyway) 
    

    0 讨论(0)
提交回复
热议问题