Java learning manuals :( data structures and algorithms - array) how to determine whether the value of a continuous array adjacent?

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/MaybeForever/article/details/102452419

Problem Description:

A sequence of array elements may be any of a number of values ​​of 0 to 65535, the same value will not be repeated. 0 is the exception, it can be repeated. Design of an algorithm, when selecting an array of five values ​​from the random sequence, it is determined whether five adjacent consecutive values. Note that the following four points:

  • 1,5 value allowed to be out of order, for example, {8,7,5,0,6}.
  • 2,0 can be any number wildcard, for example, {8,7,5,0,6} is 0 or 4 may be wildcarded 9.
  • 3,0 can appear multiple times.
  • 4, all-0 count continuously, only one non-zero count continuously.

method one:

If there is no 0, to make up a continuous series, the maximum and minimum gap must be 4, there is zero, as long as the gap between the maximum and minimum values ​​of less than 4 on it, it should identify the number of columns Africa 0 the maximum and minimum non-zero, the time complexity is O (n), if the non-zero maximum - minimum non-0 <= 4, then the five adjacent consecutive values, otherwise, the adjacent discontinuous. Thus the time complexity of the algorithm is O (n).

The method of one code is as follows:

package com.haobi;

public class Test29 {
	public static void main(String[] args) {
		int[] array = {8,7,5,0,6};
		System.out.println(IsContinuous(array));
	}
	
	public static Boolean IsContinuous(int[] a) {
		int n = a.length;
		int min=-1,max=-1;
		//遍历数组求出非0最大值和最小值
		for(int i=0;i<n;i++) {
			if(a[i]!=0) {
				if(min>a[i] || min==-1) {
					min = a[i];
				}
				if(max<a[i] || max==-1) {
					max = a[i];
				}
			}
		}
		if(max-min > n-1) {//题目约束条件
			return false;
		}else {
			return true;
		}
	}
}

Program output results are as follows:

true

Guess you like

Origin blog.csdn.net/MaybeForever/article/details/102452419