[LeetCode]First Missing Positive
2015-11-10 11:41
288 查看
First Missing Positive
My SubmissionsQuestion
Total Accepted: 51712 Total
Submissions: 224707 Difficulty: Hard
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.
Subscribe to see which companies asked this question
这个问题做了好久,好多次提交都没有成功,一开始我的想法是通过加一个数减一个数的方式来做,首先是计算有多少个正数,从而判断他们的和是多少,然后减去数组中已有的,后来发现这种方法没法处理有重复值得情况。之后想到的是,利用数组下标,将数值放到对应的下标上,最后AC。
public class Solution { public int firstMissingPositive(int[] nums) { if(nums.length<1)return 1; int result = 0; for(int i=0;i<nums.length;i++){ if(nums[i]>0&&nums[i]!=i+1){ if(nums[i]>nums.length){ continue; } while(nums[i]!=i+1&&nums[i]>0){ if(nums[i]-1>=nums.length||nums[nums[i]-1]==nums[i])break; int temp = nums[nums[i]-1]; nums[nums[i]-1]=nums[i]; nums[i]=temp; } } } for(int i=0;i<nums.length;i++){ if(nums[i]!=i+1){ return i+1; } } return nums.length+1; } }
相关文章推荐
- 类的动态实例化
- oracle基本使用
- 常用网站
- js实现浮动框跟随页面滚动,最后停留在原来位置
- 性能优化tips(一)
- cannot reload avd list问题
- Java层与Jni层的数组传递
- 三维血管中轴线特征描述
- Flash 独占 Exploit Kits 被利用漏洞前八席
- C++中 0 与 NULL 与 nullptr之间的关系,nullptr_t 的实现
- IntelliJ IDEA 15 Released 破解 注册码
- jquery 获取url 参数方法 以及 解决url中文问题
- 美国电商是如何用大数据玩转“双十一”的?
- C#判断三角形的类型
- 如何将ppt转换成pdf
- 初始Dubbo框架(HelloWorld)
- 【Codeforces Round 326 (Div 2)E】【树链剖分】Duff in the Army 树上给定路径上编号最小的几个人
- Swift开发之使用UIRefreshControl实现下拉刷新数据及uirefreshcontrol使用
- 惯导
- [LeetCode]3Sum