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:
1 | public int [] midThree( int [] nums) { |
2 | int [] myArray = new int [ 3 ]; |
3 | int middle = nums.length / 2 ; |
4 | myArray[ 0 ] = nums[middle- 1 ]; |
5 | myArray[ 1 ] = nums[middle]; |
6 | myArray[ 2 ] = nums[middle+ 1 ]; |
7 | return myArray; |
8 | |
9 | } |
public int[] midThree(int[] nums) {
ReplyDeleteint [] 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;
}
Easiest and Fastest:
ReplyDeletepublic 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;
}
public int[] midThree(int[] nums) {
ReplyDeleteint 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;
}
int[] newArr = new int[3];
ReplyDeleteif(nums.length == 3)
return nums;
for(int i = 0; i < newArr.length; i++)
newArr[i] = nums[(nums.length/2) - 1 + i];
return newArr;
public int[] midThree(int[] nums) {
ReplyDeleteint leng = nums.length/2;
return new int [] {nums[leng-1],nums[leng],nums[leng+1]};
}
public int[] midThree(int[] nums) {
ReplyDeleteint 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;
}