zoukankan      html  css  js  c++  java
  • 数组中数目最多的三个数 2.3

    是数组中超过一半数目问题的升级版,但万变不离其中

       

    声明一个time数组和candidate数组,长度为3,分别存放三个数的次数和数字

       

    首先次数声明为0,数字声明为不存在的数,这里暂时声明为-1,其实应该声明为一个不存在的数字

       

    然后遍历数组

       

    如果该数是第一个candidate,第一个candidatetime++

    如果是第二个,那么第二个time++;

       

    然后也判断三个candidatetime是否达到0,如果达到,将更新candidate,更新为当前数字

       

    最后返回candidate数组

       

    package moreThanHalfNum29;

       

    public class MostThreeNum29 {

       

    static int[] Find(int[] a) {

    int N = a.length;

    int ID_NULL = -1;

    ;// 定义一个不存在的ID

    int[] nTimes = new int[3];

    int i;

    nTimes[0] = nTimes[1] = nTimes[2] = 0;

    int[] candidate = new int[3];

    candidate[0] = candidate[1] = candidate[2] = ID_NULL;

    for (i = 0; i < N; i++) {

    if (a[i] == candidate[0]) {

    nTimes[0]++;

    } else if (a[i] == candidate[1]) {

    nTimes[1]++;

    } else if (a[i] == candidate[2]) {

    nTimes[2]++;

    } else if (nTimes[0] == 0) {

    nTimes[0] = 1;

    candidate[0] = a[i];

    } else if (nTimes[1] == 0) {

    nTimes[1] = 1;

    candidate[1] = a[i];

    } else if (nTimes[2] == 0) {

    nTimes[2] = 1;

    candidate[2] = a[i];

    } else {

    nTimes[0]--;

    nTimes[1]--;

    nTimes[2]--;

    }

    }

    return candidate;

    }

       

    public static void main(String[] args) {

    // TODO Auto-generated method stub

    int[] a = { 2, 2, 3, 3, 4, 5, 5, 6 };

    int[] result = Find(a);

    for (int i = 0; i < result.length; i++) {

    System.out.println(result[i]);

    }

    }

       

    }

  • 相关阅读:
    PHP发送邮件标题乱码的解决
    PHP方法之 mb_substr
    HTML 文件类表单元素如何限制上传类型,Accept属性设置
    Jquery 自定义动画同步进行如何实现?
    王小胖之 Base64编码/解码
    王小胖之 URL编码和解码
    王小胖之中文汉字转拼音
    跟左神学算法7 进阶数据结构(哈希相关)
    操作系统复习笔记1
    计算机网络复习笔记2
  • 原文地址:https://www.cnblogs.com/keedor/p/4394636.html
Copyright © 2011-2022 走看看