Skip to content

Commit 7115420

Browse files
committed
增加数组方式实现
1 parent 9e90dbd commit 7115420

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

ConatainsDuplicate/ConatainsDuplicate/Program.cs

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,31 @@ static void Main(string[] args)
2929

3030
static bool ContainsDupliacate(int[] nums)
3131
{
32-
/*方法一:采用Dictionary 实现*/
33-
Dictionary<int, int> dictionary = new Dictionary<int, int>();
34-
foreach (int n in nums)
32+
///*方法一:采用Dictionary 实现*/
33+
//Dictionary<int, int> dictionary = new Dictionary<int, int>();
34+
//foreach (int n in nums)
35+
//{
36+
// if (!dictionary.ContainsKey(n)) dictionary.Add(n, 1);
37+
// else return true;
38+
//}
39+
//return false;
40+
41+
/*方法二:采用数组实现(位操作)*/
42+
// 15000 暂定
43+
byte[] table = new byte[15000];
44+
foreach (var item in nums)
3545
{
36-
if (!dictionary.ContainsKey(n)) dictionary.Add(n, 1);
37-
else return true;
46+
// 为什么除以8 ? 考虑到 byte 是8位
47+
int i = item / 8;
48+
int j = item % 8;
49+
byte check =(byte) (1 << j);
50+
if ((table[i] & check) != 0)
51+
{
52+
return true;
53+
}
54+
table[i] |= check;
3855
}
3956
return false;
40-
4157
}
4258
}
4359
}

0 commit comments

Comments
 (0)