剑指Offer 59 -l
题解1
用数组切片做
代码
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(k==0) return new int [0];
int [] res= new int[nums.length-k+1];
for (int i=0;i<=nums.length-k;i++) {
res[i]=Arrays.stream(
Arrays.copyOfRange(nums, i, i+k))
.max().getAsInt();
}
return res;
}
}
知识点
System.arraycopy(Object src , int srcSta , Object dest , int destSta , int length)
1.Object src : 原数组
2.int srcSta : 从原数组的复制起始位置
3.Object dest : 目标数组
4.int destSta : 目标数组的覆盖起始位置
5.int length : 要copy的数组的长度
即将原数组从srcSta位置开始长度为length的数组切片覆盖到目标数组从destSta往后length长度的空间内,如:
int [] test=new int[] {-5,1,5,0,-7};
int [] dest=new int[6] ;
System.arraycopy(test, 2, dest, 3, 3);
System.out.print(Arrays.toString(dest));
// [0, 0, 0, 5, 0, -7]
Arrays.copyof()
int [] test=new int[] {-5,1,5,0,-7};
int[] dest2=Arrays.copyOf(test, 3);
System.out.print(Arrays.toString(dest2));
//[-5, 1, 5]
Arrays.copyOfRange()
int [] test=new int[] {-5,1,5,0,-7};
int[] dest3=Arrays.copyOfRange(test, 1, 3);
System.out.print(Arrays.toString(dest3));
//[1, 5]
找不到这道题了(