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 of the original array is odd, and two elements if it's even.
This is my code right now, which works for arrays of even length. How do I make it work for arrays with odd length?
public int[] makeMiddle(int[] nums) {
int[] a = new int[2];
if(nums.length>1) {
a[1]=nums[nums.length/2];
a[0]=nums[nums.length/2-1];
return a;
} else {
a[2]=nums[((nums.length+1)/2) -1];
}
return a;
}
First, simply sort the array. Then, check if the number of elements present in the array is even or odd. If odd, then simply return the mid value of the array. Else, the median is the average of the two middle values.
The statement array[(int)((array. length-1)/2)] will return the middle value, rounding down.
one way you can find midpoint of array is (for odd length array) just use two loops ,1st loop start traverse from 0 index and the other (nested) loop will traverse from last index of array. Now just compare elements when it comes same ...that will be the mid point of array. i.e if(arr[i]== arr[j]) .
int mid = firstIndex + (lastIndex-firstIndex)/2
, will give you the mid of the array.
start + (end - start) / 2
is prefered over (start + end) / 2
. In case of using (start + end) / 2
and the summation result of start + end is larger than the integer max value, this will cause overflow.
public class MidOfArray {
static final int start = Integer.MAX_VALUE;
static final int end = Integer.MAX_VALUE;
public static void doesnotWork() {
int mid = (start + end) / 2;
System.out.println(mid); // output: -1
}
public static void worksGreat() {
int mid = start + ((end + start) / 2);
System.out.println(mid); // output: 2147483646
}
public static void main(String[] args) {
doesnotWork();
worksGreat();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With