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

前端 未结 7 1893
小蘑菇
小蘑菇 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:48

    Try this code:

    public int[] makeMiddle(int[] nums) {
        int[] a;
        if (nums.length %2 == 0) {
            // even-length array (two middle elements)
            a = new int[2];
            a[0] = nums[(nums.length/2) - 1];
            a[1] = nums[nums.length/2];
        } else {
            // odd-length array (only one middle element)
            a = new int[1];
            a[0] = nums[nums.length/2];
        }
        return a;
    }
    

    In your original code, you were not checking whether the length of nums be even or odd.

提交回复
热议问题