Single Number II

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

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

 

题意就是,给定一个数组,除了一个元素只出现一次,其他的元素全部出现三次,这个题是在另外一个题的基础上改的,另外一个题是其他元素出现2次,那么用异或操作即可。

如果不用map或set来做,那么只能通过对数字进行操作。

这个题目,既然给定了integer,那么还是利用位操作的思想,把每一位的值(0或1)加起来,对每一位对3取模,余下的就是只出现一次的数。

Talk is cheap>>

   public int singleNumber(int[] A) {

        int[] res = new int[32];

        for (int i = 0; i < 32; i++) {

            for (int j = 0; j < A.length; j++) {

                res[i] += A[j]>>i & 1 ;

            }

            res[i] %= 3;

        }

        int ret = 0;

        for (int i = 0; i < 32; i++) {

            ret |= res[i] << i;

        }

        return ret;

    }

 

你可能感兴趣的:(number)