Advertisement
Guest User

missing-number

a guest
Jan 21st, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. //https://leetcode.com/problems/missing-number/
  2.  
  3. #include <cstdio>
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7. using namespace std;
  8.  
  9. class Solution {
  10. public:
  11.   int missingNumber(vector<int>& nums) {
  12.     if (nums.empty())
  13.       return 0;
  14.    
  15.     int missing_num = 0;
  16.     int max = nums.at(0);
  17.     // find max value
  18.     for (vector<int>::iterator it=nums.begin(); it != nums.end(); ++it){
  19.       if (max < *it)
  20.         max = *it;
  21.     }
  22.  
  23.     // create arr from 0 to max+1
  24.     int *tmp_arr = new int[max+2];
  25.     for (int i=0; i<= max+1; i++){
  26.       tmp_arr[i]=i;
  27.     }
  28.  
  29.     // replace every found entry with -1
  30.     for (int i=0; i<nums.size(); i++){
  31.       tmp_arr[nums[i]] = -1;
  32.     }
  33.  
  34.     // find first none -1 entry
  35.     for (int i=0; i<= max+1; i++){
  36.       if (tmp_arr[i] != -1){
  37.         missing_num = i;
  38.         break;
  39.       }
  40.     }
  41.  
  42.     delete[] tmp_arr;
  43.     return missing_num;
  44.   }
  45. };
  46.  
  47. int main() {
  48.   int fin;
  49.  
  50.   Solution sol;
  51.   vector<int> myvector;
  52.   for (int i=0;i<=10;i++) {
  53.     if (i != 4)
  54.       myvector.push_back(i);
  55.   }
  56.  
  57.   cout << "vector: ";
  58.   for (int i=0; i<myvector.size(); i++){
  59.     cout << myvector.at(i) << " ";
  60.   }
  61.   cout << endl;
  62.  
  63.   fin = sol.missingNumber(myvector);
  64.   cout << "missing: " << fin << endl;
  65.  
  66.   cin >> fin;
  67.   return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement