• 数组中只出现一次的数字


    题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)

    // Find two numbers which only appear once in an array

    // Input: data - an array contains two number appearing exactly once,

    //               while others appearing exactly twice

    // Output: num1 - the first number appearing once in data

    //         num2 - the second number appearing once in data

    staticvoid FindNumsAppearOnce(int[] arr, outint num1, outint num2)

    {

    num1 = num2 = 0;

    if (arr.Length < 2)

    {

    return;

    }

    // get num1 ^ num2

    int resultExclusiveOR = 0;

    for (int i = 0; i < arr.Length; ++i)

    {

    resultExclusiveOR ^= arr[i];

    }

    // get index of the first bit, which is 1 in resultExclusiveOR

    int indexOf1 = FindFirstBitIs1(resultExclusiveOR);

    for (int j = 0; j < arr.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(arr[j], indexOf1) ==1)

    num1 ^= arr[j];

    else

    num2 ^= arr[j];

    }

    }

    // Find the index of first bit which is 1 in num (assuming not 0)

    staticint 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?

    staticint IsBit1(int num, int indexBit)

    {

    num = num >> indexBit;

    return num & 1;

    }

  • 相关阅读:
    转:Windows Socket五种I/O模型
    C++线程池的实现(二)
    C++ 简单 Hash容器的实现
    C++ TrieTree(字典树)容器的实现
    转载:C++线程池的一个实现
    C++用数组实现的静态队列
    C++ 类成员函数作为参数
    C++位操作符总结
    C++简单单例模式
    C++控制程序只运行一个实例
  • 原文地址:https://www.cnblogs.com/matthew228/p/3510986.html
Copyright © 2020-2023  润新知