简体   繁体   中英

Checking if a row of a 2-dimensional array exists anywhere within another array

Say I have the following sorted array:

int[] numbers = {0, 0, 1, 2, 2, 2} .

How can I check if any sub-array of length 3 of numbers exists in the following 2-dimensional array:

int[][] sets = { {0, 0, 0}, {1, 1, 1}, {2, 2, 2} }

In this simple example, the last 3 elements of numbers are clearly contained as an array in sets , but in my actual program, sets will have far more 3 digit permutations of more numbers, but they will all remain length 3, and numbers will always be sorted.

If only the numbers less than ten are allowed, you have up to 1000 possible sequences of three numbers. Encode them as 100*a i +10*a i+1 +a i+2 , and store the index of the first such sequence in a 1001-element array.

In your case numbers would be translated into

0, 0, 1, 2, 2, 2

  1 - 0
 12 - 1
122 - 2
222 - 3

The first column is the index into 1001-element array; the second column is the value that gets placed at that index. The remaining positions of the 1001-element array are set to -1.

To see if numbers contain a three-element sequence construct 100*s 0 +10*s 1 +s 2 number from them, and look it up in the 1001-element array. If you get -1, the sequence is not there; otherwise, you would get the starting index of the desired subsequence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM