Count Primes(leetcode204)
生活随笔
收集整理的這篇文章主要介紹了
Count Primes(leetcode204)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
Count the number of prime numbers less than a non-negative number,?n.
Example:
Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. //想先用粗暴的方法實現一下 public static int countPrimes(int n) {int count = 0;for(int i = 1;i<n;i++){if(isPrime(i)){count ++;}}return count;}//全部判斷一下是否書素數 但是這看到有是那個循環 時間復雜度接受不了 private static boolean isPrime(int i) {if(i ==1){return false;}for(int j =2;j< i;j++){for(int j2 =2;j2< i;j2++){if(j*j2 == i){return false;}}}return true;}//如果稍微優化一下呢 結果還是超時 public static boolean isPrime2(int i) {if(i ==1 ){return false;}//這樣是否可以快點去掉一些數據if(i > 10 && (i%2==0 ||i%3==0||i%5==0||i%7==0)){return false;}for(int j =2;j< Math.sqrt(i)+1;j++){int j2 = (int)(Math.sqrt(i)) > 2? (int)(Math.sqrt(i)):2;for(; j2< i; j2++){if(j*j2 == i){return false;}}}return true;}/**這里的想法是反一下 找出所有的合數*/ public static int countPrimes2(int n) {boolean[] notPrime = new boolean[n];int count = 0;for (int i = 2; i < n; i++) {if (notPrime[i] == false) {count++;for (int j = 2; i*j < n; j++) {notPrime[i*j] = true;}}}return count; }//這里用了不斷累加的方法 感覺也不錯 public static int countPrimes3(int n) {boolean[] m = new boolean[n];int count = 0;for (int i=2; i<n; i++) {if (m[i]) {continue;}count++;for (int j=i; j<n; j=j+i) {m[j] = true;}}return count;}git:https://github.com/woshiyexinjie/leetcode-xin/tree/master/src/main/java/com/helloxin/leetcode/algorithms?
轉載于:https://my.oschina.net/u/2277632/blog/2962468
總結
以上是生活随笔為你收集整理的Count Primes(leetcode204)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Centos6.x Desktop 關閉
- 下一篇: docker-compose 报错记录