题解 | #牧场奶牛集合区域#
牧场奶牛集合区域
https://www.nowcoder.com/practice/89218acf98234315af1cb3a223935318
思路:一开始没有考虑双指针,直接莽其实也可以出结果。
- 遍历数组,不断存入左右边界
- 左边界好说,只要之前没有就直接放入
- 右边界需要判断(是否连续)
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param groups int整型vector
* @param n int整型
* @return int整型vector<vector<>>
*/
vector<vector<int> > findGatheringAreas(vector<int>& groups, int n) {
// 分割为连续整数区间,求所有编号的最小有序区间范围列表。
// 无重复元素的有序整数数组groups
vector<vector<int>> res;
bool first = false;
bool second = false;
vector<int> temp(2);
// 将第一个左边界
temp[0] = groups[0];
first = true;
for(int i=1;i<n;++i){
// 如果左边界没有,就放入
if(!first){
temp[0] = groups[i];
first=true;
// 放入右边界的值需要判断
}else{
// 如果差是1
if(groups[i]-groups[i-1]==1){
temp[1] = groups[i];
second=true;
// 如果差不是1
}else{
// 放入结果中
if(second){
res.push_back(temp);
}else{
// 注意这里可能存在单个数的
temp[1] = temp[0];
res.push_back(temp);
}
// 新的结果
temp[0] = groups[i];
first=true;
second = false;
}
}
}
if(first && second){
res.push_back(temp);
}else if(first){
temp[1] = temp[0];
res.push_back(temp);
}
return res;
}
};
SHEIN希音公司福利 248人发布