用Java中的一个循环解决codingBat Post4

Ani*_*udh 0 java

问题是从Java中的codingBat 解决这个问题.

问题陈述:

给定一个非空的int数组,返回一个新数组,其中包含原始数组中最后4个之后的原始数组中的元素.原始数组将包含至少一个4.请注意,在Java中创建长度为0的数组是有效的.

post4({2,4,1,2})→{1,2}

post4({4,1,4,2})→{2}

post4({4,4,1,2,3})→{1,2,3}

这是我的解决方案:

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

int lastFour=-1;
int[] post4={};

  for(int i=nums.length-1;i>=0;i--)
  {
     if((nums[i]==4))
     {
       lastFour=i;    //find the index of the last 4 in the array
       break;
     }  
   } 
   int newLen=(nums.length-lastFour)-1;
   post4=new int[newLen];   //reassign the post4 array with required length

  for(int j=0;j<newLen;j++)
  {
     post4[j]=nums[lastFour+1];   //assign values from orig. array after last 4
     lastFour++;
  }

  return post4;   
}
Run Code Online (Sandbox Code Playgroud)

但我使用了2个循环.它应该使用最多一个循环来解决.不要使用集合或任何包装类.

Psh*_*emo 7

  • 在迭代创建结果数组之前,假设长度为0.
  • 每次你发现4创建新的结果数组时,其大小基于索引4nums存储其余元素的长度.
  • 如果number没有4放在结果数组中(如果结果数组的长度是0因为它意味着我们还没找到任何数据4,或者它是nums数组的最后一个元素,则不要放置).

这是示例解决方案

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

    int[] result = new int[0];

    int j = 0;
    for (int i = 0; i<nums.length; i++){
       if (nums[i] == 4) {
           result = new int[nums.length - i-1];
           j=0;
       }
       else 
           if (result.length>0) result[j++] = nums[i]; 
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)