int[] m1 = new int[]{1, 2, 3, 4, }; int[] m2 = new int[]{1, 2, 3, 4, 5, 6, }; 

It is necessary to check whether the m2 array contains all the elements of the m1 array

I thought of this solution:

  private Boolean checkRun(int[] a, int[] b) { List<Integer> list_A = new ArrayList<Integer>(); for (int index = 0; index < a.length; index++) { list_A.add(a[index]); } Boolean ret = true; for(int i = 0; i < b.length; i++) { if(list_A.contains(b[i])) { ret = true; } else { // не содержит что то ret = false; } } return ret; } 
  • one
    What is the difficulty? What are the requirements? What exactly did you fail? - pavel
  • After ret = false, do return immediately. - pavel
  • @pavel confess I do not know what to answer the question about the complexity and requirements. It is important for me to understand the principle, in fact the real task looks exactly as described above. A little thought came up with the decision, please tell me if the algorithm is correct? - St. Ivan
  • @pavel leaves that I need to remove return ret; from the end and move it under ret = false; ? Just IDE swears, is it possible to do so? - St. Ivan
  • one
    What is not satisfied with containsAll? - Yura Ivanov

2 answers 2

Try this:

  public boolean isContain(int[] m1, int[] m2){ int count = 0; for (int a : m1) for (int b : m2) if (a == b) { count++; break; } return count == m1.length; } 

Example - 1:

  int[] m1 = new int[]{1, 2, 3, 4}; int[] m2 = new int[]{1, 2, 3, 4, 5, 6}; System.out.println(isContain(m1,m2)); 

Conclusion: true


Example 2:

 int[] m1 = new int[]{1, 8, 3, 4}; int[] m2 = new int[]{1, 2, 3, 4, 5, 2}; System.out.println(isContain(m1,m2)); 

Output: false

  • one
    Thank you, it works. - St. Ivan

1) Create an array of the size equal to the largest of the two (let's call it m3 )

2) Type boolean (all elements = false)

3) In the cycle run, comparing the elements, if the elements are the same - in the cell of the array m3 set to true.

4) At the end, check the m3 array for the fact that all elements are equal to true - if this is the case, then it contains. Otherwise, no.

So I would solve this problem.

But remember, here they will not solve problems from scratch to the end for you. Exactly how to finish course \ diplomas.

  • Slowly, you can do it in O (n + m) instead of O (n * m)) - pavel
  • @pavel if you look at the condition - two simple arrays of 4 and 6 elements. I think this is just a task from the university and not for work, where O itself is not important. - Silento
  • @Asgard is a real-life task, no university, but O really isn't that important, there are not a lot of elements. - St. Ivan