题目
给定整数数组arr和整数num,共返回多少的数组满足如下情况
max(arr[i...j]) - min(arr[i...j]) <= num
max(arr[i...j])表示数组arr[i...j] 中最大值,min(arr[i...j])表示数组arr[i...j] 中最小值
java代码
/**
* @Description:最大值减去最小值小于或等于num的数量
* @Author: lizhouwei
* @CreateDate: 2018/4/6 0:55
* @Modify by:
* @ModifyDate:
*/
public class Chapter1_10 {
public int getNum(int[] arr, int k) {
//存放最大值的索引
LinkedList<Integer> qmax = new LinkedList<Integer>();
//存放最小值的索引
LinkedList<Integer> qmin = new LinkedList<Integer>();
int i=0;
int j=0;
int res = 0;
while (i < arr.length) {
while (j < arr.length) {
while (!qmax.isEmpty() && arr[qmax.peekLast()] < arr[j]) {
qmax.pollLast();
}
qmax.offerLast(j);
while (!qmin.isEmpty() && arr[qmin.peekLast()] > arr[j]) {
qmin.pollLast();
}
qmin.offerLast(j);
//左边界为i 右边界向右能扩展的最大距离
if (arr[qmax.peekFirst()] - arr[qmin.peekFirst()] > k) {
break;
}
j++;
}
if (i == qmax.peekFirst()) {
qmax.pollFirst();
}
if (i == qmin.peekFirst()) {
qmin.pollFirst();
}
res += j - i;
i++;
}
return res;
}
//测试
public static void main(String[] args) {
Chapter1_10 chapter = new Chapter1_10();
int[] arr = {4, 3, 5, 4, 3, 3, 6, 7};
int res = chapter.getNum(arr, 3);
System.out.print(res + " ");
}
}