Accepted 4ms c++ solution with std::swap().


  • 3
    class Solution {
    public:
        int firstMissingPositive(std::vector<int>& nums) {
            int n = nums.size();
            for (int i = 0; i != n;) {
                if (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) {
                    std::swap(nums[i], nums[nums[i] - 1]);
                } else {
                    ++i;
                }
            }
            for (int i = 0; i != n; ++i) {
                if (nums[i] != i + 1) {
    				return i + 1;
    			}
            }
            return n + 1;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.