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

前端 未结 3 1189
面向向阳花
面向向阳花 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:28

    This is O(n) so it may be what he's looking for:

    auto arrBegin = begin(arr);
    const auto arrEnd = end(arr);
    
    for(int i = 0; arrBegin < arrEnd - i; ++arrBegin){
        if(*arrBegin == 0){
            i++;
            *arrBegin = *(arrEnd - i);
        }
    }
    std::fill(arrBegin, arrEnd, 0);
    

提交回复
热议问题