题解 | #牧场奶牛集合区域# 数组模拟
牧场奶牛集合区域
https://www.nowcoder.com/practice/89218acf98234315af1cb3a223935318
知识点
模拟
思路
要统计有序数组中的线段,可以从左到右模拟,维护一个当前线段的起始位置,当不满足当前一对元素的差值为1的时候将当前元素加入答案,然后更新下一组线段的起始位置。
时间复杂度
只遍历一遍数组,时间复杂度为
AC code(C++)
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param groups int整型vector
* @param n int整型
* @return int整型vector<vector<>>
*/
vector<vector<int> > findGatheringAreas(vector<int>& groups, int n) {
vector<vector<int>> res;
int last = groups[0];
for (int i = 1; i < n; i ++) {
if (groups[i] - groups[i - 1] == 1) continue;
res.push_back({last, groups[i - 1]});
last = groups[i];
}
res.push_back({last, groups[n - 1]});
return res;
}
};

查看4道真题和解析