LeetCode 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.

题意:给出一个数组,求其第一个缺失的整数

思路:从1开始查找,如果找到,就开始查找2,依次类推。在查找的过程中有两种情况

(1)如果nums[i] 不等于要找的数,i++

(2)如果相等,就将nums[i]与要找的数所在的下标交换,并且从要找的数的下标开始继续查找,同时将要查找的数加1

代码如下:

class Solution
{
    public int firstMissingPositive(int[] nums)
    {
        int result = 1;
        for (int i = 0; i < nums.length;)
        {
            if (nums[i] != result) i++;
            else
            {
                int tmp = nums[result - 1];
                nums[result - 1] = nums[i];
                nums[i] = tmp;

                i = result++;
            }
        }

        return result;
    }
}


你可能感兴趣的:(LeetCode First Missing Positive)