美文网首页
[leetcode/lintcode 题解] 微软面试题:不重复

[leetcode/lintcode 题解] 微软面试题:不重复

作者: SunnyZhao2019 | 来源:发表于2020-06-29 18:48 被阅读0次

    给定一个数组 a[],其中除了2个数,别的数都出现了2次,找到不重复的2个数并返回。

    在线评测地址: lintcode领扣

    Example 1:

    Input: a =[1,2,5,5,6,6]
    Output: [1,2]
    Explanation:
    In addition to the 1 and 2 other numbers appear twice, so return [1, 2]
    Example 2:

    Input: a=[3,2,7,5,5,7]
    Output:[2,3]
    Explanation:
    In addition to the 2 and 3 other numbers appear twice, so return [2, 3]

    【题解】

    从头到尾依次异或数组中的每一个数字,得到两个只出现一次的数字的异或结果,在结果数字中找到第一个为1的位的位置,记为第N位,以第N位是不是1为标准把原数组中的数字分成两个子数组,第一个子数组中每个数字的第N位都为1,而第二个子数组的每个数字的第N位都为0。

    public class Solution {
    
        /**
         * @param a: the array
         * @return: the two numbers that are not repeated
         */
        public List<Integer> theTwoNumbers(List<Integer> a) {
            // Write your code here
            int length = a.size();
            List<Integer> res = new ArrayList<Integer>();
            if(length < 2) {
                return res;
            }
    
            // get num1 ^ num2
            int resultExclusiveOR = 0;
            for(int i = 0; i < length; ++i) {
                resultExclusiveOR ^= a.get(i);
            }
    
            // get index of the first bit, which is 1 in resultExclusiveOR
            int indexOf1 = FindFirstBitIs1(resultExclusiveOR);
    
            int num1 = 0, num2 = 0;
            for(int j = 0; j < length; ++j) {
                // divide the numbers in data into two groups,
                // the indexOf1 bit of numbers in the first group is 1,
                // while in the second group is 0
                if(IsBit1(a.get(j), indexOf1)) {
                      num1 ^= a.get(j);
                }
                else {
                      num2 ^= a.get(j);
                }
            }
            res.add(num1);
            res.add(num2);
            return res;
        }
    
        // Find the index of first bit which is 1 in num (assuming not 0)
        private int FindFirstBitIs1(int num) {
            int indexBit = 0;
            while (((num & 1) == 0) && (indexBit < 32)) {
                num = num >> 1;
                ++ indexBit;
            }
            return indexBit;
        }
    
        // Is the indexBit bit of num 1?
        private boolean IsBit1(int num, int indexBit) {
            num = num >> indexBit;
            return (num & 1) == 0 ? false : true;
        }
    }
    

    更多语言代码参见:leetcode/lintcode题解

    相关文章

      网友评论

          本文标题:[leetcode/lintcode 题解] 微软面试题:不重复

          本文链接:https://www.haomeiwen.com/subject/rgsafktx.html