题解 | #牧场奶牛集合区域#

牧场奶牛集合区域

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

考察数组的操作,双指针遍历数组

对于题目,直接用快慢指针进行操作就可以了,因为已经升序排列了,所以直接进行题目的模拟,当连续的时候就不断移动右指针,不连续的时候将这段区间加入即可,然后更新左指针。

完整Java代码如下所示

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param groups int整型一维数组 
     * @param n int整型 
     * @return int整型二维数组
     */
    public int[][] findGatheringAreas (int[] groups, int n) {
        // write code here
        List<int[]> list = new ArrayList<>();
        int left = 0, right = 0;
        while(left < n) {
            while(right + 1 < n && groups[right] + 1 == groups[right + 1]) { //区间连续的时候
                right++;
            }
            list.add(new int[]{groups[left], groups[right]});
            left = right + 1;
            right = left;
        }
        return list.toArray(new int[list.size()][2]);
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 15:08
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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