Java > Array-1 > midThree (CodingBat Solution)

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;
  
}


6 comments :

  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;
    }

    ReplyDelete
  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;
    }

    ReplyDelete
  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;
    }

    ReplyDelete
  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;

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

    ReplyDelete
  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;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact