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. Flutter常用组件(Widget)解析-Scaffold

    实现一个应用基本的布局结构. 举个栗子: import 'package:flutter/material.dart'; void main() => runApp(MyApp()); clas ...

  2. Ubuntu18.10&Ubuntu18.04安装Python虚拟环境

    Ubuntu18.04版本里面自带了最新的Python3.6.5版本,在安装Python虚拟环境时需注意: 1.首先是安装两个包 pip3 install virtualenv # python虚拟环 ...

  3. 【nodeJS爬虫】前端爬虫系列

    写这篇 blog 其实一开始我是拒绝的,因为爬虫爬的就是cnblog博客园.搞不好编辑看到了就把我的账号给封了:). 言归正传,前端同学可能向来对爬虫不是很感冒,觉得爬虫需要用偏后端的语言,诸如 ph ...

  4. C语言上机练习二

    #include<stdio.h> int main() { int a,b; while(~scanf("%d%d",&a,&b)) printf(& ...

  5. 创建django出现的问题

    1.创建表报错 2.静态文件和模板配置 3.在表格插入数据库信息 4.继承模板 5.找不到post请求数据

  6. tab------左右布局

    <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title> ...

  7. SVN解决本地版本控制与服务器版本冲突问题

    最近经常遇到一个冲突问题,svn服务器已经没有这个文件,本地也没有这个文件,但是你提交代码的时候svn会显示冲突,也就是说本地svn仍然在管理着这个文件. 解决办法:在相应的目录下新建一个名字一样的文 ...

  8. unity无限循环报错的定位

    晚上遇到了,碰到了程序一运行就卡住的尴尬问题,然后百度下,看了看,Get到了一个新的skill. 1. 打开对应的VS程序,选择“调试/Attach Unity Debuger”菜单来调试代码. 2. ...

  9. __getattr__和__setattt__使用

    # coding:utf-8 """ __setattr__(self, name, value),如果要给name赋值,调用此方法 __getattr__(self, ...

  10. Linux--信号阻塞与屏蔽

    1. sigprocmask函数提供屏蔽和解除屏蔽信号的功能. 从而实现关键代码的运行不被打断. 函数声明如下: int sigprocmask(int how, const sigset_t *se ...