判断一个元素是否在一个集合中
2004-12-22 11:52
405 查看
出自http://community.csdn.net/Expert/TopicView1.asp?id=3660145
QuickKeyBoard()
这样的问题在noi教学中属于基础问题,当你要看一个元素是否在一个集合中时,利用Hash散列表的效率最高。代码我已经写好了,复杂度:5000+5000。delphi5下通过:
program AB5000;
{$APPTYPE CONSOLE}
const
MaxVal = 30000;
var
a, b: array [0..5000] of Integer;
d: array [0..MaxVal-1] of Byte;
i: Integer;
begin
// 向数组a,b中填入随机数据。
Randomize;
for i:=0 to 5000 do
begin
a[i] := Random(MaxVal);
b[i] := Random(MaxVAl);
end;
// 清空Hash表
FillChar(d, 30000*Sizeof(Byte), 0);
// 构造数组a的Hash表
for i:=0 to 5000 do
Inc(d[a[i] mod MaxVal]);
// 在数组a的Hash表中查找数组b的元素
for i:=0 to 5000 do
if d[b[i] mod MaxVal]<>0 then
Write(b[i], ' ');
Writeln;
Readln;
end.
如果是字符串数组的话,那么,改变一下Hash函数即可。我上面用的Hash函数是“求余数”,对于字符串,可以考虑使用执行连接格式(ELF)Hash函数,代码如下:
function ELFHash(var s: String): Integer;
var
g, h, i: LongWord;
begin
h := 0;
for i:=1 to Length(s) do
begin
h := h shl 4 + Ord(s[i]);
g := h and $f0000000;
if g <> 0 then
h := h xor (g shr 24);
h := h and (not g);
end;
ELFHash := h mod M;
end;
这个Hash函数最早用于Unix系统的文件系统,对长短字符串都很有效,对不同的s,冲突的概率非常的小。其中的M是Hash表的大小。
QuickKeyBoard()
这样的问题在noi教学中属于基础问题,当你要看一个元素是否在一个集合中时,利用Hash散列表的效率最高。代码我已经写好了,复杂度:5000+5000。delphi5下通过:
program AB5000;
{$APPTYPE CONSOLE}
const
MaxVal = 30000;
var
a, b: array [0..5000] of Integer;
d: array [0..MaxVal-1] of Byte;
i: Integer;
begin
// 向数组a,b中填入随机数据。
Randomize;
for i:=0 to 5000 do
begin
a[i] := Random(MaxVal);
b[i] := Random(MaxVAl);
end;
// 清空Hash表
FillChar(d, 30000*Sizeof(Byte), 0);
// 构造数组a的Hash表
for i:=0 to 5000 do
Inc(d[a[i] mod MaxVal]);
// 在数组a的Hash表中查找数组b的元素
for i:=0 to 5000 do
if d[b[i] mod MaxVal]<>0 then
Write(b[i], ' ');
Writeln;
Readln;
end.
如果是字符串数组的话,那么,改变一下Hash函数即可。我上面用的Hash函数是“求余数”,对于字符串,可以考虑使用执行连接格式(ELF)Hash函数,代码如下:
function ELFHash(var s: String): Integer;
var
g, h, i: LongWord;
begin
h := 0;
for i:=1 to Length(s) do
begin
h := h shl 4 + Ord(s[i]);
g := h and $f0000000;
if g <> 0 then
h := h xor (g shr 24);
h := h and (not g);
end;
ELFHash := h mod M;
end;
这个Hash函数最早用于Unix系统的文件系统,对长短字符串都很有效,对不同的s,冲突的概率非常的小。其中的M是Hash表的大小。
相关文章推荐
- 描述一个运行时间为O(nlgn)的算法,使之能在给定一个由n个整数构成的集合S和另一个整数 X 时,判断出S中是否存在有两个其和刚好等于 X 的元素。
- Java判断一个值,或者对象是否存在list集合中和去掉list集合中重复的元素
- 题目1.请给出一个运行时间为O(nlgn)的算法,使之能在给定一个由n个整数构成的集合S和另一个证书x时,判断出S中是否存在有两个其和等于x的元素。
- 给出一个实数集合和一个实数,怎样判断集合中是否存在两个和等于该实数的元素
- 判断一个元素是否在集合中
- SDUT 离散题目2 判断一个集合元素是否重复
- 题目:请给出一个运行时间为Θ(nlgn)的算法,使之能在给定一个由n个整数构成的集合S和另一个整数x时,判断出S中是否存在有两个其和等于x的元素。
- 通过set集合判断一个集合的元素是否重复
- 元素出栈、入栈顺序的合法性(判断一个字符串是否按照出栈顺序)
- 如何判断一个整数数组中是否有重复元素?要求时间复杂度O(n),空间复杂度O(1)
- POJ 1703 Find them, Catch them 并查集 (关系问题 判断是否在一个集合)
- Bloom Filter(布隆过滤器)用于 检查一个元素是否在集合中
- 在JSP使用EL和JSTL判断指定元素是否存在于指定集合中
- js数组判断是否含有某一个元素
- 四道有趣的单链表面试题(单链表反序、找出链表的中间元素、链表排序、判断一个单链表是否有环)
- 基于MATLAB的高等数学 判断:元素是否属于集合
- JSTL判断一个list集合里是否包含某个字符串
- 怎么使用jquery判断一个元素是否含有一个指定的类(class)
- 如何判断一个整数数组中是否有重复元素
- R语言判断向量中是否存在一个元素