java - 为什么这些循环和散列操作需要 O(N) 时间复杂度?
问题描述
给定数组:
int arr[]= {1, 2, 3, 2, 3, 1, 3}
你被要求在数组中找到一个出现奇数次的数字。它是 3(发生 3 次)。时间复杂度至少应为 O(n)。解决方案是使用HashMap
. 元素成为键,它们的计数成为哈希图的值。
// Code belongs to geeksforgeeks.org
// function to find the element occurring odd
// number of times
static int getOddOccurrence(int arr[], int n)
{
HashMap<Integer,Integer> hmap = new HashMap<>();
// Putting all elements into the HashMap
for(int i = 0; i < n; i++)
{
if(hmap.containsKey(arr[i]))
{
int val = hmap.get(arr[i]);
// If array element is already present then
// increase the count of that element.
hmap.put(arr[i], val + 1);
}
else
// if array element is not present then put
// element into the HashMap and initialize
// the count to one.
hmap.put(arr[i], 1);
}
// Checking for odd occurrence of each element present
// in the HashMap
for(Integer a:hmap.keySet())
{
if(hmap.get(a) % 2 != 0)
return a;
}
return -1;
}
I don't get why this overall operation takes O(N) time complexity. If I think about it, the loop alone takes O(N) time complexity. Those hmap.put
(an insert operation) and hmap.get
(a find operations) take O(N) and they are nested within the loop. So normally I would think this function takes O(N^2) times. Why it instead takes O(N)?.
解决方案
The algorithm first iterates the array of numbers, of size n
, to generate the map with counts of occurrences. It should be clear why this is an O(n)
operation. Then, after the hashmap has been built, it iterates that map and finds all entries whose counts are odd numbers. The size of this map would in practice be somewhere between 1 (in the case of all input numbers being the same), and n
(in the case where all inputs are different). So, this second operation is also bounded by O(n)
, leaving the entire algorithm O(n)
.
推荐阅读
- svn - 什么是与 TortoiseSVN 清理选项等效的 svn 命令行,可以清除所有本地更改?
- python-3.x - Python 数字三角形
- html - 我怎样才能让字体真棒图标没有文字装饰?
- java - 如何从字符串中删除尾随逗号(Java)
- python - 熊猫数据框操作以总结天数,直到出现某些状态
- python - Python:值错误:“她”不在列表中
- ruby-on-rails - 如何在 Ruby/Rails 中显示会话变量的值?
- laravel - 我在 Laravel Forge 上的新域重定向到另一个域
- javascript - immer 如何处理带有地图和集合的对象键?
- c++ - 异常在构造函数 try 块中被捕获并处理,但仍被再次抛出