相关疑难解决方法(0)

良好的C++解决方案"将所有的零带到阵列的后面"采访挑战

我接受了Jr.开发工作的采访,他让我写了一个程序,它采取一系列的整数并将零推到后面.以下是约束(他在开始时没有告诉我......正如在编程访谈中经常发生的那样,我在解决问题的过程中学会了问题的约束)

  • 必须就地做; 没有创建临时数组,新数组等
  • 不必保留非零数字的顺序(我希望他在开始时告诉我这个)

建立:

int arr[] = {0, -2, 4, 0, 19, 69}; 
/* Transform arr to {-2, 4, 19, 69, 0, 0} or {69, 4, -2, 19, 0, 0} 
   or anything that pushes all the nonzeros to the back and keeps
   all the nonzeros in front */
Run Code Online (Sandbox Code Playgroud)

我的答案:

bool f (int a, int b) {return a == 0;}
std::sort(arr, arr+sizeof(arr)/sizeof(int), f);
Run Code Online (Sandbox Code Playgroud)

还有什么其他好的答案?

c++ algorithm

5
推荐指数
1
解决办法
290
查看次数

标签 统计

algorithm ×1

c++ ×1