您的位置:首页 > 产品设计 > UI/UE

“Count Primes” and "Range Sum Query - Immutable"

2016-06-15 09:26 531 查看
Count Primes:

看了leetcode上的hint,大致明白了 Sieve of Eratosthenes方法。想用map存所有2到n的数,然而光把所有的数据扔到map中这样一个过程就超时了(囧,可能是insert太耗费时间了吧),而且map删除数据很麻烦,容易出错。官方给出的答案用了一个动态bool数组存储所有的数。还有一个重点是 Sieve of Eratosthenes方法中循环的条件,例如循环进行到5时,只需要从5*5开始标记就可以了,因为2*5,3*5,4*5在之前的循环中都标记过了,同理,5*6=5*2*3也标记过了,这样的话只需要检查5^2,5^2+5,5^2+5*2.....就足够了。最后附上官方的答案:

class Solution {
public:
int countPrimes(int n) {
bool *isPrime = new bool
;
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}
delete[] isPrime;
return count;
}
bool isPrime(int num)
{
if (num <= 1) return false;
// Loop's ending condition is i * i <= num instead of i <= sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}
};


Range Sum Query - Immutable:

最简单的方法就是一个个加,但是正如题里说的那样,这样的话加法函数被多次重复调用,所以可以把前n个数的和存在一个vector的第n位,这样求两个位置之间所有数的和的时候,直接在vector中找到对应位置的数据,做一次相减就完成了,感觉思路上有些像查表,能节省重复的加法运算。也学到了新的循环书写方式for (auto n : nums)来遍历数据集合。

class NumArray
{
public:
vector<int> vectmp;
NumArray(vector<int> &nums)
{
vectmp.push_back(0);
for (auto n : nums)
{
vectmp.push_back(vectmp.back() + n);
}
}
int sumRange(int i, int j)
{
return vectmp[j + 1] - vectmp[i];;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: