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

前端 未结 7 1875
小蘑菇
小蘑菇 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 14:03

    A slightly general solution:

    public static int[] midArray(int[] arr) {
        int extra = arr.length % 2 == 0? 1 : 0;
    
        int[] a = new int[1 + extra];
    
        int startIndex = arr.length / 2 - extra;
        int endIndex = arr.length / 2;
    
        for (int i = 0; i <= endIndex - startIndex; i++) {
            a[i] = arr[startIndex + i];
        }
    
        return a;
    
    }
    

    Test run:

    public static void main(String[] args) {
        int[] a = new int[]{1, 2, 3, 4};
        int[] b = new int[]{1, 2, 3};
        int[] c = new int[]{1, 2};
        int[] d = new int[]{1};
    
        System.out.println(Arrays.toString(midArray(a)));
        System.out.println(Arrays.toString(midArray(b)));
        System.out.println(Arrays.toString(midArray(c)));
        System.out.println(Arrays.toString(midArray(d)));
    
    }
    

    Output:

    [2, 3]
    [2]
    [1, 2]
    [1]
    

提交回复
热议问题