zoukankan      html  css  js  c++  java
  • 找数组中重复次数超过数组长度一半的元素

    找数组中重复次数超过数组长度一半的元素

    进行标号的遍历数组,因为某个元素超过一半,保存数组中的数字和其出现次数 

    如果下一个相同则次数加1,不同减1,如果次数变为0则保存数字为下一个数,最终情况是出现次数最多的元素 

    最终保存下来,然后检查是否超过半数。

     1 package cn.com.zfc.example;
     2 
     3 /**
     4  * 找数组中重复次数超过数组长度一半的元素
     5  * 
     6  * @author zfc
     7  *
     8  */
     9 public class MoreHalfArray {
    10     public static void main(String[] args) {
    11         int[] array = { 3,1,2,3,2 };
    12         moreThanHalf(array);
    13     }
    14 
    15     public static void moreThanHalf(int[] array) {
    16         int result = array[0];
    17         int time = 0;
    18         for (int i = 0; i < array.length; i++) {
    19             if (time == 0) {
    20                 result = array[i];
    21                 time = 1;
    22             } else if (array[i] == result) {
    23                 time++;
    24             } else {
    25                 time--;
    26             }
    27         }
    28         System.out.println(result);
    29         
    30         if (confirmNum(array, result)) {
    31             System.out.println("exsit this element is:" + result);
    32         } else {
    33             System.out.println("not found this element!");
    34         }
    35     }
    36 
    37     // 判断此元素的重复次数是否大于数组长度的一半
    38     public static boolean confirmNum(int[] array, int number) {
    39         int time = 0;
    40         for (int i = 0; i < array.length; i++) {
    41             if (array[i] == number) {
    42                 time++;
    43             }
    44         }
    45         if (time * 2 > array.length) {
    46             return true;
    47         } else {
    48             return false;
    49         }
    50     }
    51 }
  • 相关阅读:
    1111---9999的变换
    Mac命令行
    iOS 支付 [支付宝、银联、微信]
    ShareSDK适配iOS 9系统
    iOS中Size Classes的理解与使用
    iOS9网络请求升级 之前的不显示图片 破解方法
    iOS9中友盟分享不能使用 破解方法
    iOS9中错误信息信息是引入的一个第三方库不包含bitcode
    iOS 六大手势
    下拉刷新和上拉加载的原理
  • 原文地址:https://www.cnblogs.com/zfc-java/p/7666827.html
Copyright © 2011-2022 走看看