题解 | #牛牛的果实排序#

牛牛的果实排序

https://www.nowcoder.com/practice/975a263e2ae34a669354e0bd64db9e2a

STL利用erase和remove_if实现filter

remove_if是STL中的一个函数,这个函数的作用是遍历一个容器并筛选要删除的元素,接受一个自定义函数,这个自定义函数返回true则代表删除此元素,remove_if会将要删除的元素移动到容器尾部,以此类推,最终remove_if返回的是要删除的所有元素的第一个的位置。

#include<bits/stdc++.h>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param trees int整型vector 
     * @return int整型vector
     */

    bool static isNotPrime(int n) {
        // 质数:除了1和本身之外不再具有其他因数
        if(n < 2) {
            // 1既不是质数也不是合数
            return true;
        }
        for(int i = 2; i * i <= n; i ++) {
            if(n % i == 0) {
                return true;
            }
        }
        return false;
    }
    vector<int> primeFruits(vector<int>& trees) {

        trees.erase(remove_if(trees.begin(), trees.end(), isNotPrime), trees.end());
        sort(trees.begin(), trees.end());
        return trees;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
被加薪的哈里很优秀:应该继续招人,不会给你留岗位的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务