LoginSignup
0
0

More than 5 years have passed since last update.

【codility】Lesson 4: Counting Elements MissingInteger

Last updated at Posted at 2018-07-06

subject

配列の中で、出現していない一番小さな値(0以上の値)を返す問題
例)
A = [1, 3, 6, 4, 1, 2]の場合 5を返す。
A = [1, 2, 3]の場合 4を返す。
A = [-1, -2]の場合 1を返す。

submit

一発クリア!
image.png

program

Point:Setを使って重複を排除しながらソート
受け取る配列は、「①ソートされていない」「②重複がある」「③ゼロ以下の数値が紛れている」という特性を持っている。vectorの配列をset配列に入れる処理の中で、①ソートしながら、②重複を防ぎながら、③ゼロ以下の数値を省いた配列をつくり、簡単な処理になるようにした。

MissingInteger.cpp
#include<iostream>
#include<vector>
#include <set> 
using namespace std;

int solution(vector<int> &inputArray) {
    set<int> checkArray;

    if (!inputArray.empty()) {
        //sort the inputArray
        for (auto i : inputArray) {
            if(i > 0)
                checkArray.insert(i);
        }
        // if inputArray's elements value less than Zero
        if (checkArray.empty()) {
            return 1;
        }
        else{
            int count = 1;
            for (auto i : checkArray) {
                if (!(i == count))
                    return count;
                count++;
            }
        }
        return (checkArray.size()+1);
    }
    return 1;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0