給定數組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
若是數組長度爲N,請實現時間複雜度爲O(N)的解法。數組
package com.iqiyi;
import java.util.LinkedList;
public class Code1_10 {
public static int getNum(int[] arr,int num){
int ans=0;
int i=0;
int j=0;
LinkedList<Integer> linkedList1=new LinkedList<Integer>();
LinkedList<Integer> linkedList2=new LinkedList<Integer>();
while(i<arr.length){
while(j<arr.length){
while(!linkedList1.isEmpty()&&arr[linkedList1.peekLast()]<arr[j])
linkedList1.removeLast();
linkedList1.addLast(j);
while(!linkedList2.isEmpty()&&arr[linkedList2.peekLast()]>arr[j])
linkedList2.removeLast();
linkedList2.addLast(j);
if((arr[linkedList1.peekFirst()]-arr[linkedList2.peekFirst()])>num){
break;
}
j++;
}
ans+=j-i;
if(linkedList1.peekFirst()==i)
linkedList1.removeFirst();
if(linkedList2.peekFirst()==i)
linkedList2.removeFirst();
i++;
}
return ans;
}
public static void main(String[] args) {
System.out.println(getNum(new int[]{2,3,1,6,4}, 2));
}
}
複製代碼