Leetcode Problem 2762. Continuous Subarrays

2762. Continuous Subarrays

Leetcode Solutions

Sliding Window with TreeMap

  1. Initialize a TreeMap to store the frequency of numbers in the current window.
  2. Initialize two pointers i and j to represent the window's left and right ends, respectively.
  3. Initialize a variable ans to store the total count of continuous subarrays.
  4. Iterate through the array with the right pointer i. a. Add nums[i] to the TreeMap and increment its frequency. b. While the difference between the smallest and largest keys in the TreeMap is greater than 2, increment the left pointer j and update the TreeMap. c. Add the length of the current window (i - j + 1) to ans.
  5. Return ans as the total count of continuous subarrays.
UML Thumbnail

Two Pointers with Frequency Map

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...