首页 > 解决方案 > 返回仅包含给定数组的前 2 个元素的新数组的最短代码是什么?

问题描述

当我在 CodingBat 上练习 Java 问题时,我遇到了以下问题陈述。

问题

给定一个任意长度的整数数组,返回一个包含其前 2 个元素的新数组。如果数组小于长度 2,则使用存在的任何元素。

例子

frontPiece([1, 2, 3]) → [1, 2]
frontPiece([1, 2]) → [1, 2]
frontPiece([1]) → [1]

我的解决方案

public int[] frontPiece(int[] nums) {
    if (nums.length < 2) {
        return nums;
    }
    
    int[] myArray = new int[2];
    myArray[0] = nums[0];
    myArray[1] = nums[1];
    return myArray;
}

我的问题

虽然我已经解决了这个问题,但我的解决方案看起来有点长。所以我正在寻找更短但仍然准确的其他解决方案。你能帮我解决这个问题吗?

标签: javaarrays

解决方案


如果您只想要一个更短的方法,并且如果在为空或带有单个元素时返回参数本身是有效的,那么您可以这样写:

public static int[] frontPiece(int[] nums) {
    // if the argument is empty or has just a single element
    if (nums.length < 2) {
        // return the array itself
        return nums;
    } else {
        // otherwise, return a new array with the first two elements of argument
        return new int[] { nums[0], nums[1] };
    }
}

推荐阅读