Skip to content

Instantly share code, notes, and snippets.

@bragboy
Created November 12, 2015 11:08
Show Gist options
  • Select an option

  • Save bragboy/62a263ee785b049ddaec to your computer and use it in GitHub Desktop.

Select an option

Save bragboy/62a263ee785b049ddaec to your computer and use it in GitHub Desktop.
public class CompactArray {
public static void main(String[] args) {
CompactArray c = new CompactArray();
int[] sampleArray = {-1,5,3,-1,3,5,2,1,-1,6};
System.out.print(" Input : ");printArray(sampleArray, sampleArray.length);
int validIndex = c.compact(sampleArray);
System.out.print("Output : ");printArray(sampleArray, validIndex);
}
private int compact(int[] arr){
int k = 0;
for(int i=0;i<arr.length;i++){
if(arr[i]!=-1)
arr[k++] = arr[i];
}
return k;
}
private static void printArray(int[] sampleArray, int validIndex) {
for(int i=0;i<validIndex;i++){
System.out.print(sampleArray[i]+" ");
}
System.out.println();
}
}
/*
Input : -1 5 3 -1 3 5 2 1 -1 6
Output : 5 3 3 5 2 1 6
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment