单数II-需要通用解决方案

时间:2019-10-22 15:46:32

标签: java bit-manipulation

我正在尝试解决此问题Leetcode - Single Number ii

  

给定一个非空的整数数组,每个元素出现3次,但一次只出现一次。找到一个。

     

注意:

     

您的算法应该具有线性的运行时复杂度。您可以在不使用额外内存的情况下实现它吗?

     

示例1:

     

输入:[2,2,3,2]   输出:3

下面描述的解决方案来自GeeksforGeeks,他们很好地解释了如何解决此问题,对他们表示敬意。

static int getSingle(int arr[], int n) 
    { 
        int ones = 0, twos = 0; 
        int common_bit_mask; 

        for(int i=0; i<n; i++ ) 
        { 
            /*"one & arr[i]" gives the bits that are there in 
            both 'ones' and new element from arr[]. We 
            add these bits to 'twos' using bitwise OR*/
            twos = twos | (ones & arr[i]); 

            /*"one & arr[i]" gives the bits that are 
            there in both 'ones' and new element from arr[]. 
            We add these bits to 'twos' using bitwise OR*/
            ones = ones ^ arr[i]; 

            /* The common bits are those bits which appear third time 
            So these bits should not be there in both 'ones' and 'twos'. 
            common_bit_mask contains all these bits as 0, so that the bits can  
            be removed from 'ones' and 'twos'*/
            common_bit_mask = ~(ones & twos); 

            /*Remove common bits (the bits that appear third time) from 'ones'*/
            ones &= common_bit_mask; 

            /*Remove common bits (the bits that appear third time) from 'twos'*/
            twos &= common_bit_mask; 
        } 
        return ones; 
    } 

但是我不知所措,如何才能使该解决方案更加通用。假设数字重复5次[2,2,3,2,2,2,2]而不是3次,我该如何调整此解决方案?

感谢您的帮助。

0 个答案:

没有答案