## Problem:

Given an array of ints of odd length, return a new array length 3 containing the elements from the middle of the array. The array length will be at least 3.

midThree({1, 2, 3, 4, 5}) → {2, 3, 4}
midThree({8, 6, 7, 5, 3, 0, 9}) → {7, 5, 3}
midThree({1, 2, 3}) → {1, 2, 3}

## Solution:

public int[] midThree(int[] nums) {
int[] myArray = new int[3];
int middle = nums.length / 2;
myArray[0] = nums[middle-1];
myArray[1] = nums[middle];
myArray[2] = nums[middle+1];
return myArray;

}

1. public int[] midThree(int[] nums) {
int [] mid = new int[3];
int start = nums.length/2;
for(int i=0;i<mid.length;i++){
mid[i]=nums[start-1+i];
} return mid;
}

2. Easiest and Fastest:

public int[] midThree(int[] nums) {
int mid = nums.length / 2; // middle of the 3

int[] middle3 = { nums[mid-1], nums[mid], nums[mid+1] };
return middle3;
}

3. public int[] midThree(int[] nums) {
int a[]=new int[3];
a[0]=nums[(nums.length/2)-1];
a[1]=nums[nums.length/2];
a[2]=nums[(nums.length/2)+1];
return a;
}

4. int[] newArr = new int[3];

if(nums.length == 3)
return nums;

for(int i = 0; i < newArr.length; i++)
newArr[i] = nums[(nums.length/2) - 1 + i];

return newArr;

5. public int[] midThree(int[] nums) {
int leng = nums.length/2;
return new int [] {nums[leng-1],nums[leng],nums[leng+1]};
}

6. public int[] midThree(int[] nums) {
int first=(nums.length/2)-1;
int mid=(nums.length/2);
int last=(nums.length/2)+1;
int[] arr =new int[]{nums[first],nums[mid],nums[last]};
return arr;
}

## Subscribe

We hate spam as much as you do.