做题
力扣204:计算从2~n-1的质数的数量。
看了一个高效算法,基本思想就是,如果2是质数,那么22 23 24 25 … 就都不是质数。并且由于12 = 26 = 34 = 43 = 62 在12的根号之后,会有计算重复,所以需要检测的质数只需要小于n的平方即可,可以大大缩短计算时间。
class Solution {
public int countPrimes(int n) {
boolean[] isPrim = new boolean[n];
Arrays.fill(isPrim,true);
for(int i=2;i*i<n;i++){
if(isPrimes(i)){//如果i是质数,那么与i相乘的数就都不是质数
for(int j=2;j*i<n;j++){
isPrim[j*i] = false;
}
}
}
int count = 0;
for(int i=2;i<n;i++){
if(isPrim[i] == true) count++;
}
return count;
}
public boolean isPrimes(int n){
for(int i=2;i*i<n;i++){
if(n%i == 0) return false;
}
return true;
}
}
力扣面试题13:机器人移动的距离,机器人从(0,0)开始每次只能移动一格,并且不能移动到每位数之和大于k的格子。
使用广搜的思想,每次只要向右或者向下就可以简历完整个地图,只要遇到边界、每位数和大于k或者已经遍历过,就直接返回。这里还需要建立一个标记有没有被访问的数组mark。
class Solution {
int count;
int row;
int column;
boolean[][] mark;
public int movingCount(int m, int n, int k) {
this.count = 0;
this.row = m;
this.column = n;
mark = new boolean[m][n];
helper(0,0,k);
return count;
}
public void helper(int i, int j, int k){
if(i<row && j<column) {
if(mark[i][j] == true) return;
if(isLarger(i,j,k)) return;
count++;
mark[i][j] = true;
helper(i,j+1,k);//向下
helper(i+1,j,k);//向右
}
return;
}
public boolean isLarger(int m, int n, int k){
int result = 0;
while(m>0) {
result += m%10;
m /= 10;
}
while(n>0) {
result += n%10;
n /= 10;
}
return result > k;
}
}