Leetcode 41. First Missing Positive

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 41. First Missing Positive_第1张图片
First Missing Positive

2. Solution

  • Version 1
class Solution {
public:
    int firstMissingPositive(vector& nums) {
        int x = 0;
        for(int i = 1; i <= nums.size(); i++) {
            for(int j = 0; j < nums.size(); j++) {
                x = i ^ nums[j];
                if(x == 0) {
                    break;
                }
            }
            if(x != 0) {
                return i;
            }
        }
        return nums.size() + 1;
    }
};
  • Version 2
class Solution {
public:
    int firstMissingPositive(vector& nums) {
        int index = 0;
        int size = nums.size();
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] == i + 1) {
                continue;
            }
            if(nums[i] > 0 && nums[i] <= size && nums[nums[i] - 1] != nums[i]) {
                swap(nums[nums[i] - 1], nums[i]);
                i--;
            }
        }
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] != i + 1) {
                index = i;
                break;
            }
            index++;
        }
        return index + 1;
    }

private:
    void swap(int& a, int& b) {
        int temp = a;
        a = b;
        b = temp;
    }
};

Reference

  1. https://leetcode.com/problems/first-missing-positive/description/

你可能感兴趣的:(Leetcode 41. First Missing Positive)