【leetcode】Array——First Missing Positive(41)
2016-03-19 21:24
477 查看
题目:
Given an unsorted integer array, find the first missing positive integer.
For example,
Given
and
Your algorithm should run in O(n) time and uses constant space.
思路1:Bit Manipulation 受之前一道题目的启发Contains Duplicate(217)
用一个byte数组作为标记位,每个byte可以标记8个数字。遍历nums,并标记出现的正整数,然后从低位开始判断,第一个缺少的正整数。
同样这种方法存在缺陷就是byte数组的长度:按理应该是(2^32)/8
代码1:
思路2:从leetcode上看到的。把读取到的正整数放到对应的位置
【3,4,-1,1】=>【1,-1,3,4】 然后找到第一个不对应的元素即可。
见leetcode链接:https://leetcode.com/discuss/24013/my-short-c-solution-o-1-space-and-o-n-time
代码2:
Given an unsorted integer array, find the first missing positive integer.
For example,
Given
[1,2,0]return
3,
and
[3,4,-1,1]return
2.
Your algorithm should run in O(n) time and uses constant space.
思路1:Bit Manipulation 受之前一道题目的启发Contains Duplicate(217)
用一个byte数组作为标记位,每个byte可以标记8个数字。遍历nums,并标记出现的正整数,然后从低位开始判断,第一个缺少的正整数。
同样这种方法存在缺陷就是byte数组的长度:按理应该是(2^32)/8
代码1:
public int firstMissingPositive(int[] nums) { byte[] mark = new byte[150000]; mark[0]|=1;//set 0 mark,方便后续分析 for(int i : nums){ if(i>0){ int byteBlock = i/8;//确定i在第几个byte里面 int byteIndex = i%8;//确定i在byte中具体的位置 mark[byteBlock]|=1<<byteIndex;//把i在byte[]中的标记位设置1 } } for(int i=0;i<mark.length;i++){ if(mark[i]!=255){ //如果为255,说明btye中标记位全部为1,如果不是255,说明存在0 for(int j=0;j<=7;j++){ if(mark[i]!=(mark[i]|(1<<j))){//找到具体的低位的0 return (j+8*i); } } } } return -1; }
思路2:从leetcode上看到的。把读取到的正整数放到对应的位置
【3,4,-1,1】=>【1,-1,3,4】 然后找到第一个不对应的元素即可。
见leetcode链接:https://leetcode.com/discuss/24013/my-short-c-solution-o-1-space-and-o-n-time
代码2:
class Solution { public: int firstMissingPositive(int A[], int n) { for(int i = 0; i < n; ++ i) while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i]) swap(A[i], A[A[i] - 1]); for(int i = 0; i < n; ++ i) if(A[i] != i + 1) return i + 1; return n + 1; } };
相关文章推荐
- Bellman-Ford 算法证明
- 设计模式六大原则
- Android中实现点击变换图片
- 装饰模式
- 【SoftwareTestingLab1】--3013218086--
- 7-7-无向网的最小生成树-图-第7章-《数据结构》课本源码-严蔚敏吴伟民版
- java中的匿名内部类总结
- 七步教你精通Python机器学习
- Instrusive hdu 5040 优先队列+BFS
- abs()与fabs()
- HTML5 Canvas绘制转盘抽奖
- 四则运算3结对开发
- php捕获网络页面
- printf("%*s%s%*s",——)是什么?
- 二柱子四则运算3
- Spring-Java检查型异常和非检查型异常
- Struts2 json
- ThreadLocal的内存泄漏问题
- 使用PHP操作从Web访问MySQL
- 喝汽水