思路我差不多知道了,但是不知道怎么转成代码。
循环这1000个数字,如果arr[i+1]>arr[i]就把这个数字存在一个新数组里,不满足这个条件了,这个数组就置空,再继续,然后新数组里的长度=30就拿出来,请问代码怎么写?
示例代码如下。
private static boolean exists(int[] numbers) {
int count = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i - 1] < numbers[i]) {
count++;
if (count == 30) {
break;
}
} else {
count = 0;
}
}
return count == 30;
}
用滑动窗口更简单
public int[] fun(int a[]){
int i = 0,j = 0;
while(true){
if(j == 1000) break;
if(j - i + 1 == 30){
return Arrays.copyOfRange(a, i, j + 1);
}
if(a[i] >= a[j]){
i = j;
j = i + 1;
}else{
j ++;
}
}
return new int[]{};
}
public class Test extends BaseSolution {
/**
* 检查 int数组,是否有连续的 needUpLen 个为增长趋势
* @param val 数据
* @param needUpLen 连续增长长度
* @return 有则返回 true
*/
private boolean check(int[] val, int needUpLen) {
if (val.length == 0) {
return false;
}
int left = 0, right = 1;
while (right < val.length) {
if (val[right] > val[right - 1]) {
right++;
if (right - left >= needUpLen) {
// 输出连续 needUpLen 长度递增的部分
printVals(Arrays.copyOfRange(val, left, right));
return true;
}
} else {
left = right++;
}
}
return false;
}
public static void main(String[] args) {
Test solution = new Test();
int[] val = new int[] {
9, 84, 85, 47, 29, 35, 25, 29, 93, 57, 94, 18, 31, 12, 3, 96, 70, 1, 87, 1, 3, 43, 77, 50, 84
, 8, 45, 64, 50, 63, 60, 2, 61, 30, 6, 53, 59, 15, 37, 46, 70, 98, 57, 22, 49, 87, 11, 84, 89, 12, 83, 43, 99, 41, 26
};
printVals(val);
System.out.println(solution.check(val, 4));
}
}
这才是滑动窗口好吧?楼上的那个不还是n方复杂度?不能拷贝
private int[] fun(int[] arr){
int[] result = null;
int count = 0;
for(int i = 0; i < arr.length - 1; i++){
if(arr[i] < arr[i+1]){
if(result == null){
result = new int[30];
result[count] = arr[i];
}
result[++count] = arr[i+1];
if(count == 29){
// 从0开始到29,长度就是30 了
return result;
}
}else{
result = null;
count = 0;
}
}
if(count < 29){
result = null;
}
return result;
}