zoukankan      html  css  js  c++  java
  • 数组中只出现一次的数字

    题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是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;

    }

  • 相关阅读:
    WinForm换行
    aspx获取页面间传送的值
    Response.BinaryWrite()方法输出二进制图像
    Jquery删除table的行和列
    WinForm DataGridView控件隔行变色
    IE中table的innerHTML无法赋值
    C#为IE添加可信任站点
    静态代码检查
    第三方开源小工具
    查看sql server 服务器内存使用情况
  • 原文地址:https://www.cnblogs.com/matthew228/p/3510986.html
Copyright © 2011-2022 走看看