问题描述:

求一个数组里最大值和最小值之间缺省的数,例如 int arrDemo = {1, 3, 7};  那么就要输出最小值1和最大值7之间缺少的数字2,4,5,6

编程思想:

假设给定的数组名字为A

<1>一次遍历A   求出A里最大数max和最小数min

arrDemo里max = 7    min = 1

<2>新建一个数组B,长度len为max-min

<3>遍历数组B,使B[0]=min   B[len-1] = max-1

B = {1, 2, 3, 4, 5, 6};

<4>遍历数组A,如果A里的元素符合大于min   小于max, 就将B里对应的位置改为max+1

遍历完后,B = {8, 2, 8, 4, 5, 6}

<5>遍历数组B,如果值不为max+1,就是缺少的元素,输出

输出B中不为8的元素,即为2, 4, 5, 6

代码如下,有更好的思路欢迎大家在评论区留言讨论

 1 package test;
 2 
 3 public class Test {
 4 
 5     static int[] array = {
 6             -10,0,3,3,9
 7     };
 8     
 9     private static void printEmptyItems(int[] array) {
10         if (array == null) {
11             return;
12         }
13         
14         int min = array[0];
15         int max = array[0];
16         for (int i = 0; i <array.length; ++i) {
17             if (array[i] > max) {
18                 max = array[i];
19             }
20             if (array[i] < min) {
21                 min = array[i];
22             }
23         }
24         
25         int newLength = max - min;
26         System.out.println("min:" + min + "max:" + max + "new length is:" + newLength);
27         int []newArray = new int[newLength];
28         for (int i = 0; i < newLength; i++) {
29             newArray[i] = min + i;
30         }
31         
32         for (int i = 0; i < array.length; ++i) {
33             if (array[i] >= min && array[i] < max) {
34                 newArray[array[i] - min] = max + 1;
35             }
36         }
37         
38         for (int i = 0; i < newLength; i++) {
39             if (newArray[i] != max + 1) {
40                 System.out.println("empty item is:" + newArray[i]);
41             }
42         }
43     }
44     
45     public static void main(String[] args) {
46         // TODO Auto-generated method stub
47         printEmptyItems(array);
48     }
49 
50 }