Leetcode41. First Missing Positive
来源:互联网 发布:python ftp上传文件 编辑:程序博客网 时间:2024/05/22 15:44
题目
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.
思路
利用hash的思想来做
PS:在本地测试的时候,将中间结果打印出来
测试用例
[][0][1][-1][-1, 2, 3, 5, 1 , 6]
代码
public class Solution { public int firstMissingPositive(int[] nums) { for(int i = 0; i < nums.length; i++){ while(nums[i] > 0 && nums[i] < nums.length && nums[ nums[i] - 1] != nums[i]) 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 left, int right){ int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; }}
结果
他山之玉
class Solution{public: int firstMissingPositive(int A[], int n) { for(int i = 0; i < n; ++ i) while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i]) swap(A[i], A[A[i] - 1]); for(int i = 0; i < n; ++ i) if(A[i] != i + 1) return i + 1; return n + 1; }};
public class Solution { public int firstMissingPositive(int[] nums) { // nums[i] -> i+1 int next; for (int i = 0 ; i < nums.length; i++) { int curr = nums[i]; if (curr > 0 && curr != i+1 && curr <= nums.length) { do { next = nums[curr-1]; nums[curr-1] = curr; curr = next; } while (curr > 0 && curr <= nums.length && nums[curr-1] != curr); } } int j; for (j = 0; j < nums.length; j++) { if (nums[j] != j+1) break; } return j+1; }}
def firstMissingPositive(self, A): num = 0 for i in A: if i > 0: num = num | (1 << i) x = 1 while True: if (1 << x) & num == 0: return x x += 1
阅读全文
0 0
- [LeetCode41] First Missing Positive
- Leetcode41 First Missing Positive
- LeetCode41. First Missing Positive
- leetcode41. First Missing Positive
- leetcode41. First Missing Positive
- Leetcode41. First Missing Positive
- LeetCode41——First Missing Positive
- leetcode41~First Missing Positive Add to List
- LeetCode41/19 First Missing Positive/Remove Nth Node From End of List ****
- LeetCode: First Missing Positive
- LeetCode First Missing Positive
- LeetCode: First Missing Positive
- [Leetcode] First Missing Positive
- leetcode12: First Missing Positive
- First Missing Positive
- [LeetCode] First Missing Positive
- [Leetcode] First Missing Positive
- leetcode First Missing Positive
- Hadoop之旅(7)— HDFS HA Zookeeper自动故障转移
- jquery.form实现ajax上传文件同时设置headers
- Spring + iBATIS完整示例
- Redis入门指南之复制
- JavaScript学习总结——JavaScript编写类
- Leetcode41. First Missing Positive
- SERVLETJSP Unit05:转发 、 JSP开发常见问题 & Unit09: EL、JSTL
- PhxSQL设计与实现
- 深入浅出RxJava(二:操作符)
- 从零开始设计一款APP之如何做原型图
- [leetcode]55. Jump Game(Java)
- 【ruby】【linux】【irb】CentOS上安装配置ruby开发环境,安装 irb
- (3)大蚂蚁webservice
- struct stat结构体简介