Maximize Distance to Closest Person

2019-05-25 22:44:02 浏览数 (1)

1. Description

2. Solution

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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;
    }
};

0 人点赞