I. Problem Description
Today, I saw such a problem in the MSDN forum and thought it was very hard to train my thinking skills. So I recorded it as a backup. The requirements for the questions are as follows:
Assume that there is a string array {"0", "0", "1", "2", "3", "0", "4", "0 ", "0"}, how to find the element that makes 0 equal to the nearest and not 0. If there are two elements closest to 0, it is equal to the previous element, the array {"1", "1", "1", "2", "3", "4 ", "4", "4 "}
II. Implementation ideas
The implementation idea here is taken from the reply of zjyh16 in the Forum. The implementation idea is as follows:
- 1. First, traverse the numbers in the array. If the current value is not "0", add the valuesResult Array. Otherwise, process it.
- 2. when the value is not "0", use an "equal distance comparison" method to locate the left and right values in the same distance, check whether the value on the left is "0". If yes, Skip. If notResult ArrayTo replace the current value in.
- 3. the maximum distance (j in the Code) is the length of the array minus 1. During traversal, note that the value of I-j is not less than 0, and the value of I + j is less than the length of the array.
The specific implementation code is:
[] S = String [] {, [] result = [(I =; I <s. Length; I ++ (s [I]! = (J =; j <s. Length; j ++ (I-j> = (s [I-j]! = S [I-(I + j <(s [I + j]! = S [I + (I =; I <result. Length; I ++
Iii. Running results