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) { if (nums.length == 1) return new int[] {nums[0]}; else if (nums.length == 0) return new int[] {}; else return new int[] {nums[0],nums[1]}; }
public int[] frontPiece(int[] nums)
ReplyDelete{
if (nums.length < 2) return nums;
return new int[] {nums[0], nums[1]};
}
public int[] frontPiece(int[] nums) {
ReplyDeleteif(nums.length >= 2){
int []k = {nums[0], nums[1]};
return k;
}
return nums;
}
public int[] frontPiece(int[] nums) {
ReplyDeleteif(nums.length<2)
return nums;
else
{
int[] array= {nums[0],nums[1]};
return array;
}
}
int [] dizi=new int[2];
ReplyDeleteif(nums.length>=2)
{dizi[0]=nums[0];
dizi[1]=nums[1];
return dizi;
}
else
return nums;
public int[] frontPiece(int[] nums)
ReplyDelete{
if (nums.length <= 2)
{
int[] len = nums;
return len;
}
else
{
int[] leng = {nums[0],nums[1]};
return leng;
}
}
public int[] frontPiece(int[] nums) {
ReplyDeletefor(int i=0;i<2;i++){
if(nums.length>1){
return new int[]{nums[0],nums[1]};
}
}
return nums;
}
public int[] frontPiece(int[] nums) {
ReplyDeletereturn nums.length>1? new int[]{nums[0], nums[1]} : nums;
}
public int[] frontPiece(int[] nums) {
ReplyDeleteif(nums.length >= 2){
int []k = {nums[0], nums[1]};
return k;
} else {
return nums;
}
}
public int[] frontPiece(int[] nums) {
ReplyDeleteif(nums.length>1){
int firstTwo[] = {nums[0],nums[1]};
return firstTwo;
}else
return nums;
}
if(nums.length>2){
ReplyDeletereturn new int [] {nums[0], nums[1]};
}else{
return nums;
}