LeetCode First Missing Positive
来源:互联网 发布:淘宝卖兽药 编辑:程序博客网 时间:2024/04/30 06:52
思路:
要求找到第一个应该属于[1,nums.size()]范围内的正数却又目前不在的。
从头开始,挨个把各个数换到相应地位置,然后再扫一遍数组,看哪一个数不在它应在的位置上。
时间复杂度O(N),空间复杂度O(1)。
class Solution {private: void change(vector<int> &nums) { int n = nums.size(); for(int i = 0; i < nums.size(); ++i) { while(nums[i] != i+1) { if(nums[i] < 0 || nums[i] > n || nums[i] == nums[nums[i] - 1]) { break; } swap(nums[i], nums[nums[i] - 1]); } } }public: int firstMissingPositive(vector<int>& nums) { change(nums); for(int i = 0; i < nums.size(); ++i) { if(nums[i] != i+1) { return i + 1; } } return nums.size() + 1; }};
java code:
public class Solution { public int firstMissingPositive(int[] nums) { if(nums == null || 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[nums[i] - 1] == nums[i]) break; swap(nums, i, nums[i] - 1); } } for(int i = 0; i < nums.length; ++i) { if(nums[i] != i + 1) return i + 1; } return nums.length + 1; } void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }}
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
- 如何判断NGUI的ScrollView是否正在移动
- android library projects cannot be launched解决方法
- 用组合代替继承能为 Activity 带来什么
- 如何对程序的栈进行保护————x86_64
- DNS原理和解析过程 (2)
- LeetCode First Missing Positive
- java集合中的fail-fast机制
- ZOJ 3758 Singles' Day
- Balanced Binary Tree
- 第四章(同步并发操作)
- 7月10日 使用 APPLY MSDN
- Qt串口为什么会丢消息包?
- web.xml加载过程
- 新入手的Atmel-ICE产品说明