“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.....就足够了。最后附上官方的答案:
Range Sum Query - Immutable:
最简单的方法就是一个个加,但是正如题里说的那样,这样的话加法函数被多次重复调用,所以可以把前n个数的和存在一个vector的第n位,这样求两个位置之间所有数的和的时候,直接在vector中找到对应位置的数据,做一次相减就完成了,感觉思路上有些像查表,能节省重复的加法运算。也学到了新的循环书写方式for (auto n : nums)来遍历数据集合。
看了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];; } };
相关文章推荐
- easyui修改入门
- EasyUITree实现树形结构Json串
- UIViewController的完整生命周期
- easyui的修改
- AF_DataRequest详解
- 用BeautifulSoup,urllib,requests写twitter爬虫(1)
- LeetCode 357. Count Numbers with Unique Digits(计算无重复数字)
- break和continue
- SeaJS 与 RequireJS 的差异对比
- 手势操作
- 通过filter来改变request编码
- QtQuick学习笔记之QML布局定位器Row/Column/Grid/Flow
- new relic issue
- HTML标签marquee实现滚动效果
- Java 工程结构管理 Build Path
- UI之五种布局管理器
- UIViewController Push & Pop 的那些坑
- button属性--UIControlState与UIControlEvents的区别
- phoenixframework自动化测试平台webUI模块执行js代码示例
- Runnable接口实现线程,Handler消息队列更新UI