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


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

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

    如果下一个相同则次数加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 }
  • 相关阅读:
    初识DJango框架
    web框架基础
    前端——JavaScript
    前端——css(下)
    前端——css(上)
    前端——html
    spring注解
    spring boot 详解(1)spring boot +mybatis+mysql+jsp
    spring 事务控制
    maven pom文件管理
  • 原文地址:https://www.cnblogs.com/zfc-java/p/7666827.html
Copyright © 2020-2023  润新知