LoginSignup
1
0

More than 5 years have passed since last update.

【codility】Lesson 4: Counting Elements PermCheck

Posted at

subject

Lesson 4: Counting Elements PermCheck
順列(Permutation)の配列になっているかどうかをチェックする問題。
例)
A = {4, 1, 3, 2}ならば1を返す
A = {4, 1, 3}ならば0を返す

submit

下記の項目がどうしても解決できない。
antiSum2 :total sum is correct, but it is not a permutation, N = ~100,000

image.png

program

1~Nまでの各数値の足し算、及び掛け算の総数をあらかじめ計算し、与えられた配列の全ての値の足し算、及び掛け算の総数も計算し、それらの差分がゼロならば、それは順列であると定義した。
そうすると、
A = {1, 4, 1} の場合
totalSum = 6, arrSum = 5, totalMultiple = 6, arrMultiple = 4となり、順列ではないとなる。

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

int solution(vector<int> &A) {
    int totalSum = 0;
    int arrSum = 0;
    unsigned long totalMultiple = 1;
    unsigned long arrMultiple = 1;
    int sumCount = A.size();

    if (!A.empty()) {

        while (sumCount) {
            totalSum += sumCount;
            if(sumCount != 0)
                totalMultiple *= sumCount;
            sumCount--;
        }
        for (auto i : A) {
            if(i <= (int)A.size()){
                arrSum += i;
                arrMultiple *= i;
            }else{
                return 0;
            }
        }
        if ((totalSum - arrSum) + (totalMultiple - arrMultiple))
            return 0;
        return 1;
    }
    return 0;
}
1
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
1
0