Title:Maximize Distance to Closest Person 849
Difficulty:Easy
原题leetcode地址:https://leetcode.com/problems/maximize-distance-to-closest-person/
1. 见代码中的注释
时间复杂度:O(n),多次一层for循环,需要遍历整个数组。
空间复杂度:O(n),最长申请长度为n-1的List。
/**
* 1、计算第一个位置的数为0与后面出现的第一个1的距离
* 2、计数最后一个位置的数为0与前面出现的第一个1的距离,保留较大的那个值
* 3、将出现1的位置保存到List中,计算List中相邻的两个数差的绝对值,然后除以2保存到另一个List中
* 4、计算上述List中的最大值,然后同上面的较大值对比
* @param seats
* @return
*/
public static int maxDistToClosest(int[] seats) {
List<Integer> list = new ArrayList<>();
int startCount = 0;
int endCount = 0;
if (seats[0] == 0) {
for (int i = 1; i < seats.length; i++) {
if (seats[i] == 1) {
startCount = i - 0;
break;
}
}
}
if (seats[seats.length - 1] == 0) {
for (int i = seats.length - 2; i >= 0; i--) {
if (seats[i] == 1) {
endCount = seats.length - 1 - i;
break;
}
}
}
int maxCount = Math.max(startCount, endCount);
for (int i = 0; i < seats.length; i++) {
if (seats[i] == 1) {
list.add(i);
}
}
List<Integer> tmpList = new ArrayList<>();
for (int i = 0; i < list.size() - 1; i++) {
tmpList.add(Math.abs(list.get(i + 1) - list.get(i)) / 2);
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < tmpList.size(); i++) {
if (tmpList.get(i) > max) {
max = tmpList.get(i);
}
}
return Math.max(max, maxCount);
}
1. 见代码中的注释
时间复杂度:O(n),多次一层for循环,需要遍历整个数组。
空间复杂度:O(n),最长申请长度为n的数组。
/**
* 最近人的最大距离(最近--最小 MIN,最大--最大 MAX)
* 1、求两侧到1的距离问题,分别生成lef、right数组,分别记录到左侧1的距离和距离右侧1的距离
* 2、因为先求最小值,数组的开头和结尾可能是0,在初始化数组的时候没需要对left和right的值为数据的长度
* 3、分别对数组进行从左到右、从右到左遍历,如果当前值为1,此时left[i]和right[i]置为1,否则对之前(后)的数加1操作
* 4、求最小值,再球最大值
* @param seats
* @return
*/
public static int maxDistToClosest1(int[] seats) {
int left[] = new int[seats.length];
int right[] = new int[seats.length];
for (int i = 0; i < seats.length; i++) {
left[i] = seats.length;
right[i] = seats.length;
}
for (int i = 0; i < seats.length; i++) {
if (seats[i] == 1) {
left[i] = 0;
}
else if (i > 0) {
left[i] = left[i - 1] + 1;
}
}
for (int i = seats.length - 1; i >= 0; i--) {
if (seats[i] == 1) {
right[i] = 0;
}
else if (i < seats.length - 1) {
right[i] = right[i + 1] + 1;
}
}
for (int i = 0; i < seats.length; i++) {
System.out.print(left[i] + " ");
// System.out.print(right[i] + " ");
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < seats.length; i++) {
if (seats[i] == 0) {
max = Math.max(max, Math.min(left[i], right[i]));
}
}
return max;
}