【每日一题Day59】LC1764通过连接另一个数组的子数组得到一个数组 | 双指针模拟

通过连接另一个数组的子数组得到一个数组【LC1764】

You are given a 2D integer array groups of length n. You are also given an integer array nums.

You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups).

Return true if you can do this task, and false otherwise.

Note that the subarrays are disjoint if and only if there is no index k such that nums[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] 属于不止一个子数组,就称这些子数组是 不相交 的。子数组指的是原数组中连续元素组成的一个序列。

这代码是真的丑啊
我滴乖乖 忘记发布了

  • 思路:

    • 使用指针定位数组groupsnums中的元素,指针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(nm),nnnnumsnumsnums长度,mmmgroup[i]group[i]group[i]的最大长度
      • 空间复杂度:O(1)O(1)O(1)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值