两个数组结果相减_「算法题目」填满完美数组

这是一篇关于算法问题的博客,讨论如何帮助Ratiorg排列生日礼物雕像,使得每个雕像比前一个大1。通过举例和输入/输出说明,解释了解决此问题的步骤,包括对初始雕像数组排序,计算所需理想数组的长度,然后找出需要额外添加的雕像数量。解法涉及数组操作和数学计算。
摘要由CSDN通过智能技术生成

681637f337c222b3a4590e34c4ad65b7.png

1.Describe:

Ratiorg got statues of differentsize as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.

翻译:一个强迫症小孩希望把他生日收到的礼物按照尺寸从大到小的顺序排好,且后一个礼物的尺寸比前一个数字大「1」,问:最少需要额外添加多少个礼物才能完成小孩想要的效果。

2.Example

For statues = [6, 2, 3, 8], the output should bemakeArrayConsecutive2(statues) = 3.

Ratiorg needs statues of sizes 4, 5 and 7.

给出数组[6,2,3,8],最少需要填三个数字,即:4,5,7.

3.Input/Output

  • [execution time limit] 3 seconds (java)
  • [input] array.integer statues
    An array of distinct non-negative integers.Guaranteed constraints:1 ≤ statues.length ≤ 10,0 ≤ statues[i] ≤ 20.
  • [output] integer
    The minimal number of statues that need to be added to existing statues such that it contains every integer size from an interval [L, R] (for some L, R) and no other sizes.

解法一:

由题可知,一共存在两个数组,一个是小朋友一开始手里的数组,称之为:ExampleArray,另一个数组是小朋友希望完成的理想化数组,称之为:IdealizedArray。

第一步:先将ExampleArray进行排序,然后分别取出Example数组的头和尾,即最大元素和最小元素。然后将其相减,所得到的结果理想化数(IdealizedArray)组应该有的元素数。

第二步:将理想化数组的长度减去一开始给出的例子的长度(Example.length),就得到了最终的结果。

代码如下:

public class Ques03 {
    public static void main(String[] args) {
        int[] arr = new int[]{5,4,6};
        System.out.println(res(arr));


    }

    static int res(int[] array){
        arraySort(array);
        int MinimaAddtion = (array[array.length - 1] - array[0] + 1) - array.length;

        return MinimaAddtion;
    }

    static void arraySort(int[] arr){
        for (int i = arr.length - 1; i >0 ; i--) {
            for (int j = 0; j < i; j++) {
                if (arr[j] > arr[j+1]){
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值