在 Java 中查找数组的中间元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31778314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:36:52  来源:igfitidea点击:

Finding the middle element(s) of an array in Java

javaarrays

提问by user5183901

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

回答by Tim Biegeleisen

Try this code:

试试这个代码:

public int[] makeMiddle(int[] nums) {
    int[] a;
    if (nums.length %2 == 0) {
        // even-length array (two middle elements)
        a = new int[2];
        a[0] = nums[(nums.length/2) - 1];
        a[1] = nums[nums.length/2];
    } else {
        // odd-length array (only one middle element)
        a = new int[1];
        a[0] = nums[nums.length/2];
    }
    return a;
}

In your original code, you were not checking whether the length of numsbe even or odd.

在您的原始代码中,您没有检查长度nums是偶数还是奇数。

回答by Shashikant Sharma

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

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

回答by Bijay Gurung

A slightly general solution:

一个稍微通用的解决方案:

public static int[] midArray(int[] arr) {
    int extra = arr.length % 2 == 0? 1 : 0;

    int[] a = new int[1 + extra];

    int startIndex = arr.length / 2 - extra;
    int endIndex = arr.length / 2;

    for (int i = 0; i <= endIndex - startIndex; i++) {
        a[i] = arr[startIndex + i];
    }

    return a;

}

Test run:

测试运行:

public static void main(String[] args) {
    int[] a = new int[]{1, 2, 3, 4};
    int[] b = new int[]{1, 2, 3};
    int[] c = new int[]{1, 2};
    int[] d = new int[]{1};

    System.out.println(Arrays.toString(midArray(a)));
    System.out.println(Arrays.toString(midArray(b)));
    System.out.println(Arrays.toString(midArray(c)));
    System.out.println(Arrays.toString(midArray(d)));

}

Output:

输出:

[2, 3]
[2]
[1, 2]
[1]

回答by Kunal Vohra

I was going through Java Array docs and found that. It is perfect solution to get mid of an array.

我正在浏览 Java Array 文档并发现了这一点。这是获得数组中间的完美解决方案。

int low = startIndexOfArray;      // 0 Normally but can be anything
int high = endIndexOfArray - 1;       

int mid = (low + high) >>> 1;
System.out.print("Mid Value OF Array Is "+ mid);

回答by Jose Quijada

I've seen:

我见过:

Integer midElement(int[] ary, int start, int end) {
    if (start < end) {
        return null;
    }
    int mid = (start + end)/2;
    return ary[mid];

The above works for anystartindex and anyendindex. It even checks that invalid inputs were not passed it. The book Cracking The Coding Interviewuses this approach throughout the book in the various relevant problems

以上适用于任何start索引和任何end索引。它甚至检查无效的输入没有通过它。书中Cracking The Coding Interview使用的各种相关问题在本书中这种方法

回答by Rares

public int[] makeMiddle(int[] nums) {


        if(nums.length>=2){

        if(nums[nums.length-1]%2==0) {  
          int[] arrEven=new int[2];
          arrEven[0]=nums[(nums.length/2)-1];
          arrEven[1]=nums[(nums.length/2)];
          return arrEven;                                                
         }
        else {              
            int[] arrOdd=new int[1];
            arrOdd[0]=nums[(nums.length/2)];                
            return arrOdd;
        }
        }
        return nums;
 }