Given an unsorted integer array, find the first missing positive integer.
2016-04-01 13:50
363 查看
/*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 FindFirstLostPositive { public static void main(String[] args) { System.out.println(new FindFirstLostPositive().firstMissingPositive(new int[]{-1,-2,-3,1,2,3,4,5,6,7,8,9})); } public int firstMissingPositive(int[] nums) { if(nums.length==0||nums==null) return 1; //1放在nums[0],2放在nums[1] for(int i = 0;i<nums.length;i++) { while(nums[i]!=i+1) { if(nums[i]>=nums.length||nums[i]<=0||nums[i]==nums[nums[i]-1]) break; int temp = nums[i]; nums[i] = nums[temp-1]; nums[temp-1] = temp; } } for(int i = 0;i<nums.length;i++) { if(nums[i]!=i+1) return i+1; } return nums.length+1; } }
相关文章推荐
- 规范Python程序配置文件读写
- Zookeeper全解析——Paxos作为灵魂
- 用户手势检测-GestureDetector使用详解
- 后端知识体系--一次完整的HTTP请求
- PopupListView(ListView的Item点击弹出和退回到原来位置)
- 最简单的基于FFmpeg的libswscale的示例
- 从头学习JAVA(三)
- springMVC + hadoop + httpclient 文件上传请求直接写入hdfs
- 二叉查找树转化为双向链表
- 从业十余年谈谈对dotnet看法与坚持
- HTTP请求
- j2se方法
- Python中的threading
- PhotoSwipe简介
- eclipse创建可以导入MyEclipse的工程
- iOS 9 by Tutorials 笔记(十三)Testing
- GPRS模块在Linux平台上ppp拨号上网总结与心得
- Windows不要使用记事本编辑文本文件
- 【笔记】 《js权威指南》- 第3章 类型、值和变量 - 3.10 变量作用域
- hittest方法