zoukankan      html  css  js  c++  java
  • 在数组中查找一个仅出现2次的数

    题目:一个存放很多无符号整数的有序数组,数组元素的数量超过整数的表示范围,在数组中寻找出一个仅出现两次的数。

     1 #include <stdio.h>
     2 
     3 int FindDouble(const unsigned int *pArr, __int64 len, unsigned int *result)
     4 {
     5     if (NULL == pArr || NULL == result || 0 >= len)
     6     {
     7         return -1;  //参数错误
     8     }
     9 
    10     const unsigned int *phead = pArr; //位于后面的指针
    11     const unsigned int *ptail = pArr; //位于前面的指针
    12     while (ptail != pArr + len)
    13     {
    14         //指针指向同一位置,则为指针向后移动一个
    15         if (phead == ptail)
    16         {
    17             ptail++;
    18             continue;
    19         }
    20 
    21         //考虑数组:2 2 2 2 3 的情况
    22         while (ptail != pArr + len && *phead == *ptail) ptail++;
    23 
    24         //头尾指针相减等于*phead在数组中的次数
    25         if (2 == ptail - phead)
    26         {
    27             *result = *phead;
    28             return 0;
    29         }
    30         else
    31         {
    32             phead = ptail;
    33         }
    34     }
    35     if (2 == ptail - phead) //考虑 数组为:2 2 的情况
    36     {
    37         *result = *phead;
    38         return 0;
    39     }
    40     return 1;  //数组中没有这样的数
    41 }
    42 
    43 int main(void)
    44 {
    45     unsigned int arr[] = { 1, 1, 1, 2, 2, 2, 2, 2, 3, 4, 5, 6, 7, 7 };
    46     unsigned int num = 0;
    47     if (0 == FindDouble(arr, sizeof(arr) / sizeof(unsigned int), &num))
    48     {
    49         printf("%d
    ", num);
    50     }
    51     return 0;
    52 }
  • 相关阅读:
    DataGird导出EXCEL的几个方法
    csv文件与DataTable互相导入处理
    LeetCode 345
    LeetCode 168
    LeetCode 344
    LeetCode 342
    LeetCode 343
    LeetCode 326
    LeetCode 338
    LeetCode 319
  • 原文地址:https://www.cnblogs.com/yongqiang/p/6086822.html
Copyright © 2011-2022 走看看