• You have three Arrays…

     Akash  updated 11 months, 3 weeks ago 2 Members · 2 Posts
  • Akash 

    Administrator
    at

    You have three Arrays.

    A = {2, 5, 3, 2, 8,1}

    B = {7, 9, 5, 2, 4, 10, 10}

    C = {6, 7, 5, 5, 3, 7}

    make an array from this three arrays which elements is present in at least two array.

    This question was followed by instead of three arrays. If you have a list of array then what will be the solution? Also what will be the time complexity?

  • Akash 

    Administrator
    at

    package myProject;

    import java.util.ArrayList;

    import java.util.Arrays;

    import java.util.HashSet;

    import java.util.Set;

    public class Stores {

    public static void main(String[] args) {

    Integer[] arr1 = {2, 5, 3, 2, 8,1};

    Integer[] arr2 = {7, 9, 5, 2, 4, 10, 10};

    Integer[] arr3 = {6, 7, 5, 5, 3, 7};

    Set<Integer> set1 = new HashSet<>(Arrays.asList(arr1));

    Set<Integer> set2 = new HashSet<>(Arrays.asList(arr2));

    Set<Integer> set3 = new HashSet<>(Arrays.asList(arr3));

    Set<Integer> set = new HashSet<>();

    set.addAll(Arrays.asList(arr1));

    set.addAll(Arrays.asList(arr2));

    set.addAll(Arrays.asList(arr3));

    ArrayList<Integer> list = new ArrayList<>();

    for (Integer val: set) {

    if(set1.contains(val) && set2.contains(val) && set3.contains(val)) {

    list.add(val);

    }

    else if(set1.contains(val) && set2.contains(val)) {

    list.add(val);

    }

    else if(set2.contains(val) && set3.contains(val)) {

    list.add(val);

    }

    else if(set1.contains(val) && set3.contains(val)) {

    list.add(val);

    }

    }

    System.out.println(list);

    }}

Log in to reply.

Original Post
0 of 0 posts June 2018
Now
KodNest Training New Batch is starting on 02nd November 2020. Attend one week free demo classes.Register Now

New Report

Close