I don't have a lot to say, but this is my little bit.

Thursday, October 25, 2012

Postfix Zeros In Array

To change this array:

int[] nums = new int[] {2, 5, 0, -1, 0, 7, 11, 0 };

into this array:

= { 2, 5, -1, 7, 11, 0, 0, 0 }

You can do this, which is the Standard Way:

int switchIndex = 0;
for(int numIndex = 0; numIndex < nums.length; numIndex++) {
    if(nums[numIndex] != 0 && numIndex != switchIndex) {
        nums[switchIndex++] = nums[numIndex];
        nums[numIndex] = 0;
    }
}

Or you can do this, which uses an empty for loop:

for(int numIndex = 0, switchIndex = 0;
    numIndex < nums.length
        && nums[numIndex] != 0
        && numIndex != switchIndex
        && nums[switchIndex++] = nums[numIndex];
    nums[numIndex++] = 0
    );

No comments:

Post a Comment