zoukankan      html  css  js  c++  java
  • 825. Friends Of Appropriate Ages有效的好友请求的数量

    [抄题]:

    Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person. 

    Person A will NOT friend request person B (B != A) if any of the following conditions are true:

    • age[B] <= 0.5 * age[A] + 7
    • age[B] > age[A]
    • age[B] > 100 && age[A] < 100

    Otherwise, A will friend request B.

    Note that if A requests B, B does not necessarily request A.  Also, people will not friend request themselves.

    How many total friend requests are made?

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    用sliding window写不出

    至少可以返回来用暴力做法啊

    [一句话思路]:

    duplicate的数组完全可以用hashmap来存数,特别是duplicate特别多的时候

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 一开始没有先想好,hashmap存错了。先想好再写

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    index 还是 nums[index]下次可以检查下

    [总结]:

    有duplicate的数组完全可以用hashmap来存数

    [复杂度]:Time complexity: O(n^2) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    有duplicate的数组完全可以用hashmap来存数,特别是duplicate特别多的时候

    [算法思想:递归/分治/贪心]:

    [关键模板化代码]:

    两个变量的双重循环:

    for (int a : map.keySet()) for (int b : map.keySet())

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public int numFriendRequests(int[] ages) {
            //cc
            if (ages == null || ages.length == 0) return 0;
            
            //ini: hashmap: age,count
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < ages.length; i++) map.put(ages[i], map.getOrDefault(ages[i], 0) + 1);
            int res = 0;
            
            //for loop: return a* b or a * (a - 1)
            for (int a : map.keySet()) for (int b : map.keySet()) {
                if (valid(a, b)) 
                    res += map.get(a) * (map.get(b) - (a == b ? 1 : 0));
            }
            return res;
        }
        
        public boolean valid(int a, int b) {
            return !(b <= 0.5 * a + 7 || b > a || (b > 100 && a < 100));
        }
    }
    View Code
  • 相关阅读:
    Guava Enums
    Guava CharMatcher
    Guava CaseFormat
    HotSpot Generations
    Java Run-Time Data Areas
    Reloading Java Classes 201: How do ClassLoader leaks happen? Translation
    Guava BiMap AbstractBiMap
    Reloading Java Classes 101: Objects, Classes and ClassLoaders Translation
    Guava CompoundOrdering
    Chapter 4 -- Throwables
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9049778.html
Copyright © 2011-2022 走看看