Advertisement
theSwamz

NumberItemsContainers(O(M+N))

Apr 24th, 2021
1,310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.15 KB | None | 0 0
  1. I think that question could be solved in O(m + n).
  2.  
  3. public List<Integer> itemCount(String s, List<Integer> start, List<Integer> end) {
  4.         List<Integer> result = new ArrayList<>();
  5.         int sum, currentSum, len, index;
  6.         len = s.length();
  7.         int count[] = new int[len];
  8.         int left[] = new int[len];
  9.         int right[] = new int[len];
  10.         sum = currentSum = 0;
  11.         boolean begin = false;
  12.        
  13.         for(int i = 0; i < len; i++) {
  14.             if(s.charAt(i) == '|') {
  15.                 if(begin) {
  16.                     sum += currentSum;
  17.                     count[i] = sum;
  18.                 }
  19.                 currentSum = 0;
  20.                 begin = true;
  21.             } else {
  22.                 currentSum++;
  23.             }
  24.         }
  25.        
  26.         index = -1;
  27.         for(int i = 0; i < len; i++) {
  28.             if(s.charAt(i) == '|') {
  29.                 index = i;
  30.             }
  31.             left[i] = index;
  32.         }
  33.        
  34.         index = len;
  35.         for(int i = len - 1; i >= 0; i--) {
  36.             if(s.charAt(i) == '|') {
  37.                 index = i;
  38.             }
  39.             right[i] = index;
  40.         }
  41.         int rBoundary, lBoundary;
  42.         for(int i = 0; i < start.size(); i++) {
  43.             lBoundary = right[start.get(i) - 1];
  44.             rBoundary = left[end.get(i) - 1];
  45.             if(lBoundary < rBoundary) {
  46.                 result.add(count[rBoundary] - count[lBoundary]);
  47.             } else {
  48.                 result.add(0);
  49.             }
  50.         }
  51.         return result;
  52.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement