leetcode1562 查找大小为 M 的最新分组

思路:

通过维护区间的左右端点来实现快速区间合并。类似的题目有https://leetcode-cn.com/problems/longest-consecutive-sequence/,不过此题更加简单,需要考虑的情况更少。

实现:

 1 class Solution
 2 {
 3 public:
 4     int findLatestStep(vector<int>& arr, int m)
 5     {
 6         int n = arr.size();
 7         vector<int> link(n + 2, -1);
 8         int cnt = 0, res = -1;
 9         for (int i = 0; i < n; i++)
10         {
11             int x = arr[i], l = x - 1, r = x + 1;
12             int L = x, R = x;
13             if (link[l] != -1) L = link[l];
14             if (link[r] != -1) R = link[r];
15             if (l - L + 1 == m) cnt--;
16             if (R - r + 1 == m) cnt--;
17             if (R - L + 1 == m) cnt++;
18             link[L] = R; link[R] = L;
19             if (cnt > 0) res = i + 1;
20         }
21         return res;
22     }
23 };