题解 | 牧场奶牛集合区域
牧场奶牛集合区域
https://www.nowcoder.com/practice/89218acf98234315af1cb3a223935318
- 注意 L19 L20 即可。
import java.util.*;
public class Solution {
public int[][] findGatheringAreas (int[] groups, int n) {
if (n == 0) {
return new int[0][0];
}
List<Integer> tmp = new ArrayList<>();
Arrays.sort(groups);
int l = 0;
for (int r = 1; r < n; ++r) {
if (groups[r] != groups[r - 1] + 1) {
tmp.add(groups[l]);
tmp.add(groups[r - 1]);
l = r;
}
}
tmp.add(groups[l]);
tmp.add(groups[n - 1]);
final int m = tmp.size() / 2;
int[][] ans = new int[m][2];
for (int i = 0; i < m; i += 1) {
ans[i][0] = tmp.get(2 * i);
ans[i][1] = tmp.get(2 * i + 1);
}
return ans;
}
}

查看23道真题和解析