pull all non-zero elements in an array to the left - c# -
if have following array
{ 1, 0, 0, 1, 2, 0, 1 }
and want method take array , change to
{ 1, 1, 2, 1, 0, 0, 0 }
what best algorithm this? possible in o(n) time?
this question exact question except in python not c#, in case not clear: (only difference move zeros right, not left) how move non-zero elements in python list or numpy array 1 side?
thanks
edit: i've ran problem didn't consider @ first. i'm trying run algorithm on 2d array, on 1 particular dimension. how change account this?
updated 2d array
int[,] array = { { 1, 0, 0, 1, 2, 0, 1 }, // row 0 { 1, 0, 0, 1, 2, 0, 1 }, // row 1 { 1, 0, 0, 1, 2, 0, 1 } // row 2 }; pullnonzerostoleft(array, 1); (int row = 0; row <= array.getupperbound(0); row++) { (int col = 0; col <= array.getupperbound(1); col++) { console.write("{0} ", array[row,col]); } console.writeline(); }
pullnonzerostoleft()
public static void pullnonzerostoleft(int[,] array, int row) { if (row > array.getupperbound(0)) { return; } // used keep track of swap point int index = 0; (int = 0; <= array.getupperbound(1); i++) { if (array[row, i] == 0) { continue; } int temp = array[row, i]; array[row, i] = array[row, index]; array[row, index] = temp; index++; } }
results:
1 0 0 1 2 0 1 1 2 1 1 0 0 0 1 0 0 1 2 0 1
updated jagged array
a non-linq
approach, swap non-zero elements 0 elements.
int[][] array = { new[] { 1, 0, 0, 1, 2, 0, 1 }, // row 0 new[] { 1, 0, 0, 1, 2, 0, 1 }, // row 1 new[] { 1, 0, 0, 1, 2, 0, 1 } // row 2 }; pullnonzerostoleft(array, 1); foreach (int[] row in array) { console.writeline(string.join(", ", row)); }
pullnonzerostoleft()
public static void pullnonzerostoleft(int[][] array, int row) { if (row >= array.length) { return; } // used keep track of swap point int index = 0; (int = 0; < array[row].length; i++) { if (array[row][i] == 0) { continue; } int temp = array[row][i]; array[row][i] = array[row][index]; array[row][index] = temp; index++; } }
results:
1, 0, 0, 1, 2, 0, 1 1, 1, 2, 1, 0, 0, 0 1, 0, 0, 1, 2, 0, 1
Comments
Post a Comment