作者:小迅
链接:https://leetcode.cn/problems/form-array-by-concatenating-subarrays-of-another-array/solutions/2023883/mo-ni-zhu-shi-chao-ji-xiang-xi-by-xun-ge-y4ft/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目
示例
思路
题意 -> 在 nums 数组中寻找 n 个子数组,其中nums中的元素不可重复,使得子数组与 groups 中的子数组相同并且顺序也一样
直接使用双指针模拟,枚举数组nums中的每一个位置,与 groups 中的子数组进行对比,最后当groups中子数组都匹配成功则返回true,否则 false。
代码
bool check(const int *g, int gSize, const int *nums, int numsSize, int k) {//判断子数组是否相同
if (k + gSize > numsSize) {
return false;
}
for (int j = 0; j < gSize; j++) {
if (g[j] != nums[k + j]) {
return false;
}
}
return true;
}
bool canChoose(int** groups, int groupsSize, int* groupsColSize, int* nums, int numsSize) {
int i = 0;
for (int k = 0; k < numsSize && i < groupsSize;) {//枚举nums中的每一个元素
if (check(groups[i], groupsColSize[i], nums, numsSize, k)) {//判断子数组是否相同
k += groupsColSize[i];//相同,改变位置
i++;
} else {
k++;//当前位置接下来的子数组不能满足要求,下一个位置
}
}
return i == groupsSize;
}
作者:小迅
链接:https://leetcode.cn/problems/form-array-by-concatenating-subarrays-of-another-array/solutions/2023883/mo-ni-zhu-shi-chao-ji-xiang-xi-by-xun-ge-y4ft/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。