通过连接另一个数组的子数组得到一个数组【LC1764】
You are given a 2D integer array
groupsof lengthn. You are also given an integer arraynums.You are asked if you can choose
ndisjoint subarrays from the arraynumssuch that theithsubarray is equal togroups[i](0-indexed), and ifi > 0, the(i-1)thsubarray appears before theithsubarray innums(i.e. the subarrays must be in the same order asgroups).Return
trueif you can do this task, andfalseotherwise.Note that the subarrays are disjoint if and only if there is no index
ksuch thatnums[k]belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.
给你一个长度为
n的二维整数数组groups,同时给你一个整数数组nums。你是否可以从
nums中选出n个 不相交 的子数组,使得第i个子数组与groups[i](下标从 0 开始)完全相同,且如果i > 0,那么第(i-1)个子数组在nums中出现的位置在第i个子数组前面。(也就是说,这些子数组在nums中出现的顺序需要与groups顺序相同)如果你可以找出这样的
n个子数组,请你返回true,否则返回false。如果不存在下标为
k的元素nums[k]属于不止一个子数组,就称这些子数组是 不相交 的。子数组指的是原数组中连续元素组成的一个序列。
这代码是真的丑啊
我滴乖乖 忘记发布了
-
思路:
- 使用指针定位数组
groups和nums中的元素,指针iii定位groups中的某一数组,指针jjj定位groups中数组的某一元素,指针kkk定位nums中数组的某一元素。 - 从前往后进行匹配,当某一位置匹配不成功时,将
nums数组的指针kkk移动到groups[i]首字符的下一位置、groups数组的指针jjj移动到首字符位置重新匹配,若最后groups中所有子数组均找到对应的子数组,那么返回true
- 使用指针定位数组
-
实现
class Solution { public boolean canChoose(int[][] groups, int[] nums) { int i = 0, j = 0, k = 0; while (i < groups.length && k < nums.length){ if (groups[i][j] == nums[k]){ j++; k++; if (j == groups[i].length){ i++; j = 0; } }else if (j != 0){ k = k - j + 1; j = 0; }else{ k++; } } return i == groups.length; } }- 复杂度
- 时间复杂度:O(n∗m)O(n*m)O(n∗m),nnn为numsnumsnums长度,mmm为group[i]group[i]group[i]的最大长度
- 空间复杂度:O(1)O(1)O(1)
- 复杂度

775

被折叠的 条评论
为什么被折叠?



