• Hash Table Four


    (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 }
    View Code

    注意:循环都从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 }
    View Code

    解题思路:

    双重循环,使用hashmap记录每个点到其他点的距离。更换起始点时hashmap要重新分配。计数乘以2是要考虑到顺序问题。

    注意:Array myarr=[[55,32],[5,90,66]],myarr[1]=[5,90,66],myarr[1][2]=[66]

  • 相关阅读:
    redis和memcache的区别
    c语言行编辑程序
    C语言栈的实现
    双向链表
    静态链表的合并
    静态链表的创建
    链表
    将非递减有序排列(L L1)归并为一个新的线性表L2 线性表L2中的元素仍按值非递减
    C语言合并两个集合(L,L1) 将L1中不在L中的元素插入到L线性表中
    oracle--JOB任务
  • 原文地址:https://www.cnblogs.com/struggleli/p/6181090.html
Copyright © 2020-2023  润新知