-1

The following code snippet works only with duplicated numbers but I'm curious how to solve it with multiple repeated elements.
Input: 1, 2, 5, 5, 5, 8, 9, 11, 12, 1
Output: 1, 5

int[] arr = {1, 2, 5, 5, 5, 8, 9, 11, 12, 1}; 
for (int i = 0; i < arr.length; i++) {
    for (int j = i + 1; j < arr.length; j++) {
        if (arr[i] == arr[j] && i != j) {                  
            System.out.print(arr[j] + " ");
        }
    }
}
Giancarlo Romeo
  • 663
  • 1
  • 9
  • 24
HuserB1989
  • 358
  • 5
  • 16

5 Answers5

3

How about this:

int[] arr = { 1, 2, 5, 5, 5, 8, 9, 11, 12, 1 };

boolean[] seen = new boolean[arr.length];

for (int i = 0; i < arr.length; i++)
{
    if(seen[i]) continue;

    boolean duplicate = false;
    for (int j = i + 1; j < arr.length; j++)
    {
        if (arr[i] == arr[j])
        {
            duplicate = seen[j] = true;
        }
    }
    if(duplicate) 
        System.out.print(arr[i] + " ");
}

Output:

1 5 
RaffleBuffle
  • 5,396
  • 1
  • 9
  • 16
1
int[] arr = {1, 2, 5, 5, 5, 8, 9, 11, 12, 1};

Map<Integer, Integer> map = new HashMap<>();

Arrays.stream(arr).forEach(i -> map.put(i, map.getOrDefault(i, 0) + 1));

map.keySet().stream().mapToInt(i -> i).filter(i -> map.get(i) > 1)
    .forEachOrdered(System.out::println);

You can use a map to store the frequency and then get the numbers with frequency greater than 1.

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
1

You can do it in one pass using sets (linear time complexity)

public static void getRepeatedValues(int[] values)
    {
        Set<Integer> set = new HashSet<>();
        Set<Integer> ans = new HashSet<>();

        for (int value : values)
        {
            if(set.contains(value))
            {
                ans.add(value);
            } else {
                set.add(value);
            }
        }
        System.out.println(ans);
    }
Input:
[1, 2, 5, 5, 5, 8, 9, 11, 12, 1]
Output:
[1, 5]
Bahij.Mik
  • 1,358
  • 2
  • 9
  • 22
1

You can do it using Stream API as follows:

import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        Integer[] arr = { 1, 2, 5, 5, 5, 8, 9, 11, 12, 1 };
        Stream.of(arr).distinct().filter(n -> Collections.frequency(Arrays.asList(arr), n) > 1)
                .forEach(System.out::println);
    }
}

Output:

1
5
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

Here's a simple way to do it with a map.

  • use the value for the key and the count for the value.
  • Just count the occurrences and only print the value when the count == 2
int[] arr = { 1, 2, 5, 5, 5, 8, 9, 11, 12, 1 };

Map<Integer, Integer> dups = new HashMap<>();

for (int i : arr) {
    if (dups.compute(i,(k,v)-> v == null ? 1 : v + 1) == 2) {
            System.out.print(i + " ");
    }
}
System.out.println();

Prints

5 1
WJS
  • 36,363
  • 4
  • 24
  • 39