Leetcode 41. First Missing Positive
来源:互联网 发布:用友软件代理商名单 编辑:程序博客网 时间:2024/05/21 17:22
41. First Missing Positive
Not available yet, please check back later.
Total Accepted: 63225 Total Submissions: 265575 Difficulty: Hard
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.
一看到O(n),常数空间瞬间乱了。觉得这种array的不能用sort的话,基本都是靠integer和下标的对应关系才能O(n),网上一搜果然。。
大致思想是从左到右遍历,然后如果i位置的元素为i+1,no problem;否则交换到nums[i]-1位置的元素(如果该元素<=0也跳过)。
比如[3, 4, -1, 2],首先是3,这个位置元素应该是1,则交换。交换到3-1=2位置的元素,也就是-1。
交换的跳出条件:
1. nums[i]-1>=nums.length || nums[i]-1<0
2. nums[nums[i]-1]==nums[i] 元素重复,会TLE。
public class Solution { public int firstMissingPositive(int[] nums) { if(nums==null || nums.length == 0) return 1; for(int i=0; i<nums.length; i++){ if(nums[i]!=i+1){ //一开始用的while TLE了 if(nums[i]<=0) continue; //一开始用的beak错了 else swap(nums, i); } } 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){ if(nums[i]-1>=nums.length || nums[i]-1<0) return; if(nums[nums[i]-1]==nums[i]) return; //一开始没判断重复tle了 int temp = nums[nums[i]-1]; nums[nums[i]-1] = nums[i]; nums[i]=temp; if(temp<0) return; if(nums[i]!=i+1){ swap(nums, i); } }}
0 0
- [LeetCode]41.First Missing Positive
- LeetCode --- 41. First Missing Positive
- LeetCode 41.First Missing Positive
- [Leetcode] 41. First Missing Positive
- [leetcode] 41.First Missing Positive
- leetCode 41. First Missing Positive
- LeetCode 41. First Missing Positive
- leetcode 41. First Missing Positive
- Leetcode 41. First Missing Positive
- LeetCode 41. First Missing Positive
- [leetcode]41. First Missing Positive
- LeetCode-41.First Missing Positive
- leetcode 41. First Missing Positive
- [LeetCode] 41. First Missing Positive
- [LeetCode]--41. First Missing Positive
- leetcode 41. First Missing Positive
- leetcode 41.First Missing Positive
- leetcode 41. First Missing Positive
- Leetcode 36. Valid Sudoku & 37. Sudoku Solver
- linux下安装mysql5.6.26
- spring+sprinmvc+mybatis基本整合(二)--基于spring注解mybais非注解非Mapper接口方式
- mysql小知识笔记
- std::swap 不支持 std::auto_ptr 类型参数
- Leetcode 41. First Missing Positive
- Android中怎样使用计步器传感器 "TYPE_STEP_DETECTOR"
- round() Function in Python and Matlab
- Leetcode 56. Merge Intervals & 57. Insert Interval
- java基础(29)--深入剖析Java中的装箱和拆箱
- 易學原論 (4288_6)
- java基础(30)--Java中实现CallBack功能
- 70%的人离职因领导这4宗罪
- 易經大意 461_477