• 【面试题29】数组中出现次数超过一半的数字


    【题目描述】

    数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

    【解决方案】

    解法一:基于Partition函数的O(n)算法

    我的代码实现,仅供参考:

     1         public static int MoreThanHalfNum(int[] arr)
     2         {
     3             if (arr == null || arr.Length < 1)
     4                 return 0;
     5 
     6             int mid = arr.Length >> 1;
     7             int start = 0;
     8             int end = arr.Length - 1;
     9 
    10             int index = Partition(arr, start, end);
    11 
    12             while (index != mid)
    13             {
    14                 if (index > mid)
    15                     index = Partition(arr, start, index - 1);
    16                 else
    17                     index = Partition(arr, index + 1, end);
    18             }
    19 
    20             return arr[mid];
    21         }
    22 
    23         public static int Partition(int[] arr, int start, int end)
    24         {
    25             int key = arr[start];
    26 
    27             while (start < end)
    28             {
    29                 while (start < end && arr[end] >= key)
    30                     end--;
    31                 arr[start] = arr[end];
    32 
    33                 while (start < end && arr[start] <= key)
    34                     start++;
    35                 arr[end] = arr[start];
    36             }
    37 
    38             arr[start] = key;
    39 
    40             return start;
    41         }

    解法二:根据数组特点找出O(n)的算法

    我的代码实现,仅供参考:

     1         public static int MoreThanHalfNum(int[] arr)
     2         {
     3             if (arr == null || arr.Length < 1)
     4                 return -1;
     5 
     6             int result = arr[0];
     7             int times = 1;
     8 
     9             for (int i = 1; i < arr.Length; i++)
    10             {
    11                 if (times == 0)
    12                 {
    13                     result = arr[i];
    14                     times = 1;
    15                 }
    16                 else if (arr[i] == result)
    17                     times++;
    18                 else
    19                     times--;
    20             }
    21 
    22             return result;
    23         }
  • 相关阅读:
    Splay 详解
    莫队套值域分块
    浅谈区间众数
    回滚莫队分块
    带修莫队分块
    微服务规划准则
    mysql查询包含逗号的数据,并逗号拆分为多行展现
    python mysql 单连接和连接池简单示例
    代理模式八:装饰者模式
    代理模式七:迭代器模式
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4807495.html
Copyright © 2020-2023  润新知