Problem:
Given an int array of any length, return a new array of its first 2 elements. If the array is smaller than length 2, use whatever elements are present.
frontPiece({1, 2, 3}) → {1, 2}
frontPiece({1, 2}) → {1, 2}
frontPiece({1}) → {1}
Solution:
public int[] frontPiece(int[] nums) { int[] myArray = new int[2]; if (nums.length < 2) return nums; else { myArray[0] = nums[0]; myArray[1] = nums[1]; return myArray; } }
public int[] frontPiece(int[] nums) {
ReplyDeletereturn (nums.length <= 1)? nums : new int[]{nums[0], nums[1]};
}
public int[] frontPiece(int[] nums) {
ReplyDeletereturn (nums.length <= 1)? nums : new int[]{nums[0], nums[1]};
}
public int[] frontPiece(int[] nums) {
ReplyDeleteif(nums.length>=2)
return new int[]{nums[0],nums[1]};
return nums;
}
public int[] frontPiece(int[] nums) {
ReplyDeletereturn nums.length>1?Arrays.copyOfRange(nums,0,2):nums;
}
public int[] frontPiece(int[] nums) {
ReplyDeleteif(nums.length>=2){
int[] arr = new int[]{ nums[0] ,nums[1]};
return arr;
}
else {
return nums;
}
}