java - 返回仅包含给定数组的前 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;
}
我的问题
虽然我已经解决了这个问题,但我的解决方案看起来有点长。所以我正在寻找更短但仍然准确的其他解决方案。你能帮我解决这个问题吗?
解决方案
如果您只想要一个更短的方法,并且如果在为空或带有单个元素时返回参数本身是有效的,那么您可以这样写:
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] };
}
}
推荐阅读
- html - 当我添加更多内容时,如何防止我的文本被推高?
- json - 如何从 Delphi 6 中的 Microsoft XML CoXMLHTTP60 响应中获取属性?
- azure - Azure IOT PnP 数字孪生 API/SDK 检索设备/孪生的属性、命令和遥测定义
- javascript - 当我使用旧的刷新令牌时,为什么刷新端点会返回新的令牌?
- amazon-web-services - 添加逻辑以检查 Infra 是否在帐户中,如果没有则部署 AWS-CDK
- python-3.x - 将上市公司数据的 HTML 读入 Dataframe
- c# - 使用字符串格式的 LINQ
- android - 如何创建由片段重叠另一个片段组成的动画?
- uart - 无法在 ESP32 控制器上使用 micropython 和 SIM7070G NB 从 uart 读取数据
- json - Flutter如何从json http响应中获取特定值