在阵列中增加的数字,直到他们都是平等的 [英] increment numbers in an array until they are all equal

查看:168
本文介绍了在阵列中增加的数字,直到他们都是平等的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该计划的目标是让所有的数字数组中的相同。你必须增加阵列中的所有值除了每次一。那么程序将打印出的,将采取让所有的数字相同的步骤的最小数量。我有什么,我相信这是一个工作解决方案,我只是想使之更有效率,没有任何一个有什么想法?在以下code中的用户的号码到阵列进入初始值,然后计算出所需的步骤的数量

 公共静态无效的主要(字串[] args)抛出NumberFormatException的,IOException异常
{
计数器= 0;
         大小= sc.nextInt();
         输入=新INT [大小]
        对于(INT K = 0; K<大小; k ++)
        {
            输入[K] = sc.nextInt();
        }
        而(!isAllEqual(输入))
        {
            Arrays.sort(输入);
            对于(INT K = 0; K< input.length-1; ​​k ++)
            {
                输入[K] +;
            }
            反++;
        }
        pw.println(柜);公共静态布尔isAllEqual(INT [] A){
    的for(int i = 1; I<则为a.length;我++){
        如果(一个[0]!=一个由[i]){
            返回false;
        }
    }
返回true;
}


解决方案

这可能是更容易,如果你改变了一步成更简单的东西环绕这你的头。如果我们只谈论值之间的平等(即相对的,不是绝对的值),递增和递减的所有的值的一次没什么区别。如果我们改变我们的一步增加所有,但一个,则减一的每个值,我们可以看到,递增所有,但一个相当于递减一个值。

你能想出的步骤,使值相等数量如果步长递减一个值?它应包括通过数组两次在最大,而且没有排序循环。

The goal of this program is to make all numbers in an array the same. You have to increment all values in the array except for one each time. Then the program will print out the minimum number of steps it would take to make all the numbers the same. I have what I believe is a working solution I just want to make it more efficient, does any one have any ideas? In the following code the user enters the initial values for the numbers into the array and then calculates the amount of steps required

public static void main(String[] args) throws NumberFormatException, IOException 
{
counter=0;
         size=sc.nextInt();
         input= new int[size];
        for(int k=0; k<size; k++)
        {
            input[k]=sc.nextInt();
        }
        while(!isAllEqual(input))
        {
            Arrays.sort(input);
            for(int k=0; k<input.length-1; k++)
            {
                input[k]++;
            }
            counter++;
        }
        pw.println(counter);

public static boolean isAllEqual(int[] a){
    for(int i=1; i<a.length; i++){
        if(a[0] != a[i]){
            return false;
        }
    }
return true;
}

解决方案

It might be easier to wrap your head around this if you change the step into something simpler. If we're only talking about equality between the values (i.e. relative, not absolute values), incrementing and decrementing all of the values at once makes no difference. If we change our step to "increment all but one, then decrement every value by one", we can see that incrementing all but one is equivalent to decrementing a single value.

Can you figure out the number of steps to make the values equal if the step is "decrement one value"? It should involve looping through the array two times at max, and no sorting.

这篇关于在阵列中增加的数字,直到他们都是平等的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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