Title:

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放到数组中0的位置,2放到1的位置...

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

  

 

相关文章:

  • 2021-11-01
  • 2021-12-31
  • 2022-02-24
  • 2021-08-02
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-04
  • 2021-07-22
  • 2021-08-09
  • 2021-11-29
  • 2021-06-08
  • 2021-10-03
相关资源
相似解决方案