暴力解法:按照示例在firsti到lasti遍历,将seati加到每个数上。时间复杂度取决于bookings的长度
一维差分:建立初始数组和差分数组,在差分数组的firsti位置加上seati,差分数组的lasti+1位置减去seati(避免影响原数组lasti之后的数),最后还原数组
代码
import org.junit.Test;
public class CountFights {
@Test
public void test() {
int[][] bookings = new int[][]{{1, 2, 10}, {2, 3, 20}, {2, 5, 25}};
int[] result = new int[5];
result = countFights(bookings, 5);
for (int i : result) {
System.out.print(i + " ");//[10,55,45,25,25]
}
System.out.println();
int[][] bookings1 = new int[][]{{1, 2, 10}, {2, 2, 15}};
int[] result1 = new int[2];
result1 = countFights(bookings1, 2);
for (int i : result1) {
System.out.print(i + " ");//[10,25]
}
}
public static int[] countFights(int[][] bookings, int n) {
int[] result = new int[n];//初始数组
int[] difference = new int[n + 1];//差分数组,差分数组长度加一避免最后一位对后一位操作时越界
for (int i = 0; i < bookings.length; i++) {
//firsti和endi与差分数组的索引相差一
difference[bookings[i][0] - 1] += bookings[i][2];//difference[firsti-1] += seati;
difference[bookings[i][1]] -= bookings[i][2];//difference[endi] -= seati;
}
result[0] = difference[0];
for (int i = 1; i < n; i++) {
result[i] = result[i - 1] + difference[i];//还原数组
}
return result;
}
}