leetcode-First Missing Positive
阿新 • • 發佈:2017-06-11
href algorithm missing 排序 lan problem right ive 數組
https://leetcode.com/problems/first-missing-positive/#/description
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.
題解:這道題目比較簡單,需要註意的是幾個陷阱:數組為空,數組裏數據重復。
比較有技巧的地方是O(1)space,因為考慮到數據重復,此處只能排序, 這就要求重用nums數組空間。
引用網上一位網友的題解:
Put each number in its right place. For example: When we find 5, then swap it with A[4]. At last, the first place where its number is not right, return the place + 1.
程序:
1 class Solution { 2 public: 3 intfirstMissingPositive(vector<int>& nums) { 4 for (int i = 0; i < nums.size(); i++) 5 { 6 while (nums[i] > 0 && nums[i] <= nums.size() && nums[i] != nums[nums[i] -1]) 7 { 8 swap(nums[i], nums[nums[i] -1]); 9 } 10 } 11 for (int i = 0; i < nums.size(); i++) 12 { 13 if (nums[i] != i + 1) 14 { 15 return i + 1; 16 } 17 } 18 return nums.size() + 1; 19 } 20 };
leetcode-First Missing Positive