• 【面试题40】数组中只出现一次的数字


    【题目描述】

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

    【解决方案】

     1         public static void FindNumsAppearOnce(int[] data)
     2         {
     3             if (data == null || data.Length < 1)
     4                 throw new Exception("Arraty is empty!");
     5 
     6             int numA = 0, numB = 0, numAll = 0;
     7 
     8             foreach (int num in data)
     9                 numAll ^= num;
    10 
    11             int bitOneFlag = GetBitOneFlag(numAll);
    12 
    13             foreach (int num in data)
    14             {
    15                 if ((num & bitOneFlag) == 1)
    16                     numA ^= num;
    17                 else
    18                     numB ^= num;
    19             }
    20 
    21             Console.WriteLine("numA:{0},numB:{1}", numA, numB);
    22         }
    23 
    24         public static int GetBitOneFlag(int num)
    25         {
    26             int count = 0;
    27 
    28             while ((num & 1 << count) == 0)
    29                 count++;
    30 
    31             return 1 << count;
    32         }
  • 相关阅读:
    文件
    drf序列化组件
    drf入门规范
    单例模式
    初识drf
    restful规范
    虚拟环境使用
    vue基础(三)
    vue基础(二)
    作业
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4830990.html
Copyright © 2020-2023  润新知