Проверить, равны ли два массива или нет ?? например: {1,2,3,4,5} == {4,5,3,2,1} - PullRequest
0 голосов
/ 28 мая 2020

Есть ли проблема с этим подходом? или это нормально? мы должны определить, равны ли 2 массива, как в цифрах в них, и их частоты должны быть одинаковыми независимо от их порядка.

#include<bits/stdc++.h>
using namespace std;

main(){

int t,n,i,in;
vector<int> x;

cin>>t;
while(t--){

   unordered_map<int,int> a,b;
   cin>>n;

   for(i=0;i<n;i++){
       cin>>in;
       x.push_back(in);
       a[in]++;
   }

   for(i=0;i<n;i++){
       cin>>in;
       b[in]++;
   }

   for(i=0;i<n;i++){

       if(b.find(x[i]) == b.end()){
           cout<<"0"<<endl;
           goto x;
       }

       if(a[x[i]] != b[x[i]]){
           cout<<"0"<<endl;
           goto x;
       }
   }

   cout<<"1"<<endl;
   x : ;
   }
}

1 Ответ

0 голосов
/ 28 мая 2020

Я не знаю, насколько вы новичок в C ++, поэтому вот возможное решение с несколькими пояснениями.

#include <map>
#include <vector>
#include <iostream>

//Avoid using namespace std as it can cause problems with conflicts of names
//and other sorts of nasty issues
using std::cout;
using std::cin;
using std::map;
using std::vector;
using std::endl;

//By using an ordered map you can more easily compare them
//The arguments are passed as const (you will never modify them)
//and also as reference (&) since you don't need to copy them.
bool CheckIfEqual (const vector<int> & V1, const vector<int> & V2) {
    //If the vectors don't have the same size you can just return false
    if (V1.size() != V2.size()) {
        return false;
    }
    map <int, size_t> M1;
    map <int, size_t> M2;
    //This type of loop goes through all elements of the vector and 
    //either creates a corrisponding value in the map or, if it is
    //already present, it increases it to accout for repetitions.
    //Map is automatically sorted.
    for (auto & Elem : V1) {
        M1[Elem]++;
    }
    for (auto & Elem : V2) {
        M2[Elem]++;
    }
    return M1 == M2;
}

//The main function is used to provide some examples
int main () {
    //Expected output: true
    vector<int> V1 {1, 2, 3, 4, 5};
    vector<int> V2 {1, 2, 3, 4 ,5};
    cout << CheckIfEqual(V1, V2) << endl;

    //Expected output: true
    V1 = {1, 2, 3, 4, 5};
    V2 = {5, 3, 2, 1 ,4};
    cout << CheckIfEqual(V1, V2) << endl;

    //Expected output: false
    V1 =  {1, 2, 3};
    V2 =  {5, 3};
    cout << CheckIfEqual(V1, V2) << endl;

    //Expected output: false
    V1 =  {1, 2, 3, 4, 5};
    V2 = {5, 3, 2, 1 ,1};
    cout << CheckIfEqual(V1, V2) << endl;

    //Expected output: true
    V1 = {1, 5, 5, 4, 5};
    V2 = {5, 5, 5, 1 ,4};
    cout << CheckIfEqual(V1, V2) << endl;
}

Результат:

1
1
0
0
1

Также будьте очень осторожны при использовании goto, он устарел и полезен только тогда, когда вам нужно выпрыгнуть из многих вложенных циклов. однажды. Простая break работала бы лучше.

...