LOVE BABBAR 450 Q SHEET SOLUTIONS - ARRAY SOLUTIONS
5 - MOVE ALL NEGATIVE ELEMENTS OF ARRAY TO ONE SIDE OF ARRAY
A. WITH EXTRA SPACE ALLOWED
Q1- Given an unsorted array having both negative and positive integers. The task is place all negative element at the end of array without changing the order of positive element and negative element.
S1
void segregateElements(int arr[],int n)
{
int temp[n];
int j = 0;
for(int i = 0; i < n; i++){
if(arr[i] > 0)
temp[j++] = arr[i];
}
if(j == n || j == 0)
return;
for(int i = 0; i < n; i++){
if(arr[i] < 0)
temp[j++] = arr[i];
}
memcpy(arr, temp, sizeof(temp));
}
6- UNION AND INTERSECTION OF 2 ARRAYS
6A- UNION OF 2 ARRAY
S1- USING SET
int doUnion(int a[], int n, int b[], int m) {
set<int>s;
for(int i = 0; i < n; i++){
s.insert(a[i]);
}
for(int i = 0; i < m; i++){
s.insert(b[i]);
}
return s.size();
}
6B - INTERSECTION OF 2 ARRAYS
S1- USING SET
int NumberofElementsInIntersection (int a[], int b[], int n, int m )
{
int cntIntersect = 0;
set<int>s;
set<int>in;
for(int i = 0; i < n; i++){
s.insert(a[i]);
}
for(int i = 0; i < m; i++){
if(s.count(b[i]) == 1 && in.count(b[i]) == 0){
in.insert(b[i]);
cntIntersect++;
}
}
return cntIntersect;
}
No comments:
Post a Comment