在Java中查找数组的中间元素 [英] Finding the middle element(s) of an array in Java

查看:130
本文介绍了在Java中查找数组的中间元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个整数数组,我需要返回一个包含原始数组中间元素的新数组。具体来说,如果原始数组的长度是奇数,则结果将具有一个元素,如果是偶数,则结果将具有两个元素。

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


推荐答案

int mid = firstIndex +(lastIndex -firstIndex)/ 2,会给你数组的中间位置。

int mid = firstIndex+ (lastIndex-firstIndex)/2 , will give you the mid of the array.

这篇关于在Java中查找数组的中间元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆