Social Icons

Sunday, April 18, 2010

fix34:Solutions for Javabat:10


Return an array that contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3's, but every other number may move. The array contains the same number of 3's and 4's, every 3 has a number after it that is not a 3 or 4, and a 3 appears in the array before any 4.

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

Source

public int[] fix34(int[] nums) {
int newA[]=new int[nums.length];
for(int i=0 , index4=0 ; i< nums.length ; i++){
if(nums[i]==3 && i<nums.length-1){
newA[i]=3;
// find a four
for(int j=index4;j<nums.length;j++){
if(nums[j]==4){
nums[j]=newA[j]=nums[i+1];
nums[i+1]=newA[i+1]=4;
index4=i+2;
break;
}  // end if
}// end inner for
}// end if
else if(newA[i]==0) newA[i]=nums[i];
}
return newA;
}
 
 
Blogger Templates http://slots.to/