您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - First Missing Positive

2012-09-06 04:37 381 查看
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.

JAVA 正解如下:

public class Solution {
public int firstMissingPositive(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function

//put i to A[i-1], so the array looks like: 1, 2, 3, ...

for (int i = 0; i < A.length; i++) {
while (A[i] != i+1) {
if (A[i] <= 0 || A[i] > A.length || A[i] == A[A[i] - 1]) {
break;
}

int tmp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = tmp;
}
}

for (int i = 0; i < A.length; i++) {
if (A[i] != i+1) {
return i+1;
}
}
return A.length+1;

}
}


按照数组里的值换位,然后再撸一次,撸到A[i] != i + 1; 返回此i +1,如果不存在,那第一个Missing 正整数就是数组长度的后面一个数了。

对不起了,下面的做法是错误示范,不能算是constant space!!

public static int FirstMissingPositive(int[] A)
{
BitArray ba = new BitArray(int.MaxValue);
int max = int.MinValue;
foreach (int num in A)
{
if(num > max) //set the maximum number in A[]
max = num;
if(num > 0) //ignore the negative number
ba[num] = true;
}

//if no positive number in A[], return 1
if(max <= 0)
return 1;

//retrieve the first missing positive
for (int i = 1; i < max; i++)
{
if (!ba[i])
return i;
}

return max + 1;
}


代码分析:

  建立一个bit array,迭代input数组,碰到positive的就映射到bit array,同时维持一个max来存放数组中最大的数。

  如果max <= 0, 返回1。

  迭代bit array,找出最小的positive number。 如果没有,返回max后一个数 max + 1。

int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// Find the max value
int max = 0;
for (int i = 0; i < n; ++i)
max = (A[i] >= 0 && A[i] > max) ? A[i] : max;

if (max <= 0)
return 1;

// Allocate memory of size max bits
unsigned int size = max / 8 + (max % 8 > 0);
// Initialize the memory
// all reset to 0 but the first one
char arr[size];
arr[0] = 1;
for (int i = 1; i < size; ++i)
arr[i] = 0;

// If the given array containing the value,
// set the x-th value to 1;
for (int i = 0; i < n; ++i)
{
if (A[i] <= 0)
continue;

unsigned int index = A[i] / 8;
char mask = A[i] % 8;

arr[index] = arr[index] | (1 << mask);
}

// Check the first missing positive
for (int i = 0; i < size; ++i)
for (int mask = 0; mask < 8; ++mask)
if (((arr[i] >> mask) & 1) == 0)
return (i * 8 + mask);

return max + 1;
}


贴一个C++的code,毕竟C++没有内建的bit array。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: