2

I have two Arrays/ArrayLists of Integer. I want to know the optmized way to find duplicates from two and store into the third one.

Array1 = {1,2,3,6,9,10,15,4};  
Array2 = {4,8,6,5,12,14,1,2,9};  
Result Array= {1,2,3,6,9,10,15,4,8,5,12,14,9}

Regards, Android IT

5
  • Is there a limit on the values of the integers in the array (in addition to the 2^31 limit, of course?) Commented Jan 22, 2012 at 4:11
  • 2
    Are you sure you need optimization here? How much time your current implementation takes? More than 10ms? Commented Jan 22, 2012 at 4:12
  • 1
    Why is 9 in the output twice? Commented Jan 22, 2012 at 4:15
  • Sort. Merge. Erase duplicates. Commented Jan 22, 2012 at 4:16
  • 1
    What Fedor said. Also you can't just say "optimized", you need to qualify what you are trying to optimize. Are these lists going to have 10 elements each? 10 million? Commented Jan 22, 2012 at 4:20

4 Answers 4

2

I would prefer to use Set over HashMap as HashMap need key-value & Sets talks about UNIQUENESS. Sets don't allow duplicates...

Sign up to request clarification or add additional context in comments.

Comments

1

Add elements of both arrays into a HashMap where the value is the number of times the element occurs. Then output it to an array.

Comments

1

You mean, a set union?

List<Integer> array1 = Arrays.asList(1,2,3,6,9,10,15,4);
Set<Integer> set1 = new HashSet<Integer>(array1);

List<Integer> array2 = Arrays.asList(4,8,6,5,12,14,1,2,9);
Set<Integer> set2 = new HashSet<Integer>(array2);

set1.addAll(set2);
List<Integer> resultArray = new ArrayList<Integer>(set1);

Now resultArray contains

[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 14, 15]

Comments

0

The efficient way, sort the arrays (O(n log n)) and iterate through the lowest in both arrays and only select it if is in both (O(n)), otherwise discard.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.