Leetcode no. 41
2016-07-09 23:40
190 查看
41. First Missing Positive
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.
public class Solution {
public int firstMissingPositive(int[] nums) {
if (nums.length==0) return 1;
for (int i=0; i<nums.length; i++){
while (nums[i]>0 && nums[i]<= nums.length && nums[i]!=i+1){
if (nums[i]== nums[nums[i]-1]) break;
int tmp= nums[nums[i]-1];
nums[nums[i]-1]= nums[i];
nums[i]= tmp;
}
}
for (int i=0; i<nums.length; i++){
if (nums[i]!=i+1) return i+1;
}
return nums[nums.length-1]+1;
}
}
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.
public class Solution {
public int firstMissingPositive(int[] nums) {
if (nums.length==0) return 1;
for (int i=0; i<nums.length; i++){
while (nums[i]>0 && nums[i]<= nums.length && nums[i]!=i+1){
if (nums[i]== nums[nums[i]-1]) break;
int tmp= nums[nums[i]-1];
nums[nums[i]-1]= nums[i];
nums[i]= tmp;
}
}
for (int i=0; i<nums.length; i++){
if (nums[i]!=i+1) return i+1;
}
return nums[nums.length-1]+1;
}
}
相关文章推荐
- Codeforces Round #350 (Div. 2) C. Cinema __ sortings, 思维题,many data
- LRU Cache
- The Values You Can Mak CF687C(简单DP)
- Linux挂载U盘
- Launcher3--抽屉
- 百度地图被曝偷跑流量自动下载音频
- 百度地图被曝偷跑流量自动下载音频
- Turtle随机生成图像
- 安卓中的Flux架构
- [leetcode]344. Reverse String
- [LintCode] Parking Lot 停车场问题
- HDU 1115 Lifting the Stone
- JavaScript类数组对象
- [华为OJ] 字符串加密
- 数论相关公式
- XXTea算法Java版
- Android内核开发:图解Android系统的启动过程
- Github如何上传文件
- pch文件
- 用go和zk实现一个简单的分布式server