1. 程式人生 > >尋找一個數組中未出現的最小正整數(數組元素可重復)

尋找一個數組中未出現的最小正整數(數組元素可重復)

個數 pre doesn inf tput swe return 分享圖片 針對

題目描述

Description

Given nn non-negative integers, please find the least non-negative integer that doesn’t occur in the nn numbers.

Input

The first line is an integer T, representing the number of test cases.(T≤10)
The first line of each test case is an integer n (n≤2?10?^5??).
The second line of each test case are nn

non-negative integers a?i?? (a?i??<2?^31??).

Output

For each test case, output a line with the answer.

輸入樣例

2

4

4 0 1 3

2

1 1

輸出樣例

2

0

分析:暴力數字範圍給定,暴力搜索其實也不是不可以,但是肯定會超時,網上有很多解法針對的都是數組元素不重復的情況,參考價值也不是很大,後來我自己想了一種方法,需要先進行排序,之後從頭遍歷,需要記錄下來重復數字的重復次數,根據數組下標和重復次數之間的 關系,得到解答。時間復雜度O(n),空間復雜度O(1)

技術分享圖片

代碼:

 1 #include<algorithm>
 2 #include<iostream>
 3 #include<string>
 4 #include<vector>
 5 using namespace std;
 6 int main()
 7 {
 8     int n;
 9     cin >> n;
10     // 打比賽時使用GCC編譯器,務必要將兩個>之間打上空格,以免誤判
11     vector<vector<int> > v(1001,vector<int>(200001,INT_MAX));
12 vector<int> len(1001); 13 for (int i = 0; i < n; i++) 14 { 15 //int m; 16 cin >> len[i]; 17 for (int j = 0; j < len[i]; j++) 18 cin >> v[i][j]; 19 } 20 for (int i = 0; i < n; i++) 21 { 22 int res = 0; 23 int repNum = 0; 24 sort(v[i].begin(), v[i].end()); 25 if (v[i][0] > 0) 26 { 27 cout << 0 << endl; 28 continue; 29 } 30 else 31 { 32 int j = 1; 33 for ( ; j < len[i]; j++) 34 { 35 if (v[i][j] == v[i][j - 1]) 36 { 37 repNum++; 38 continue; 39 } 40 if (v[i][j] != j - repNum) 41 { 42 cout << j - repNum << endl; 43 break; 44 } 45 } 46 if (j == len[i]) 47 cout << len[i] << endl; 48 } 49 } 50 system("pause"); 51 return 0;

尋找一個數組中未出現的最小正整數(數組元素可重復)