爪哇 - 寻找一个有序数组最少见的整数 [英] Java - Finding the least common integer in a sorted array

查看:128
本文介绍了爪哇 - 寻找一个有序数组最少见的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被分配了功课规划问题,我在静止不动。我已经搜索了几个小时试图今天找到一个答案,好像它从来没有被问过这里。基本上,我需要找到阵列模式相反。下面是我被要求找到解决的问题:

I was assigned a programming problem for homework, and I am at a stand-still. I have searched for hours today trying to find an answer, and it seems like it's never been asked on here. I basically need to find the reverse of the mode of the array. Here is the question I was asked to find the solution to:

LeastFrequent - 输出其中至少经常沿发生整数
  其发生从10整数输入列表计数
  System.in。如果列表中的多个整数至少发生频繁,
  输出至少经常发生的任何整数。命名类
  LeastFrequent。你可以假设所有的10个整数的范围是
  -100到100(含)。

LeastFrequent - Output the integer which occurs least frequently along with its occurrence count from a list of 10 integers input from System.in. If multiple integers in the list occur least frequently, output any integer that occurs least frequently. Name your class LeastFrequent. You can assume that all 10 integers are in the range -100 to 100 inclusive.

下面是code我到目前为止有:

Here is the code I have so far:

package leastfrequent;
import java.util.*;

public class LeastFrequent
{
    private static int[] arr = new int[10];
    private static int minValue;
    private static int minCount;

    public static void leastCommon()
    {
        for(int i = 0; i < arr.length; i++)
        {
            int count = 0;

            for(int j = 0; j < arr.length; j++)
            {
                if(arr[j] == arr[i]) 
                {
                    count++;
                }
            }

            if(count > minCount)
            {
                minCount = count;
                minValue = arr[i];
            }
        }
    }

    public static void main(String[] args)
    {
        Scanner stdin = new Scanner(System.in);
        System.out.print("numbers: ");

        for(int i = 0; i < arr.length; i++)
        {
            arr[i] = stdin.nextInt();
        }

        Arrays.sort(arr);
        leastCommon();

        System.out.println("least frequent: " + minValue + " occurs " + minCount + " times");
    }
}

基本上,我想如果我能找到的模式,我可以扭转这种算法并找到最不常见的,但是,这并不工作,因为它总是读数为零。

Basically I figured if I could find the mode, I could reverse that algorithm and find the least common, but that doesn't work because it always reads zero.

有没有人有什么想法?

请帮助!

推荐答案

两个变化:


  1. 初始化 minCount 与最大的指数,即10为:

  1. Initialize minCount with biggest index i.e. 10 as:

private static int minCount = 10;


  • 更改如果来比较小于更大不是为:

    if(count < minCount){
    


  • 这样,您将修改 minCount 较低的计数,当你收到下occurence计数和年底,将有最少。

    This way you will change the minCount with lower count, whenever you receive the lower occurence count and in the end, it will have the least.

    我想,剩下的就是罚款。希望这个修复程序。

    I think, rest is fine. Hope this fixes your program.

    这篇关于爪哇 - 寻找一个有序数组最少见的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆