Question:

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

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

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

Return that maximum distance to closest person.

Example:

  1. Input: [1,0,0,0,1,0,1]
  2. Output: 2
  3. Explanation:
  4. If Alex sits in the second open seat (seats[2]), then the closest person has distance 2.
  5. If Alex sits in any other open seat, the closest person has distance 1.
  6. Thus, the maximum distance to the closest person is 2.
  1. Input: [1,0,0,0]
  2. Output: 3
  3. Explanation:
  4. If Alex sits in the last seat, the closest person is 3 seats away.
  5. This is the maximum distance possible, so the answer is 3.

Solution:

  1. /**
  2. * @param {number[]} seats
  3. * @return {number}
  4. */
  5. var maxDistToClosest = function(seats) {
  6. let max = 0
  7. for(let i=0; i<seats.length; i++){
  8. if (seats[i] === 0) {
  9. // 左边
  10. let j = i , k = i;
  11. let left , right, close;
  12. if(i!==0){
  13. while(j>=0){
  14. if(seats[j] === 1){
  15. left = j
  16. console.log
  17. break
  18. }
  19. j--
  20. }
  21. }
  22. // 右边
  23. if(i!=seats.length-1){
  24. while(k<seats.length){
  25. if(seats[k] === 1){
  26. right = k
  27. break
  28. }
  29. k++
  30. }
  31. }
  32. //左边没有相邻
  33. if(typeof left === 'undefined'){
  34. close = Math.abs(right-i);
  35. }
  36. else if(typeof right === 'undefined'){
  37. close = Math.abs(left-i)
  38. }else {
  39. close = Math.min(Math.abs(left-i), Math.abs(right-i));
  40. }
  41. max = Math.max(max, close)
  42. }
  43. }
  44. return max
  45. };

Runtime: 92 ms, faster than 8.60% of JavaScript online submissions for Maximize Distance to Closest Person.