3355. Zero Array Transformation I

T: O(nlogn)

S: O(n)


class Solution {
    public boolean isZeroArray(int[] nums, int[][] queries) {
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int[] q : queries) {
            int start = q[0];
            int end = q[1] + 1;
            map.put(start, map.getOrDefault(start, 0)+1);
            map.put(end, map.getOrDefault(end, 0)-1);
        }
        int cur = 0;
        for (int key : map.keySet()) { // 0: 1 , 3: 0
            int value = map.get(key);
            cur += value;
            map.put(key, cur);
        }

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                continue;
            }
            Integer floorKey = map.floorKey(i);
            //System.out.println(floorKey + ", v=" + map.get(floorKey));
            if (floorKey == null || map.get(floorKey) < nums[i]) {
                return false;
            }
        }
        return true;
    }
}

/***

  1 2 3
0 1 2

-1 -2 -2 -1

1 0 1
1 1 1

  1.  3 4
0.  2 
+
  +   - -

1 2 2 1 0


[0,2]
0.  3
1.  0  
 */

because the traget is limited, so can use bucket sort

T: O(n+q)

S: O(n)

Last updated

Was this helpful?