代码:借鉴了评论区大佬的代码。
class Solution {
public int countPrimes(int n) {
boolean[] arr = new boolean[n];
int cnt = 0;
for(int i = 2; i < n; i++) {
if(arr[i]) continue;
cnt++;
for(int j = i; j < n; j+=i) {
arr[j] = true;
}
}
return cnt;
}
}
作者:如一
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnzlu6/?discussion=qFD1PW
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
这里要注意内层for 循环要放到 if 和cnt++的后边,学习到了。