849 maximize Distance to Closest person

Source: Internet
Author: User

In a row seats of, 1 represents a person sitting in this seat, and 0 represents that the seat is empty.

There is at least one empty seat, and at least a person sitting.

Alex wants to sit in the seat such, the distance between him and the closest person to him are maximized.

Return this maximum distance to closest person.

Example 1:

2explanation:if Alex sits in the second open seat (Seats[2]) and then the closest person have distance 2.If Alex sits in any Other open seat, the closest person had distance 1.Thus, the maximum distance to the closest person is 2.

Example 2:

3explanation:if Alex sits in the last seat, the closest person is 3 seats away. The maximum distance possible, so the answer is 3.

Note:

    1. 1 <= seats.length <= 20000
    2. seatscontains only 0s or 1s, at least one 0 , and at least one 1 .
//pointer:time:o (n), Space:o (1)//I record 0 position, J record 1 position, three cases should be considered in place1. [0,0,0,0,1] 0 at the beginning 2. [1,0,0,0,1] 0 in the middle 3. [1,0,0,0,0] 0 in the result  Public intMaxdisttoclosest (int[] seats) {        if(Seats = =NULL|| Seats.length = = 0) {            return0; }                inti = 0;//record the position of the first zero after 1        intresult = 0;  for(intj = 0; J < Seats.length; J + +) {//location of record 1            if(Seats[j] = = 1) {result= (i = = 0? Math.max (Result, j-i): Math.max (result, (j-i + 1)/2));//i = = 0 is in order to judge 0 in the case of the opening, otherwise is 0 in the middlei = j + 1; }        }                return Math.max (result, seats.length-i);//0 in the case of the result}

849 maximize Distance to Closest person

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.