mercredi 7 août 2019

Number of occurrence of each element in less than n^2

I'm given two arrays a[n], b[n], where n can be 10^5

Initially answer array is of size n with all zeroes.

The task is to take a[i], b[i] as interval for answer[i] and increment values between it by 1.

Example:

         a[n] = {1,1,1,1,1};
         b[n] = {3,3,5,5,5};

so answer [n] = {5, 5, 5, 3, 3}

b[i] is always greater than a[i]

I have done this using bruteforce in n^2

int i=0;
int ans[n];
while(i<n){
  for(int j=a[i]; j<=b[i]; j++){
    ans[j]++;
  }
  i++;
}

Is there any better way to solve this in linear time.

Aucun commentaire:

Enregistrer un commentaire