3643 数组是否为连贯数组

题目描述

如果数组包含[x, x+n-1]范围内的所有数字(包括x和x+n-1),则称该数组为连贯数组。其中x是数组中最小的数,n是数组的长度。

现给你一个整数数组nums,如果nums是一个连贯数组,则返回true,否则返回false。

思路

创建一个长度为数组两倍的bool数组。从数组的第二个元素开始,计算该元素与第一个元素的差,用这个差作为index去设置bool数组对应的值为true。同时记录数组中最小的值,作为bool数组的起始index。这样只需要两次遍历即可。时间复杂度为O(n)。

C++代码

class Solution {
public:
    /**
     * @param nums: An integer array.
     * @return: Whether the array is consecutive.
     */
    bool isConsecutive(vector<int> &nums) {
        // --- write your code here ---
        const int numsLen = nums.size();

        if (numsLen == 1) {
            return true;
        } else {
            const int len = 2 * numsLen;
            std::vector<bool> tempVec(len, false);
            int minValue = nums[0];
            tempVec[numsLen] = true;
            
            for (int i = 1; i < numsLen; ++i) {
                if (nums[i] < minValue) {
                    minValue = nums[i];
                }

                int step = numsLen + nums[i] - nums[0];
                if (step < 0 || step > len) {
                    return false;
                } else {
                    tempVec[step] = true;
                }
            }
            
            int begin = numsLen - nums[0] + minValue;
            int end = begin + numsLen;

            for (int i = begin; i < end; ++i) {
                if (!tempVec[i]) {
                    return false;
                }
            }

            return true;
        }
    }
};

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值