Given two arrays of integers, find which elements in the second array are missing from the first array.
Example:
Input: n=6, arr[]={7,2,5,3,5,3}, m=8, arr[]={7,2,5,4,6,3,5,3}
Output: 4 6
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class MissingNumbers {public static void main(String[] args) {int[] arr = { 7, 2, 5, 3, 5, 3 };int[] brr = { 7, 2, 5, 4, 6, 3, 5, 3 };int[] result = missingNumbers(arr, brr);System.out.println(Arrays.toString(result));}private static int[] missingNumbers(int[] arr, int[] brr) {int f[] = new int[10001];for (int i = 0; i < brr.length; i++)f[brr[i]]++;for (int i = 0; i < arr.length; i++)f[arr[i]]--;List<Integer> res = new ArrayList<Integer>();for (int i = 1; i < 10001; i++)if (f[i] > 0)res.add(i);return res.stream().mapToInt(Integer::intValue).toArray();}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> missingNumbers(vector<int> arr, vector<int> brr){int f[10001] = {0};for (int i = 0; i < brr.size(); i++)f[brr[i]]++;for (int i = 0; i < arr.size(); i++)f[arr[i]]--;vector<int> res;for (int i = 1; i < 10001; i++)if (f[i])res.push_back(i);return res;}int main(){int n = 6;vector<int> arr = {7, 2, 5, 3, 5, 3};int m = 8;vector<int> brr = {7, 2, 5, 4, 6, 3, 5, 3};vector<int> result = missingNumbers(arr, brr);for (int i = 0; i < result.size(); i++){cout << result[i];if (i != result.size() - 1){cout << " ";}}cout << "\n";return 0;}
No comments:
Post a Comment