题目链接:
缺失的第一个正整数_牛客题霸_牛客网 (nowcoder.com)
题目简介:
描述
给定一个无重复元素的整数数组nums,请你找出其中没有出现的最小的正整数
进阶: 空间复杂度 O(1),时间复杂度 O(n)
数据范围:
−2^31≤nums[i]≤2^31−1
0≤len(nums)≤5∗10^5
题目解法:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <memory.h>
#define NUMLEN(c) (sizeof(c)/sizeof(c[0]))
/*
*BM53 缺失的第一个正整数
描述
给定一个无重复元素的整数数组nums,请你找出其中没有出现的最小的正整数
进阶: 空间复杂度 O(1) ,时间复杂度 O(n)
数据范围:
-2^{31} ≤ nums[i] ≤ 2^{31}-1 int
0≤ len(nums)≤5*10^5
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @param numsLen int nums数组长度
* @return int整型
*/
int minNumberDisappeared(int* nums, int numsLen ) {
// write code here
int* hash = (int*)calloc(500001, sizeof(int));
memset(hash, 0, 500001*sizeof(int));
for(int i=0; i<numsLen; i++){
if(nums[i] >= 0) //对于正整数,赋值hash对应表项
hash[nums[i]] = 1;
}
for(int i=1; i<500001; i++){ //从1开始遍历hash表,找出最小未出现的正整数
if(hash[i] == 0){
free(hash);
return i;
}
}
free(hash);
return NULL;
}
/**************************end******************************************/
int main ()
{
// int nums1[] = {1,0,2};
int nums1[] = {4,5,6,8,9};
int numbersLen = NUMLEN(nums1);
int ret = minNumberDisappeared(nums1, numbersLen);
printf("\r\n ret: %d ", ret);
return 0;
}