leetcode First Missing Positive
来源:互联网 发布:马曳 知乎 编辑:程序博客网 时间:2024/05/17 06:00
题目:https://oj.leetcode.com/problems/first-missing-positive/
思路:完全没有思路,题都没看懂,看了别人的解题报告,大概是这个意思
1.先把整个数组进行各种调换,最后从前往后缕,第一不等于i+1的就是缺的整数
2.怎么调换:首先排除,<0和>n的数,全部跳过,因为他们不可能有属于自己的位置!什么叫属于自己的位置,比如数字3,属于他的位置就是A[2],数字1,属于他的位置就是A[0],当发现有>0并且<n的数时,如果他没在自己的位置,要通过换位,换到属于他的位置,那就是A[A[i]-1]这个位置,如果他目前的位置上,和他该属于的位置上都是同一个数字,也就是说,这个数字出现了两遍,那它肯定多余了,则不进行交换,要不也得进入个死循环,从i=0一直换到i<n
代码:
class Solution {public: int firstMissingPositive(int A[], int n) { if(n <1) return 1; int i =0; while(i<n){ if(A[i]>0 && A[i]<=n && A[i]!=i+1 && A[i]!=A[A[i]-1]){ swap(A[i],A[A[i]-1]); } else i++;<span style="white-space:pre"></span>//这里注意,i++和上面的判断是并列的,因为进行各种换的时候,有可能一次换完得不到i位置上真正的数,那么i先不动,直到实在不行<span style="white-space:pre"></span>//了,i再+1 } for(int i =0;i<n;i++){ if(A[i]!=i+1) return i+1; } return n+1; } void swap(int &a,int &b){ int tmp; tmp =b; b =a; a =tmp; }};
0 0
- 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
- LeetCode | First Missing Positive
- Leetcode: First Missing Positive
- Leetcode:First Missing Positive
- HTML网页中插入本地音乐
- iOS 折线图 ARLineChart-master
- 闻名不如见面——三层
- ubuntu的xorg的配置文件通过/var/log/Xorg.0.log查看位置
- 使用Event Bus模式解耦Android App组件间通信
- leetcode First Missing Positive
- 100+有趣的统计数据集
- 使用SurfaceView.unlockCanvasAndPost报错IllegalArgumentException
- 对于Linux创建链接时终目录和文件处理的认识
- HTTP协议实现文件上传学习心得
- 排序问题 二
- 【最小割】Stoer-Wagner模板
- JS实现HTML页面背景色平滑转变
- word中连续参考文献引用