Title: An integer sequence, the element value may be any number of 0-65535, the same value does not recur. 0 is an exception and can recur.
Please design an algorithm, when you randomly select 5 values from the series, to determine whether these 5 values contiguous.
Attention:
1, 5 numerical values are allowed to be ordered randomly. For example: 8 7 5 0 6;
2, 0 can be used with arbitrary values. For example: 8 7 5 0 6 of 0 can be made into 9 or 4;
3, 0 can appear many times;
4, the complexity of the O (N2) is not scored.
Analysis: Through the analysis you can find that the topic as long as satisfied: except 0 of the maximum number minus removal 0 of the minimum number is less than 4 on the line.
So as long as through a loop on the 5 numbers in addition to the maximum number of 0 and the smallest decimal. After the difference and 4 to make a comparison on the line. Pseudo code is as follows:
1 public boolean isContiguous(int[] array)
2 {
3 int min=-1;
4 int max=-1;
5 for(int i=0;i <array.length;i++)
6 {
7 if(array[i]!=0)
8 {
9 if(min==- 1||min>array[i])
10 {
11 min=array[i];
12 }
13 if(max==-1||max <array[i])
14 {
15 max=array[i];
16 }
17 }
18 }
19 return max-min <=array.length-1;
20 }
Let me use WF4.0 to achieve the solution of this topic, thinking and the above code thinking is consistent.
Process: