classSolution { public: intlongestConsecutive(vector<int>& nums){ unordered_set<int> numbers; for (auto i = nums.begin(); i != nums.end(); i++) { numbers.insert(*i); } int ans = 0; for (auto i = numbers.begin(); i != numbers.end(); i++) { if (numbers.find(*i - 1) != numbers.end()) { continue; } int cur = *i; int len = 1; while (numbers.find(cur + 1) != numbers.end()) { cur++; len++; } ans = max(len, ans); } return ans; } };
from django.shortcuts import render from django.http import HttpResponse from info.consts import StatusCode from functools import wraps from info.models import * from django.contrib import auth import json
classSolution: defcountPrimes(self, n: int) -> int: data = set(range(2, n)) primes = set() while data: t = data.pop() primes.add(t) if t ** 2 > n: break for i inrange(2, n // t + 1): try: data.remove(i * t) except: pass returnlen(primes) + len(data)
用list来写:
1 2 3 4 5 6 7 8 9 10
classSolution: defcountPrimes(self, n: int) -> int: if n <= 2: return0 l = [1] * n # l为记录1至n-1是否为质数的列表 l[0] = l[1] = 0# 0和1不是质数 for i inrange(2, int(n ** 0.5) + 1): if l[i] == 1: # 若i为质数 l[2*i:n:i] = [0] * ((n - i - 1) // i) # i的整数倍都不是质数 returnsum(l)