以下不是一个家庭作业的问题,它只是一组的,我一直在努力通过实践的问题,我想知道如果任何人能搞清楚:在多回路彻底难倒了Java程序
http://codingbat.com/prob/p159339
返回一个数组,其中包含与给定数组完全相同的数字,但重新排列,以便每3个紧跟着一个4.不要移动3,但每移动一个数字。该数组包含3和4相同的数字,每3个数字后面有一个不是3或4的数字,并且在任何4之前出现在数组中。3
*求助 - 这里是我的工作代码:
public int[] fix34(int...nums)
{
int[] returnArray = new int[nums.length];
//ASSIGN ARRAY
//We know that all 3's can't be moved, and after every 3 there
//will automatically be a 4
for(int i = 0; i<nums.length; i++)
{
if(nums[i] == 3)
{
returnArray[i] = 3;
returnArray[i+1] = 4;
}
}
//REBUILD ARRAY - UNMOVED INDEXES
//If a value was not moved/affected by the above, it will get placed into the array
//in the same position
for (int i = 0; i < nums.length; i++)
{
if (returnArray[i] != 3 && returnArray[i] != 4 && nums[i] != 3 && nums[i] != 4)
{
returnArray[i] = nums[i];
}
}
//REBUILD ARRAY - MOVED INDEXES
//changed values = 0 in returnArray, as a result, any time we hit a 0 we
//can simply assign the value that was in the 4's place in the nums array
OuterLoop: for (int i = 0; i < nums.length; i++)
{
if (returnArray[i] == 0)
{
for (int n = 0; n < returnArray.length; n++)
{
if (returnArray[n] == 4)
{
returnArray[i] = nums[n];
continue OuterLoop;
}
}
}
}
return returnArray;
}
另一个重要的问题是,问题规范还指出,每个输入是“可解决的”。 IE浏览器。将不会有任何解决方案。 – cdeszaq 2012-03-05 22:45:54