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

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

    public int[] makeMiddle(int[] nums) {
    
    
            if(nums.length>=2){
    
            if(nums[nums.length-1]%2==0) {  
              int[] arrEven=new int[2];
              arrEven[0]=nums[(nums.length/2)-1];
              arrEven[1]=nums[(nums.length/2)];
              return arrEven;                                                
             }
            else {              
                int[] arrOdd=new int[1];
                arrOdd[0]=nums[(nums.length/2)];                
                return arrOdd;
            }
            }
            return nums;
     }
    

提交回复
热议问题