1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class OddOccurrencesInArray_lesson02 { public static void main(String[] args) { solution(new int[]{2, 2, 3, 3, 4}); solution(new int[]{9,3,9,3,9,7,9}); solution(new int[]{42}); } static int solution(int[] A) { Map<Integer, Integer> m = new HashMap<>(); Arrays.sort(A); for(int i=0; i<A.length; i++){ if(!m.containsKey(A[i])){ m.put(A[i], 1); }else { int mValue = m.get(A[i]); m.put(A[i], mValue+1); } } int answer = 0; for(Integer key : m.keySet()){ int value = m.get(key); if(value % 2 != 0){ answer = key; } } System.out.println("answer = " + answer); return answer; } }
|