Find a single integer that occurs with even frequency in a given array of ints when all others occur odd with frequency

后端 未结 5 1369
盖世英雄少女心
盖世英雄少女心 2021-02-03 10:26

This is an interview question.

Given an array of integers, find the single integer value in the array which occurs with even frequency. All integers will be

5条回答
  •  攒了一身酷
    2021-02-03 10:59

    I guess we read the task improperly. It asks us "find the single integer value in the array which occurs with even frequency". So, assuming that there is exactly ONE even element, the solution is:

    public static void main(String[] args) {
        int[] array = { 2, 1, 2, 4, 4 };
    
        int count = 0;
        for (int i : array) {
            count^=i;
        }
        System.out.println(count); // Prints 1
    }
    

提交回复
热议问题