Skip to content

Instantly share code, notes, and snippets.

@josephbleau
Last active Dec 28, 2015
Embed
What would you like to do?
A comprehensive solution to: http://codingbat.com/prob/p159339 -- This solution also works for the next problem at codingbat, just replace the relevant numbers.
public int[] fix34(int[] nums) {
if(nums.length == 0 || nums.length == 1 )
return nums;
ArrayList<Integer> bank = new ArrayList();
for(int i = 0; i < nums.length; ++i) {
if(nums[i] == 4){
bank.add(i);
}
else if(nums[i] == 3 && i+1 < nums.length) {
if(nums[i+1] == 4) {
++i;
}
else if( !bank.isEmpty() ) {
int idx = bank.get(0);
bank.remove(0);
nums[idx] = nums[i+1];
nums[i+1] = 4;
++i;
}
else {
for(int j = i+1; j < nums.length; ++j) {
if(nums[j] == 4) {
nums[j] = nums[i+1];
nums[i+1] = 4;
++i;
break;
}
else{
if(j == nums.length-1)
return nums;
}
}
}
}
}
return nums;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment