<分区>
我正在研究这个问题:
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
我知道如何通过就地交换来回答这个问题,但我也想看看是否可以使用 std::sort
来解决它。
根据 cplusplus.com:
the comparator function for the sort function is a Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
//comments below are based on my understanding
static bool comp(int a, int b){
//lambda function evaluates to true - no swap,
//evaluates to false -swap
if(a==0) return false;
if(b==0) return true;
//if neither a nor b is 0 them do not swap
return true;
}
void moveZeroes(vector<int>& nums) {
sort(nums.begin(),nums.end(),comp);
}
给定的测试用例是[0,1,0,3,12]
我的输出是[12,3,1,0,0]