LeetCode First Missing Positive
来源:互联网 发布:match sql语句 编辑:程序博客网 时间:2024/04/30 01:19
这题不是自己做的,也没想出来,估计要我自己想得想个一年半载的,也够呛。看了别人的做法真是巧妙呀。不管别的,把能放得放到应该放的位置上,当然之前不能覆盖元素,所以要保存原来的值,然后还要对保存的值进行同样处理,看看它能放到哪,因为元素的值都是正整数,所以可以直接作为索引了,这样才能保证O(n)的时间复杂度。因为每次放到正确的位置的值下次就不用放了,所以不会重复无用的计算,这样既是for里有while 还能是O(n)的时间复杂度。漂亮!理解了,学习了。
int firstMissingPositive(int A[], int n) {for(int i = 0; i < n; ++i) { int curNum = A[i]; while(curNum >= 1 && curNum <= n && A[curNum-1] != curNum) { int tmp = A[curNum-1]; A[curNum-1] = curNum; curNum = tmp; } } //find the first missing int i; for(i = 0; i < n; ++i) if(A[i] != i+1) break; return i+1; }
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
- 设置Linux shell超时自动退出
- JMS
- 【Unity Shaders】Diffuse Shading——漫反射光照改善技巧
- 关于word删不掉的虚线横线
- AT24C256
- LeetCode First Missing Positive
- adb 环境变量设定
- HDU 2053 Switch Game(基础题)
- 蓝桥杯 c 天干地支计年法转换
- 今天说点什么呢
- ovs-ofctl 官方手册翻译(1)OpenFlow Switch Management Commands
- 我的2013
- 安卓UDP通信
- 利用函数传递结构体--冒泡排序