leetcode做题总结,题目First Missing Positive 2012/03/08
来源:互联网 发布:elfgame软件视频格式 编辑:程序博客网 时间:2024/05/18 12:43
这道题一开始把题意理解偏了,我以为是找出串中第一个缺失的正数,比如5,6,8返回7,但是题意是从1开始5,6,8应该返回1。这样就容易了很多。只要把位置和数字对应上即可,如果数字小于等于0直接无视,如果大于数组长度也无视,因为如果有数字大于数组长度,则从1~数组长度必有一个数字缺失。遇到数字i就把他交换到A[i-1]的位置上去,调整后如果出现A[i]!=i+1则返回i+1;注意的是交换后需要i--重新访问一下这个位置。
public int firstMissingPositive(int[] A) { if(A.length==0) return 1; if(A.length==1){ if(A[0]==1)return 2; else return 1; } int tmp; for(int i=0;i<A.length;i++){ if(A[i]!=i+1&&A[i]>0&&A[i]<A.length&&A[A[i]-1]!=A[i]){ tmp=A[A[i]-1]; A[A[i]-1]=A[i]; A[i]=tmp; i--; } } for(int i=0;i<A.length;i++){ if(A[i]!=i+1) return i+1; } return A.length+1; }
Update 2015/08/22: 上面的可以更加简洁
public class Solution { /** * @param A: an array of integers * @return: an integer */ public int firstMissingPositive(int[] A) { // write your code here int tmp; for(int i=0;i<A.length;i++){ if(A[i]!=i+1 && A[i]>0 && A[i]<A.length && A[A[i]-1]!=A[i]){ tmp=A[A[i]-1]; A[A[i]-1]=A[i]; A[i]=tmp; i--; } } for(int i=0;i<A.length;i++){ if(A[i]!=i+1) return i+1; } return A.length+1; }}
0 0
- leetcode做题总结,题目First Missing Positive 2012/03/08
- leetcode -- First Missing Positive -- 简单trick题目
- LeetCode题目:41. First Missing Positive
- LeetCode: First Missing Positive
- LeetCode First Missing Positive
- LeetCode: First Missing Positive
- [Leetcode] First Missing Positive
- [LeetCode] First Missing Positive
- [Leetcode] First Missing Positive
- leetcode First Missing Positive
- LeetCode First Missing Positive
- [leetcode] first missing positive
- LeetCode: First Missing Positive
- [LeetCode]First Missing Positive
- LeetCode-First Missing Positive
- [leetcode] First Missing Positive
- [LeetCode] First Missing Positive
- LeetCode - First Missing Positive
- ViewPager的adapter
- 畅通工程续
- WebStorm的安装和配置
- APUE笔记二
- UVA 11732 - strcmp() Anyone?(Trie)
- leetcode做题总结,题目First Missing Positive 2012/03/08
- 使用CCScrollView + CCMenu
- 程序员通过什么渠道接外包项目和兼职编程工作
- Win7系统安装U盘制作、使用及Win7系统安装详细流程(超简单)
- POJ 2677 Tour
- 最短路径问题
- SVN服务器搭建和使用(三)
- ASP.NET Web API Caching with CacheCow and CacheOutput
- TortoiseSVN客户端重新设置用户名和密码