题解 | #牧场奶牛集合区域#
牧场奶牛集合区域
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; } int[][] res = new int[list.size()][2]; for(int i = 0; i < list.size(); i++) { res[i] = list.get(i); } return res; } }