我完全熟悉哈希表和哈希的工作原理,但我试图完全理解O(1)是如何完全来自的。
set1 = {'s','t'}
print('x' in set1)
print('s' in set1)
set2 = {'s'}
print('s' in set2)
Run Code Online (Sandbox Code Playgroud)
我被告知要检查是否's'在 set1 中,if 将检查 的哈希值的内存分配's',并检查它是否在O(1)中的 set1 中并返回布尔值。因此两个 O(1) 操作,但我的问题是:散列实际上如何深入工作。我的意思是,当您 hash 时's',该散列是否有类似的东西set1,set2并且您正在检查是否set1为set1或set2,或者每个集合是否具有不同的散列's'并且您正在检查's'每个不同集合的散列。
我对想澄清的字典和哈希表有些困惑,假设我有当前的字典以及当前python运行的哈希值的当前输出。
Dict = dict()
print(hash('a'))
print(hash('b'))
print(hash('c'))
Dict['a'] = 1
Dict['b'] = 2
Dict['c'] = 3
print(Dict)
Run Code Online (Sandbox Code Playgroud)
具有的输出
1714333803
1519074822
1245896149
{'a': 1, 'c': 3, 'b': 2}
Run Code Online (Sandbox Code Playgroud)
因此,据我所知,哈希表只是一个数组,其中哈希是哈希表的索引。例如,“ a”的哈希值为1714333803,因此我的哈希表索引1714333803的值为“ a”。因此,我感到困惑的是,哈希表有多少个索引以及哈希函数如何产生答案?它使用模数并且具有固定范围的索引吗?因为给定的字典打印结果输出{'a': 1, 'c': 3, 'b': 2},但是即使假设它输出也正确,但实际上该字典实际上是至少1714333803索引的数组,因为包含3个元素似乎太可笑了,更不用说浪费了多少的空间。同样对于散列表,索引中没有值的内容为null吗?
Python developer here. I am using JavaScript to run the following command,
let a = [1, 2, 3];
let b , c, d = a;
console.log(b);
console.log(c);
console.log(d);
Run Code Online (Sandbox Code Playgroud)
To my surprise, b and c are undefined while d is the entire a variable. I later realize that I am meant to go let [b, c, d] = a;, however I am just trying to understand what is happening and why they're undefined.
public int[] biggerTwo(int[] a, int[] b) {
int suma = 0;
int sumb = 0;
for(int x = 0; x < a.length; x ++){
a[x] += suma;
}
for(int x = 0; x < b.length; x ++){
b[x] += sumb;
}
if(suma >= sumb)
return a;
else
return b;
}
Run Code Online (Sandbox Code Playgroud)
这是我写的代码,用于返回具有最大总和的列表.在CodingBat我只在两次测试中弄错了.
biggerTwo({1, 2}, {3, 4}) Mine returns {1,2}
biggerTwo({1, 1}, {1, 2}) Mine returns {1,1}
Run Code Online (Sandbox Code Playgroud)
其他一切都是正确的,我不知道为什么.另外,在else语句中我注意到,最初我还有其他if(sumb> suma),我更改为其他知道是否!(suma> = sumb)这意味着sumb> suma,但是当我键入时它会导致错误否则如果?
如果有人能看到错误,我会很感激:D