Friday, June 14, 2013

find the first missing positive integer@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
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.
» Solve this problem

We need to pay attention to two constraints, 1) Constant additional space. 2)O(n) time cost. So we can't sort the array first and can't copy the array to another array. While the key point here, is to find the first missing positive integer of the array. So we can make use of the index. We iterate through the whole array, to store A[i] = i+1, if i+1 exists in the array. We do the swap.

In the swap loop, we need to be careful.
In the first, my loop is
for( int i=0; i<n; i++)
{
   if(A[i]<n&&A[i]>0)
   swap(A[i], A[A[i]-1]);
}

In this case, it will miss some elements in the array. For example, -1, 4, 2, 1, 9, 10. After first swap, A[3]=4, A[1]=1. So 1 will be missed to be swapped. So the loop here is very important.


No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...