zoukankan      html  css  js  c++  java
  • 牛客网在线编程:n个数中出现次数大于等于n/2的数

    题目描述:

    输入n个整数,输出出现次数大于等于数组长度一半的数。
    输入描述:
    每个测试输入包含 n个空格分割的n个整数,n不超过100,其中有一个整数出现次数大于等于n/2。
    输出描述:
    输出出现次数大于等于n/2的数。
    示例1
    输入

    3 9 3 2 5 6 7 3 2 3 3 3
    输出

    3

    思路:

    每次输入,使用数组a[n]记录n出现的次数,num记录总数。然后判断a[i]是否大于等于num/2。是的话返回i即可
    剑指offer上的思路是保存两个值,当接下来出现的下一个数与前一个数相同时,计数加一,否则减一。当计数为0时,保存下一个数字,并把计数记为1.由于
    要找的数出现的次数比其他数的和还要多,所有要找的数就是最后一次把数设为1的那个数字。

     1 import java.util.*;
     2 public class Chuxiancishu {
     3 
     4     public static void main(String[] args) {
     5         // TODO Auto-generated method stub
     6 //        Scanner sc = new Scanner(System.in);
     7 //        int[] a = new int[100];
     8 //        int num = 0;
     9 //        while(sc.hasNext()){
    10 //            int n = sc.nextInt();
    11 //            a[n]++;
    12 //            num++;
    13 //        }
    14 //        for(int i = 0; i < num; i++){
    15 //            if(a[i]>=(num/2)){
    16 //                System.out.println(i);
    17 //            }
    18 //        }
    19 
    20     Scanner sc = new Scanner(System.in);
    21     int[] a = new int[100];
    22     int i =0;
    23     
    24     while(sc.hasNext()){
    25         a[i]=sc.nextInt();
    26         i++;
    27     }
    28     int count = 0;
    29     int num = a[0];
    30     for(int j = 0; j < i;j++){
    31         //System.out.println(a[j]);
    32         if(a[j]==num) count++;
    33         else if(count>0) count--; 
    34         else num =a[j];
    35     }
    36     System.out.println(num);
    37     }
    38 
    39 }
  • 相关阅读:
    Codeforces 1316B String Modification
    Codeforces 1305C Kuroni and Impossible Calculation
    Codeforces 1305B Kuroni and Simple Strings
    Codeforces 1321D Navigation System
    Codeforces 1321C Remove Adjacent
    Codeforces 1321B Journey Planning
    Operating systems Chapter 6
    Operating systems Chapter 5
    Abandoned country HDU
    Computer HDU
  • 原文地址:https://www.cnblogs.com/zlz099/p/8521348.html
Copyright © 2011-2022 走看看