zoukankan      html  css  js  c++  java
  • LeetCode 169

    Majority Element

    Given an array of size n, find the majority element.
    The majority element is the element that appears more than ⌊ n/2 ⌋ times.

    You may assume that the array is non-empty and the majority element always exist in the array.

     1 /*************************************************************************
     2     > File Name: LeetCode169.c
     3     > Author: Juntaran
     4     > Mail: Jacinthmail@gmail.com
     5     > Created Time: Tue 10 May 2016 02:40:25 PM CST
     6  ************************************************************************/
     7  
     8 /*************************************************************************
     9 
    10     Majority Element
    11     
    12     Given an array of size n, find the majority element. 
    13     The majority element is the element that appears more than ⌊ n/2 ⌋ times.
    14 
    15     You may assume that the array is non-empty and the majority element always exist in the array.
    16 
    17  ************************************************************************/
    18 
    19 #include<stdio.h>
    20 
    21 int majorityElement( int* nums, int numsSize )
    22 {
    23     int ret = nums[0];
    24     int count = 1;
    25     
    26     int i;
    27     for( i=1; i<numsSize; i++ )
    28     {
    29         if( ret == nums[i] )
    30         {
    31             count ++;
    32         }
    33         else
    34         {
    35             count --;
    36         }
    37         if( count == 0 )
    38         {
    39             ret = nums[i];
    40             count ++;
    41         }
    42     }
    43     return ret;
    44 }
    45 
    46 int main()
    47 {
    48     int nums[] = {3,2,3};
    49     int numsSize = 3;
    50 
    51     int ret = majorityElement( nums, numsSize );
    52     printf("%d
    ", ret);
    53 
    54     return 0;
    55 }
  • 相关阅读:
    什么是垃圾回收??
    Nginx教程3:SSL设置
    Nginx教程2:性能
    Nginx教程1:基本概念
    iOS 设计中-- 自定义-- 评星图标的方法
    iOS设计中对Xcode设置中创建PCH文件的过程
    iOS设计中不同屏幕适配的方法-登陆界面
    iOS设计之--OC学习总结之延展类目协议
    iOS 最新版 CocoaPods 的安装流程介绍
    iOS基本UI控件总结
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5479091.html
Copyright © 2011-2022 走看看