Finding the middle element(s) of an array in Java

前端 未结 7 1879
小蘑菇
小蘑菇 2021-02-14 13:03

Given an array of integers, I need to return a new array containing the middle element(s) from the original array. Specifically, the result will have one element if the length o

7条回答
  •  离开以前
    2021-02-14 13:49

    I've seen:

    Integer midElement(int[] ary, int start, int end) {
        if (start < end) {
            return null;
        }
        int mid = (start + end)/2;
        return ary[mid];
    

    The above works for any start index and any end index. It even checks that invalid inputs were not passed it. The book Cracking The Coding Interview uses this approach throughout the book in the various relevant problems

提交回复
热议问题