Same array?

Write code to check whether two sorted arrays have the same element, and indicate the time complexity. What about if the arrays are not sorted?

C++:
01 bool sameArray(int* A, int* B, int m, int n)
02 {
03     if(m!=n)
04         return false;
05     for(int i=0;i<m;i++){
06         if(A[i]!=B[i])
07             return false;
08     }
09     return true;
10 }
If they are not sorted,
C++:
01 bool sameArray(int* A, int* B, int m, int n)
02 {
03     map <int,int> S;
04     if(m!=n)
05         return false;
06     for(int i=0;i<m;i++)
07         S[A[i]]=i;
08     for(int i=0;i<m;i++){
09         if(S.find(B[i])==S.end())
10             return false;
11         else
12             S.erase(B[i]);
13     }
14     return true;
15 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s