算法-数组的应用

2020-02-15  本文已影响0人  TanzeyTang

题目二:找出第一个最大的稳定区间:

给定一个数组e.g.[1,1,2,2,3,5,6,6,6,5]和方差X=1,如果前一天的数据和后一天的数据相差在方差范围内,则称第一天和第二天为一个稳定区间【1,1】,找出符合这样规律的最大子区间,如果存在多个长度相等的最大区间,返回第一个。

分析:见注释行。

package zexin;

import java.util.*;

public class Stablecase2 {

int arrayStart = 0;

int arraySize = 0;

int arrayEnd = 0;

int start = 0;

int size = 0;

int currentIndex =0;

    Integer

previous = null;

    ArrayList

arrayMax = newArrayList<>();

//1,1,2,2,3,6,5,5,5,4,4

    public ArrayList<Integer>

findMax(List<Integer> array, int X){

        List list  = array;

for(var i : list){

//case 1 start from the previous == null:

            if(previous == null||Math.abs(previous - i) > X){

//check the arrarySize compared to thesize:

                if(arraySize < size){

arraySize = size;

arrayStart = start;

arrayEnd = arraySize + arrayStart;

                }

//start from the first element:

                start = currentIndex;

//note: the size here is set to 0, whichmeans the first element is not contians in the size,

                size = 0;

            }

else{

size++;

            }

//move to next element in the original array:

            currentIndex ++;

previous = i;

        }

//if the for loop end, and then then compare the sizewith the arraysize:

        if(size > arraySize){

arraySize = size;

arrayStart = start;

arrayEnd = arraySize + arrayStart;

        }

//since we set the initial size for each start to 0, so that the array end actually the real index in the

        // array, so that i should <=arrayend

        for(var i = arrayStart;i<=arrayEnd;i++){

arrayMax.add(array.get(i));

        }

return arrayMax;

    }

}

上一篇 下一篇

猜你喜欢

热点阅读