简体   繁体   中英

Java Arraylist Program Failing Test

I am creating a program that when given a list, returns a new integer list where the first two elements remain the same, and where each element after is the median of the three elements ending in that position in the original list. For example, given the list: [1, 2, 3, 4, 5, 6, 7, 8, 9] , the program would return: [1, 2, 2, 3, 4, 5, 6, 7, 8] .

This is the code I've written where I'm getting the correct results, but it is failing my tester. I'm not sure if I'm missing an odd case.

Yes you missed some cases: Your code does not calculate the median if one ore more numbers are equal.

Solution whitch will work, based on your Code:

    public static List<Integer> method(List<Integer> items) {
    List<Integer> list = new ArrayList<Integer>();
    int size = items.size();
    if (size == 0) {
        list = Arrays.asList();
    } else if (size == 1) {
        int first = items.get(0);
        list.add(first);
    } else if (size == 2) {
        int first = items.get(0);
        list.add(first);
        int second = items.get(1);
        list.add(second);
    } else {
        int first = items.get(0);
        int second = items.get(1);
        list.add(first);
        list.add(second);
        for (int i = 2; i < size; i++) {
            int med;
            if (items.get(i) <= items.get(i - 1) && items.get(i) >= items.get(i - 2)
                    || items.get(i) >= items.get(i - 1) && items.get(i) <= items.get(i - 2)) {
                med = items.get(i);

            } else if (items.get(i - 1) <= items.get(i) && items.get(i - 1) >= items.get(i - 2)
                    || items.get(i - 1) >= items.get(i) && items.get(i - 1) <= items.get(i - 2)) {
                med = items.get(i - 1);
            } else {
                med = items.get(i - 2);
            }
            list.add(med);
        }
    }
    return list;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM