[LeetCode 203,204][简单]移除链表元素/计数质数

203.移除链表元素
题目链接
比较通用的思路是加一个dummyhead,那我就不用它,用二级指针做一下

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode **p = &head;
        while(*p){
            if((*p)->val==val)*p = (*p)->next;
            else p = &(*p)->next;
        }
        return head;
    }
};

204.计数质数
题目链接
复习一下欧拉筛,如果对亚线性的做法感兴趣可以移步Atkin筛更加神奇的做法

class Solution {
public:
    bool *is;
    int *p;
    int cnt = 0;
    int countPrimes(int n) {
        if(!n)return 0;
        is = new bool[n]{0};
        p = new int[n];
        for(int i = 2; i < n; i++){
            if(!is[i])p[cnt++]=i;
            for(int j = 0; j < cnt && p[j] * i < n; j++){
                is[p[j]*i] = 1;
                if(i % p[j] == 0)break;
            }
        }
        return cnt;
    }
};
发布了104 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/IDrandom/article/details/104266820