Good C++ solutions to the “Bring all the zeros to the back of the array” interview challenge

前端 未结 3 1180
面向向阳花
面向向阳花 2021-01-01 01:43

I had an interview for a Jr. development job and he asked me to write a procedure that takes an array of ints and shoves the zeroes to the back. Here are the constraints (wh

3条回答
  •  既然无缘
    2021-01-01 02:35

    An approach that sorts is O(N*Log2N). There is a linear solution that goes like this:

    • Set up two pointers - readPtr and writePtr, initially pointing to the beginning of the array
    • Make a loop that walks readPtr up the array to the end. If *readPtr is not zero, copy to *writePtr, and advance both pointers; otherwise, advance only readPtr.
    • Once readPtr is at the end of the array, walk writePtr to the end of the array, while writing zeros to the remaining elements.

提交回复
热议问题