First Missing Positive
41. First Missing Positive
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0] Output: 3
Example 2:
Input: [3,4,-1,1] Output: 2
Example 3:
Input: [7,8,9,11,12] Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
解题思路:
第一步:将数组中大于0的整数做一个hash映射,同时获取最大值ARRMAX。
第二步:从1到ARRMAX遍历hash表,找到第一个为0的终止,返回最后查找索引值即可。
1 #define HASHNUM 100000 2 3 int firstMissingPositive(int* nums, int numsSize) 4 { 5 int numsMax = 0; 6 int hash[HASHNUM] = {0}; 7 // hash and seek for array max num. 8 for(int idx = 0; idx < numsSize; ++idx) 9 { 10 if(nums[idx] <= 0 ) continue; 11 else 12 { 13 hash[nums[idx]] = 1; 14 if(numsMax < nums[idx]) 15 { 16 numsMax = nums[idx]; 17 } 18 } 19 } 20 21 // judge for missing 22 int retIdx = 1; 23 for(retIdx = 1; retIdx <= numsMax; ++retIdx) 24 { 25 if(hash[retIdx] == 0) 26 { 27 break; 28 } 29 } 30 31 return retIdx; 32 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2016-05-20 Debian8 系统修改语言设置成英文