zoukankan      html  css  js  c++  java
  • 剑指Offer27 数组中超过一半的数

     1 /*************************************************************************
     2     > File Name: 27_MoreThanHalfNum.c
     3     > Author: Juntaran
     4     > Mail: JuntaranMail@gmail.com
     5     > Created Time: 2016年08月31日 星期三 16时40分55秒
     6  ************************************************************************/
     7 
     8 #include <stdio.h>
     9 
    10 int FindNum(int* nums, int length)
    11 {
    12     if (nums==NULL || length<=0)
    13         return -1;
    14     
    15     int ret = nums[0];
    16     int count = 1;
    17     for (int i = 0; i < length; ++i)
    18     {
    19         if (nums[i] == ret)
    20             count ++;
    21         else
    22             count --;
    23         if (count == 0)
    24         {
    25             ret = nums[i];
    26             count = 1;
    27         }
    28     }
    29     
    30     // 检验是否正确
    31     int count2 = 0;
    32     for (int i = 0; i < length; ++i)
    33     {
    34         if (nums[i] == ret)
    35             count2 ++;
    36     }
    37     if (count2*2 > length)
    38         return ret;
    39     else
    40         return -1;
    41 }
    42 
    43 int main()
    44 {
    45     int nums[] = {1,2,3,2,2,2,5,4,2};
    46     int length = 9;
    47     int ret = FindNum(nums, length);
    48     if (ret == -1)
    49         printf("Not Find
    ");
    50     else
    51         printf("ret is %d
    ", ret);
    52     
    53     return 0;
    54 }
  • 相关阅读:
    my.cnf
    js日期和毫秒互转
    传送门
    js 十进制转十六进制
    关键字
    常见异常
    Map迭代
    Hibernate

    MySql Host is blocked because of many connection errors; unblock with 'mysqladmin flushhosts' 解决方法
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5826654.html
Copyright © 2011-2022 走看看