How to find an element that appears once in an array of elements that appears three times in Java

2 Answers

0 votes
import java.util.Map;
import java.util.HashMap;

class FindElementThatAppearsOnceInArray_Java {
     public static int findElementThatAppearsOnceInArray(int[] arr) {
        Map<Integer, Integer> map = new HashMap<>();
        
        for (int x : arr) {
            map.put(x, map.getOrDefault(x, 0) + 1);
        }

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                return entry.getKey();
            }
        }
        
        return -1;
    }
    public static void main(String[] args) {
        int arr[] = new int[]{3, 5, 5, 2, 7, 3, 2, 8, 8, 3, 2, 5, 8};
        
        System.out.println(findElementThatAppearsOnceInArray(arr));
    }
}



/*
run:

7

*/

 



answered Jul 7, 2024 by avibootz
edited Jul 7, 2024 by avibootz
0 votes
class FindElementThatAppearsOnceInArray_Java {
     public static int findElementThatAppearsOnceInArray(int[] arr) {
        int result = 0;

        for (int i = 0; i < 32; i++) {
            int sum = 0;
            for (final int num : arr) {
                sum += num >> i & 1;
            }
            sum %= 3;
            result |= sum << i;
        }
        
        return result;
    }
    
    public static void main(String[] args) {
        int arr[] = new int[]{3, 5, 5, 2, 7, 3, 2, 8, 8, 3, 2, 5, 8};
        
        System.out.println(findElementThatAppearsOnceInArray(arr));
    }
}



/*
run:

7

*/

 



answered Jul 7, 2024 by avibootz
edited Jul 8, 2024 by avibootz
...