Advertisement
BojidarDosev

find the duplicates in a list

May 5th, 2025
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.stream.Collectors;
  3.  
  4. public class Main {
  5. public static void main(String[] args) {
  6. Scanner sc = new Scanner(System.in);
  7.  
  8. String s = sc.nextLine();
  9. String[] words = s.split(", ");
  10. int[] nums = new int[words.length];
  11. for (int i = 0; i < words.length; i++) {
  12. nums[i] = Integer.parseInt(words[i]);
  13. }
  14. System.out.println(duplicate(nums));
  15. }
  16.  
  17. public static List<Integer> duplicate(int[] nums) {
  18. List<Integer> duplicatesList = new ArrayList<>();
  19. List<Integer> nonDuplicates = new ArrayList<>();
  20. for (int i = 0; i < nums.length; i++) {
  21. int curNum = nums[i];
  22. if(!nonDuplicates.contains(curNum)) {
  23. nonDuplicates.add(curNum);
  24. }
  25. else if(duplicatesList.contains(curNum)) {
  26. break;
  27. }
  28. else {
  29. duplicatesList.add(curNum);
  30. }
  31. }
  32.  
  33. return duplicatesList.stream().mapToInt(i -> i).boxed().collect(Collectors.toList());
  34. }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement