Leetcode-2229
题目2229.Check if an Array Is Consecutive
难度:简单
Given an integer array nums, return true if nums is consecutive, otherwise return false.
An array is consecutive if it contains every number in the range [x, x + n - 1] (inclusive), where x is the minimum number in the array and n is the length of the array.
Example 1:
Input: nums = [1,3,4,2]
Output: true
Explanation:
The minimum value is 1 and the length of nums is 4.
All of the values in the range [x, x + n - 1] = [1, 1 + 4 - 1] = [1, 4] = (1, 2, 3, 4) occur in nums.
Therefore, nums is consecutive.
Example 2:
Input: nums = [1,3]
Output: false
Explanation:
The minimum value is 1 and the length of nums is 2.
The value 2 in the range [x, x + n - 1] = [1, 1 + 2 - 1], = [1, 2] = (1, 2) does not occur in nums.
Therefore, nums is not consecutive.
Example 3:
Input: nums = [3,5,4]
Output: true
Explanation:
The minimum value is 3 and the length of nums is 3.
All of the values in the range [x, x + n - 1] = [3, 3 + 3 - 1] = [3, 5] = (3, 4, 5) occur in nums.
Therefore, nums is consecutive.
Constraints:
- 1 <= nums.length <= 105
- 0 <= nums[i] <= 105
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-if-an-array-is-consecutive/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
排序,新建a,判断是否在nums中
扩展思考: a所有元素(可能重复/不重复)是否在b中
解题代码
class Solution
{
public:
bool isConsecutive(vector<int> &nums)
{
// if(nums == nullptr) return;
int n = nums.size();
// size
sort(nums.begin(), nums.end());
int min = nums[0];
//最小值
vector<int> vec;
for (int i = min; i <= n + min - 1; i++)
{
vec.push_back(i);
}
int i = 0;
while (i < vec.size())
{
if (vec[i] == nums[i])
i++;
else
return false;
}
return true;
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话