返回介绍

solution / 2700-2799 / 2762.Continuous Subarrays / README_EN

发布于 2024-06-17 01:03:00 字数 5060 浏览 0 评论 0 收藏 0

2762. Continuous Subarrays

中文文档

Description

You are given a 0-indexed integer array nums. A subarray of nums is called continuous if:

  • Let i, i + 1, ..., j be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j, 0 <= |nums[i1] - nums[i2]| <= 2.

Return _the total number of continuous subarrays._

A subarray is a contiguous non-empty sequence of elements within an array.

 

Example 1:

Input: nums = [5,4,2,4]
Output: 8
Explanation: 
Continuous subarray of size 1: [5], [4], [2], [4].
Continuous subarray of size 2: [5,4], [4,2], [2,4].
Continuous subarray of size 3: [4,2,4].
Thereare no subarrys of size 4.
Total continuous subarrays = 4 + 3 + 1 = 8.
It can be shown that there are no more continuous subarrays.

 

Example 2:

Input: nums = [1,2,3]
Output: 6
Explanation: 
Continuous subarray of size 1: [1], [2], [3].
Continuous subarray of size 2: [1,2], [2,3].
Continuous subarray of size 3: [1,2,3].
Total continuous subarrays = 3 + 2 + 1 = 6.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109

Solutions

Solution 1: Ordered List + Two Pointers

We can use two pointers, $i$ and $j$, to maintain the left and right endpoints of the current subarray, and use an ordered list to maintain all elements in the current subarray.

Iterate through the array $nums$. For the current number $nums[i]$ we're iterating over, we add it to the ordered list. If the difference between the maximum and minimum values in the ordered list is greater than $2$, we then loop to move the pointer $i$ to the right, continuously removing $nums[i]$ from the ordered list, until the list is empty or the maximum difference between elements in the ordered list is not greater than $2$. At this point, the number of uninterrupted subarrays is $j - i + 1$, which we add to the answer.

After the iteration, return the answer.

The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $nums$.

from sortedcontainers import SortedList


class Solution:
  def continuousSubarrays(self, nums: List[int]) -> int:
    ans = i = 0
    sl = SortedList()
    for x in nums:
      sl.add(x)
      while sl[-1] - sl[0] > 2:
        sl.remove(nums[i])
        i += 1
      ans += len(sl)
    return ans
class Solution {
  public long continuousSubarrays(int[] nums) {
    long ans = 0;
    int i = 0, n = nums.length;
    TreeMap<Integer, Integer> tm = new TreeMap<>();
    for (int j = 0; j < n; ++j) {
      tm.merge(nums[j], 1, Integer::sum);
      while (tm.lastEntry().getKey() - tm.firstEntry().getKey() > 2) {
        tm.merge(nums[i], -1, Integer::sum);
        if (tm.get(nums[i]) == 0) {
          tm.remove(nums[i]);
        }
        ++i;
      }
      ans += j - i + 1;
    }
    return ans;
  }
}
class Solution {
public:
  long long continuousSubarrays(vector<int>& nums) {
    long long ans = 0;
    int i = 0, n = nums.size();
    multiset<int> s;
    for (int j = 0; j < n; ++j) {
      s.insert(nums[j]);
      while (*s.rbegin() - *s.begin() > 2) {
        s.erase(s.find(nums[i++]));
      }
      ans += j - i + 1;
    }
    return ans;
  }
};
func continuousSubarrays(nums []int) (ans int64) {
  i := 0
  tm := treemap.NewWithIntComparator()
  for j, x := range nums {
    if v, ok := tm.Get(x); ok {
      tm.Put(x, v.(int)+1)
    } else {
      tm.Put(x, 1)
    }
    for {
      a, _ := tm.Min()
      b, _ := tm.Max()
      if b.(int)-a.(int) > 2 {
        if v, _ := tm.Get(nums[i]); v.(int) == 1 {
          tm.Remove(nums[i])
        } else {
          tm.Put(nums[i], v.(int)-1)
        }
        i++
      } else {
        break
      }
    }
    ans += int64(j - i + 1)
  }
  return
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文