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 existingstatues
such that it contains every integer size from an interval[L, R]
(for someL, 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;
}
}
}
}
}