Leetcode 849. Maximize Distance to Closest Person

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/86017926

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Maximize Distance to Closest Person

2. Solution

  • Version 1
class Solution {
public:
    int maxDistToClosest(vector<int>& seats) {
        int max_distance = 0;
        int distance = 0;
        int left = -1;
        int right = -1;
        int size = seats.size();
        for(int i = 0; i < seats.size(); i++) {
        	if(!seats[i]) {
                getRight(seats, right, i);
        		calculateDistance(i, left, right, max_distance, size);
        	}
        	else {
        		left = i;
        	}
        }
        return max_distance;
    }

private:
    void calculateDistance(int current, int left, int& right, int& max_distance, int size) {
    	int distance_left = INT_MAX;
    	int distance_right = INT_MAX;
    	int distance = 0;
    	if(left > -1) {
    		distance_left = current - left;
    	}
        if(right < size){
    		distance_right = right - current;
    	}
    	distance = min(distance_left, distance_right);
    	max_distance = max(max_distance, distance);
    }
    
    void getRight(vector<int>& seats, int& right, int current) {
        if(right <= current) {
    		for(int i = current + 1; i < seats.size(); i++) {
    			if(seats[i]) {
    				right = i;
    				break;
    			}
                else {
                    right = i + 1;
                }
    		}
    	}
    }
};
  • Version 2
class Solution {
public:
    int maxDistToClosest(vector<int>& seats) {
        int max_distance = 0;
        int distance = 0;
        int left = -1;
        int right = seats.size() - 1;
        for(int i = 0; i < seats.size(); i++) {
        	if(seats[i]) {
        		if(left == -1) {
        			max_distance = max(max_distance, i);
        		}
        		else {
        			max_distance = max(max_distance, (i - left) / 2);
        		}
        		left = i;
        	}
        }
        if(!seats[right]) {
        	max_distance = max(max_distance, right - left);
        }
        return max_distance;
    }
};

Reference

  1. https://leetcode.com/problems/maximize-distance-to-closest-person/description/

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试