238.[LeetCode]Product of Array Except itself
来源:互联网 发布:淘宝延迟发货道歉信 编辑:程序博客网 时间:2024/06/07 06:29
内容关键:
- 时间复杂度为 O(n) 的桶排序
- java中各类hash实现的遍历顺序
题中要求的时间复杂度不能超过 O(nlogn)
首先如果在O(nlogn)的时间复杂度能怎么做呢?
hash + 快排
但是如果要在 O(n) ,并且题中没有要求空间复杂度,那么我们就可以使用 桶排序
桶排序的特点
- 稳定的
- 最快
- 大量空间
算法的大量思路还是很简单的,先hash获取所有element出现的频率,然后遍历hash表,再存入对饮的桶中
public List<Integer> topKFrequent(int[] nums, int k) { List<Integer>[] bucket = new List[nums.length + 1]; Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>(); for (int n : nums) { frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1); } for (int key : frequencyMap.keySet()) { int frequency = frequencyMap.get(key); if (bucket[frequency] == null) { bucket[frequency] = new ArrayList<>(); } bucket[frequency].add(key); } List<Integer> res = new ArrayList<>(); for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) { if (bucket[pos] != null) { res.addAll(bucket[pos]); } } return res;}
代码很好理解,并且容易通过,但是一个额外的问题却跑了出来,java中的hashmap 的 keyset 返回的值是有序的吗?其他hash的实现呢?
在这篇博文里,博主亲自示范了各种hash实现
不过,关于hashmap的部分是错误的,网上很多都说 hashmap 的 setkey 是 无序的,不过经过我亲自测试,最新的java中,应该是 升序的。
Hashtable ———————降序
TreeMap / HashMap ——升序
LinkedHashMap ———- 原序
有时候,与其各种找结果不如自己跑一下
0 0
- 238.[LeetCode]Product of Array Except itself
- 238.[LeetCode]Product of Array Except itself
- [leetcode] 238.Product of Array Except Self
- [LeetCode]238.Product of Array Except Self
- [leetcode] 238. Product of Array Except Self
- Leetcode 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- 238. Product of Array Except Self LeetCode
- LeetCode 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- LeetCode *** 238. Product of Array Except Self
- LeetCode 238. Product of Array Except Self
- 【leetcode】238. Product of Array Except Self
- leetcode-238. Product of Array Except Self
- Leetcode 238. Product of Array Except Self
- 【leetcode】238. Product of Array Except Self
- LeetCode- 238. Product of Array Except Self
- leetcode 238. Product of Array Except Self
- angularjs 容易踩到的坑
- 解决Mybatis 写xml映射时,eclipse不自动提示
- [Leetcode]27. Remove Element
- 第二天 Java基础总结 3
- NOIP2015 斗地主 解题报告(搜索)
- 238.[LeetCode]Product of Array Except itself
- 集群资源管理与调度
- 第一次配置安卓开发环境,坑到路都走不直。(问题分享)
- c++继承和组合的区别
- AngularJs数据绑定以及数据绑定的API
- 51Nod Problem 1605 棋盘问题(博弈,奇偶性)
- 初学者SSM整合入门
- File的理解
- 在Java中,String、StringBuffer、StringBuilder之间的区别