/
DeC2018
/
0041
Обзор
Документация
Войти
/
DeC2018
/
0041
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
main.cpp
55 строк
1 KB
Den
create main.cpp
23 янв 2025, 22:18
23 янв 2025, 22:18
da2c18d
Код
Авторство
О чём код?
#include <iostream> #include <vector> #include <cmath> using namespace std; class Solution { public: int firstMissingPositive(vector<int>& nums) { int n = nums.size(); // Step 1: Replace negative numbers, zeros, and numbers larger than n with n + 1 for (int i = 0; i < n; i++) { if (nums[i] <= 0 || nums[i] > n) { nums[i] = n + 1; } } // Step 2: Mark the presence of numbers for (int i = 0; i < n; i++) { int temp = abs(nums[i]); if (temp <= n) { nums[temp - 1] = -abs(nums[temp - 1]); } } // Step 3: Find the first positive number for (int i = 0; i < n; i++) { if (nums[i] > 0) { return i + 1; } } // If all numbers from 1 to n are present return n + 1; } }; int main() { Solution solution; vector<int> nums1 = {1, 2, 0}; cout << "Input: nums = [1,2,0]" << endl; cout << "Output: " << solution.firstMissingPositive(nums1) << endl; vector<int> nums2 = {3, 4, -1, 1}; cout << "Input: nums = [3,4,-1,1]" << endl; cout << "Output: " << solution.firstMissingPositive(nums2) << endl; vector<int> nums3 = {7, 8, 9, 11, 12}; cout << "Input: nums = [7,8,9,11,12]" << endl; cout << "Output: " << solution.firstMissingPositive(nums3) << endl; return 0; }