Leetcode 41. First Missing Positive

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

1. Description

《Leetcode 41. First Missing Positive》 First Missing Positive

2. Solution

  • Version 1
class Solution {
public:
    int firstMissingPositive(vector<int>& 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<int>& 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/
    原文作者:SnailTyan
    原文地址: https://www.jianshu.com/p/240ecddd851c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞