First Missing Positive Leetcode
来源:互联网 发布:MySQL concat array 编辑:程序博客网 时间:2024/06/01 22:21
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.
My Solution:
public class Solution { public int firstMissingPositive(int[] A) { Boolean[] table = new Boolean[A.length + 1]; for (int i = 0; i < table.length; i++) { table[i] = false; } int i = 0; while(i < A.length){ if(A[i] > 0 && A[i] <= table.length - 1) table[A[i]] = true; i ++; } i = 1; while(i < table.length && table[i]) i++; return i; }}better Solution:
public class Solution { public int firstMissingPositive(int[] A) { int i = 0; while(i < A.length){ if(A[i] == i+1 || A[i] <= 0 || A[i] > A.length) i++; else if(A[A[i]-1] != A[i]) swap(A, i, A[i]-1); else i++; } i = 0; while(i < A.length && A[i] == i+1) i++; return i+1; } private void swap(int[] A, int i, int j){ int temp = A[i]; A[i] = A[j]; A[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
- 今天被一个架构师面了
- 欢迎使用CSDN-markdown编辑器
- 基于Java、Kafka、ElasticSearch的搜索框架的设计与实现
- go语言中select与switch的区别
- 自顶向下 逐步求精
- First Missing Positive Leetcode
- 用Java生成随机检查作业的程序
- SqlServer邮件
- 稀疏矩阵
- React学习笔记
- SpringJdbcTemplate模板类使用小记
- [LeetCode] Longest Palindromic Substring
- 2017年年末目标
- maya(学习笔记)之Arnold渲染器二