import java.util.Arrays; public class Compact { static int previousValid(int[] nums, int startIndex) { while (--startIndex >= 0 && nums[startIndex] == -1); return startIndex; } static int nextInvalid(int[] nums, int startIndex) { while (++startIndex < nums.length && nums[startIndex] != -1); return startIndex; } static void compact(int... nums) { int last = previousValid(nums, nums.length); for (int h = -1, t = last + 1; (h = nextInvalid(nums, h)) < (t = previousValid(nums, t)); ) { nums[last = h] = nums[t]; } System.out.println(Arrays.toString(nums) + "; last valid = " + last); } public static void main(String[] args) { compact(3, 4, -1, -1, -1, 5, 8, -1, 8);
Key ideas:
- Use
previousValid and nextInvalid helper methods to make logic more understandable - Keep track of
h and t for "head" and "tail"h finds nextInvalidt finds previousValid
- Keep assignment
nums from index t to h , and h < t
source share