题目:

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.

代码:

class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
const int len = nums.size();
for ( int i = ; i < len; ++i )
{
while ( nums[i]!=i+ )
{
if ( nums[i]>len || nums[i]< || nums[i]==nums[nums[i]-] ) break;
std::swap(nums[i], nums[nums[i]-]);
}
}
for ( int i = ; i < len; ++i )
{
if ( nums[i]!=i+)
return i+;
}
return len+;
}
};

tips:

通过此题学习了桶排序(bucket sort)

桶排序原理讲解 http://bubkoo.com/2014/01/15/sort-algorithm/bucket-sort/

桶排序演示动画 http://www.cs.usfca.edu/~galles/visualization/BucketSort.html

大神的解答 http://fisherlei.blogspot.sg/2012/12/leetcode-first-missing-positive.html

自己coding的时候思考过程如下:

1. 此题设计的是最简单的桶,利用nums[i]存放i+1

2. 如果某个位置上nums[i]不等于i+1,则就swap(nums[i], nums[nums[i]-1])

  为什么是这样的?因为nums[i]=i+1→nums[i]-1=i→nums[nums[i]-1]=i,简单说就是把nums[i]这个值放到它该放到的桶里面。

3. 紧接着考虑2中swap能成每次都立么?显然不能:nums[i]>len nums[i]<1这两个条件出现时已经超出了nums数组量程。显然是不行的。

还有一种隐蔽的情况也是不能swap的,比如[1,1]会陷入死循环,因此在swap之前还需要判断nums[i] != nums[nums[i]-1]。

4. 把1~3的过程走完,再遍历数组nums,判断nums[i]!=i+1第一次出现的位置。

5. 如果4中把nums都走过一遍,也没有发现缺失的,则证明缺失的是len+1。

=============================================

第二次过这道题,直接记住思路了,默写了一遍。

class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
for ( int i=; i<nums.size(); ++i )
{
while ( nums[i]!=i+ )
{
if ( nums[i]>nums.size() || nums[i]< || nums[i]==nums[nums[i]-] ) break;
swap(nums[i],nums[nums[i]-]);
}
}
for ( int i=; i<nums.size(); ++i )
{
if ( nums[i]!=i+ ) { return i+; }
}
return nums.size()+;
}
};

【First Missing Positive】cpp的更多相关文章

  1. hdu 4740【模拟+深搜】.cpp

    题意: 给出老虎的起始点.方向和驴的起始点.方向.. 规定老虎和驴都不会走自己走过的方格,并且当没路走的时候,驴会右转,老虎会左转.. 当转了一次还没路走就会停下来.. 问他们有没有可能在某一格相遇. ...

  2. 【Combination Sum II 】cpp

    题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...

  3. 【Search Insert Position 】cpp

    题目: Given a sorted array and a target value, return the index if the target is found. If not, return ...

  4. 【Insertion Sorted List】cpp

    题目: Sort a linked list using insertion sort. 代码: /** * Definition for singly-linked list. * struct L ...

  5. 【Merge Sorted Array】cpp

    题目: Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Not ...

  6. 【Path Sum II】cpp

    题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the give ...

  7. 【Longest Common Prefix】cpp

    题目: Write a function to find the longest common prefix string amongst an array of strings. 代码: class ...

  8. 【 Regular Expression Matching 】cpp

    题目: Implement regular expression matching with support for '.' and '*'. '.' Matches any single chara ...

  9. 【Longest Palindromic Substring】cpp

    题目: Given a string S, find the longest palindromic substring in S. You may assume that the maximum l ...

随机推荐

  1. mysql中union与union all的区别

    当查询表结构完全相同的多张表的数据时: 1.当查询条件完全相同且不包括主键,此时用union查询会过滤掉查询出的重复的记录,及漏查记录:使用union all进行查询,则会查出所有的符合条件的记录,保 ...

  2. url中文参数解决方案

    首先,弄清楚为什么url传递中文会转码或者乱码,以及http头 contentType="text/html; charset=GBK" 的作用. html代码会经过web服务器, ...

  3. WebClient模拟发送Post请求

    WebClient模拟发送Post请求方法: /// <summary> /// 模拟post请求 /// </summary> /// <param name=&quo ...

  4. ASP.NET中的状态保持(转载)

    状态是某一类型的数据在一定时期内保持活跃的信息.这里说的一定时期可以使整个应用程序的生命周期,可以使用户操作程序的时间,当然也可以是单个页面的生命周期等.  为了解决传统Web编程中固有的限制,ASP ...

  5. 在VS中快速查看文件被谁签出

    步骤如下: 1 在VS中的菜单上单击鼠标右键,然后选择显示“源代码管理” 2 选中要查看的文件后,在源代码管理中单击“属性” 3 打开第2个标签页“Check Out Status”,可以看到签出人等 ...

  6. asp.net mvc 用Redis实现分布式集群共享Session。

    1.这两天研究Redis搞分布式session问题,网上找的资料都是用ServiceStack.Redis来实现的,但是在做性能测试的时候发现最新的v4版本有限制每小时候最多请求6000次,因为官网开 ...

  7. php 数组排序代码

    php对数组排序代码.   <?phpclass='pingjiaF' frameborder='0' src='http://www.jbxue.com' scrolling='no'> ...

  8. 【转】CSS white-space 属性

    定义和用法 white-space 属性设置如何处理元素内的空白. 这个属性声明建立布局过程中如何处理元素中的空白符.值 pre-wrap 和 pre-line 是 CSS 2.1 中新增的. 默认值 ...

  9. spark概论,补充

    基本概念 RDD spark最大的亮点是提出RDD(Resilient Distributed Dataset)的概念,也就是可伸缩的分布式数据集合,本身只读,可恢复.spark本身不做物理储存,通过 ...

  10. 【Weblogic】--Weblogic的部署方式和缓存

    参考网址: http://dead-knight.iteye.com/blog/1938882 Weblogic11g部署web应用,有三种方式,非常简单,但是很多新手部署总是出现若干错误,不知道如何 ...