First Missing Positive

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.

SOLUTION 1:

使用类似桶排序的方法:

将值放在它应该在的位置,最后再扫描一次得出哪个位置有缺少值。

引自:

http://m.blog.csdn.net/blog/hellobinfeng/17348055

http://n00tc0d3r.blogspot.com/2013/03/find-first-missing-positive.html

http://www.cnblogs.com/AnnieKim/archive/2013/04/21/3034631.html

A few quick thoughts:

  • Sort all numbers and iterate through to find the first missing integer? No, most sorting algorithms take time at least O(nlogn).
  • How about linear sorting algorithm? No, bucket sort requires O(n) space.
  • Mapping all positive integers to a hash table and iterate from 1 to the length of the array to find out the first missing one? No, hash table requires O(n) space.

Then, how to solve this?

Let's take another look at the problem. It is asking for the first missing POSITIVE integer.
So, given a number in the array,

  • if it is non-positive, ignore it;
  • if it is positive, say we have A[i] = x, we know it should be in slot A[x-1]! That is to say, we can swap A[x-1] with A[i] so as to place x into the right place.
We need to keep swapping until all numbers are either non-positive or in the right places. The result array could be something like [1, 2, 3, 0, 5, 6, ...]. Then it's easy to tell that the first missing one is 4 by iterate through the array and compare each value with their index.

解1:

 public int firstMissingPositive1(int[] A) {
// bug 3: when length is 0, return 1;
if (A == null) {
return 0;
} for (int i = 0; i < A.length; i++) {
// BUG 1: TLE , should judge when A[i] - 1 == i;
while (A[i] - 1 != i && A[i] > 0) {
// bug 2: cant exchange a same node: A[A[i] - 1] != A[i]
if (A[i] - 1 < A.length && A[A[i] - 1] != A[i]) {
swap(A, i, A[i] - 1);
} else {
// when the number is out of range, delete it.
A[i] = 0;
}
}
} for (int i = 0; i < A.length; i++) {
if (A[i] <= 0) {
return i + 1;
}
} return A.length + 1;
} public void swap(int[] A, int l, int r) {
int tmp = A[l];
A[l] = A[r];
A[r] = tmp;
}

简化后,解2:

其实交换的条件就是3个:

1: A[i] is in the range;
2: A[i] > 0.
3: The target is different; (如果不判断这个,会造成死循环,因为你交换过来一个一样的值)

 // SOLUTION 2:
public int firstMissingPositive(int[] A) {
// bug 3: when length is 0, return 1;
if (A == null) {
return 0;
} for (int i = 0; i < A.length; i++) {
// 1: A[i] is in the range;
// 2: A[i] > 0.
// 3: The target is different;
while (A[i] <= A.length && A[i] > 0 && A[A[i] - 1] != A[i]) {
swap(A, i, A[i] - 1);
}
} for (int i = 0; i < A.length; i++) {
if (A[i] != i + 1) {
return i + 1;
}
} return A.length + 1;
}

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/array/FirstMissingPositive.java

LeetCode: First Missing Positive 解题报告的更多相关文章

  1. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  2. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  3. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  4. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

  5. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  6. 【LeetCode】Gas Station 解题报告

    [LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...

  7. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  8. [LeetCode] First Missing Positive 首个缺失的正数

    Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0]  ...

  9. LeetCode: Unique Paths II 解题报告

    Unique Paths II Total Accepted: 31019 Total Submissions: 110866My Submissions Question Solution  Fol ...

随机推荐

  1. python使用 requirements.txt 管理所需的包

    使用 requirements.txt 管理所需的包 2019/01/28 作者 若要与其他人共享项目.使用生成系统,或打算将项目复制到需要在其中还原环境的其他任何位置,必须指定项目需要的外部包. 建 ...

  2. P2376 [USACO09OCT]津贴Allowance

    P2376 [USACO09OCT]津贴Allowance一开始想的是多重背包,但是实践不了.实际是贪心,让多c尽可能少,所以先放大的,最后让小的来弥补. #include<iostream&g ...

  3. P3719 [AHOI2017初中组]rexp

    P3719 [AHOI2017初中组]rexp一开始想的是类似计算式子的值的东西,用栈.然后发现处理最大值很麻烦,因为处理的很像子过程,所以考虑递归来做.碰到'('就递归一次,碰到'|'就取最大值再递 ...

  4. CNN做序列标注问题(tensorflow)

    一.搭建简单的CNN做序列标注代码 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt TIME_ST ...

  5. AGC 016B.Colorful Hats(思路)

    题目链接 对于某个元素分类讨论一下,就可以知道n个元素的总颜色种数了. 比如对a[1]分类讨论: 若1的颜色和某个元素相同,则总颜色数为a[1].a[i]要么等于a[1](i与某个元素颜色相同,记个数 ...

  6. [BZOJ4987]Tree

    题目大意: 给定一棵\(n(n\le3000)\)个点的带边权的树,找出\(k\)个点\(A_{1\sim k}\)使得\(\sum_{1\le i<k} dis(A_i,A_i+1)\)最小. ...

  7. C++学习笔记38:事件机制

    事件基本概念 操作系统或应用程序内部发生某件事,程序的某个组件需要响应该事件,并进行特定处理 面向对象架构中,事件响应函数最可能为成员函数 问题:指向类成员函数的指针不能转换为哑型指针void *,也 ...

  8. centos 6 秘钥分发

    http://www.cnblogs.com/chensiqiqi/p/6554055.html

  9. redis 在 php 中的应用(Server[ 服务器] 篇)

    本文为我阅读了 redis参考手册 之后编写,注意 php_redis 和 redis-cli 的区别(主要是返回值类型和参数用法) 目录: Server(服务器) BGREWRITEAOF BGSA ...

  10. Matplotlib新手上路(下)

    接上篇继续,这次来演示下如何做动画,以及加载图片 一.动画图 import numpy as np import matplotlib.pyplot as plt import matplotlib. ...