(1)Count Primes
质数(素数):在大于1 的自然数中,除了1和它本身之外,不能被任何其他整数整除。
解题思路:使用一个boolean类型的数组,从i(2) 开始循环,将小于N的i的倍数都做标记,这些数不是质数。遇到没标记的小于N的数就加一,总数即为质数的个数。
代码如下:

1 public class Solution { 2 public int countPrimes(int n) { 3 boolean[] notPrime = new boolean[n]; 4 int count = 0; 5 for (int i = 2; i < n; i++) { 6 if (notPrime[i] == false) { 7 count++; 8 for (int j = 2; i*j < n; j++) { 9 notPrime[i*j] = true; 10 } 11 } 12 } 13 return count; 14 } 15 }
注意:循环都从2开始!!!
(2)Number of Boomerangs
代码如下:

1 public class Solution { 2 public int numberOfBoomerangs(int[][] p) { 3 //[[0,0],[1,0],[2,0]] 4 int n = p.length;//3 5 if (n == 0) { 6 return 0; 7 } 8 int count = 0; 9 for (int i = 0; i < n; i++) { 10 Map<Double,Integer> map = new HashMap<>(); 11 for (int j = 0; j < n; j++){ 12 if (map.containsKey(distance(p[i],p[j]))) { 13 int value = map.get(distance(p[i],p[j])); 14 count += 2 * value; 15 map.put(distance(p[i],p[j]), value+1); 16 } else { 17 map.put(distance(p[i],p[j]), 1); 18 } 19 } 20 } 21 return count; 22 } 23 public Double distance(int[] a, int[]b){ 24 return Math.sqrt(Math.pow(a[0]-b[0], 2) + Math.pow(a[1]-b[1], 2)); 25 } 26 }
解题思路:
双重循环,使用hashmap记录每个点到其他点的距离。更换起始点时hashmap要重新分配。计数乘以2是要考虑到顺序问题。
注意:Array myarr=[[55,32],[5,90,66]],myarr[1]=[5,90,66],myarr[1][2]=[66]