一道算法题(负数左边,正数右边)的最优答案
int[] source = { 5, -3, 6, -7, -6, 1, 8, -4, 0, 0 }; int toRightIdx = 0; int toLeftIdx = source.Length - 1; int leftIdx = 0; int rightIdx = source.Length - 1; int[] result = new int[source.Length]; while (true) { if (toLeftIdx >= 0) { int left = source[toRightIdx++]; if (left < 0) result[leftIdx++] = left; int right = source[toLeftIdx--]; if (right > 0) result[rightIdx--] = right; } else { result[rightIdx--] = 0; } if (leftIdx > rightIdx) break; }
应该算是最好的解法了吧:P