Single Number II

Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Solution

public class Solution {
    public int singleNumber(int[] nums) {
        int[] arr = new int[32];

        int ret = 0;
        for (int i = 0; i < 32; i++) {
            for (int num : nums) {
                arr[i] += (num >> i) & 1;
            }

            arr[i] = arr[i] % 3;
            ret |= arr[i] << i;
        }



        return ret;
    }
}

results matching ""

    No results matching ""