题解 | #牧场奶牛集合区域# 数组模拟

牧场奶牛集合区域

https://www.nowcoder.com/practice/89218acf98234315af1cb3a223935318

知识点

模拟

思路

要统计有序数组中的线段,可以从左到右模拟,维护一个当前线段的起始位置,当不满足当前一对元素的差值为1的时候将当前元素加入答案,然后更新下一组线段的起始位置。

时间复杂度

只遍历一遍数组,时间复杂度为O(n)

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;
    }
};

全部评论

相关推荐

Lorn的意义:1.你这根本就不会写简历呀,了解太少了 2.你这些项目经历感觉真的没啥亮点啊,描述的不行,重写书写一下让人看到核心,就继续海投 注意七八月份ofer还是比较多的,越往后机会越少,抓住时机,抓紧检查疏漏,加油查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务