[C # development tips] how to make a non-conforming Element equal to an element closest to it

Source: Internet
Author: User

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

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.