判断是否存在重复元素

326 阅读2分钟
题目:
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。
如果数组中每个元素都不相同,则返回 false。
​ ​解析:给定数组,数组有重复元素,就返回true,没有返回false,这是典型的用list和for循环的题。​思路:for循环遍历list,去判断第一个 和剩余的是否存在相等的,有相等的 代表存在重复元素,返回true,否则,返回false。
​​ 我们看python版本怎么实现的,代码如下​:

[backcolor=rgb(255, 255, 255) !important][size=1em]
1

2

3

4

5

6

def listfind(nums:list)->int:
for i in range(len(nums)):
for j in range(len(nums))[i:]:
if nums[j]==nums and j!=i:
return True
return False




​ 测试代码:
[backcolor=rgb(255, 255, 255) !important][size=1em]
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

import unittest
from four import listfind
class TestCae(unittest.TestCase):
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
def testone(self):
reslt=listfind([])
self.assertFalse(reslt)
def testtwo(self):
reslt=listfind([1])
self.assertFalse(reslt)
def testthree(self):
reslt=listfind([1,1])
self.assertTrue(reslt)
if __name__=="__main__":
unittest.main()




测试结果
​测试代码覆盖率:
​python版本的实现还是不是特别难的,比较容易理解,我们接下来看下java版本是如何实现的​?
​实现代码:
[backcolor=rgb(255, 255, 255) !important][size=1em]
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

public class Four {

public boolean find(List<Integer> list) {
for (int a = 0; a < list.size(); a++) {
for (int b = a; b < list.size(); b++) {
if (list.get(a).equals(list.get(b)) && !new Integer(a).equals(new Integer(b))) {
return true;
}
}
}
return false;
}


}




测试代码:
[url=]
[/url]

public
class
FourTest { @Test
public
void
testFind() { Four four=
new
Four(); List<Integer> list=
new
ArrayList<Integer>();
boolean
rest=four.find(list); assertFalse(rest); } @Test
public
void
testFind2() { Four four=
new
Four(); List<Integer> list=
new
ArrayList<Integer>(); list.add(0);
boolean
rest=four.find(list); assertFalse(rest); } @Test
public
void
testFind3() { Four four=
new
Four(); List<Integer> list=
new
ArrayList<Integer>(); list.add(0); list.add(0);
boolean
rest=four.find(list); assertTrue(rest); } @Test
public
void
testFind4() { Four four=
new
Four(); List<Integer> list=
new
ArrayList<Integer>(); list.add(0); list.add(1); list.add(0);
boolean
rest=four.find(list); assertTrue(rest); }}
[url=]
[/url]





测试结果:
代码覆盖率:
我们通过python和java两个版本的实现,可以看出来,其实有些问题的解决出来,并不是那么难,关键是在于思路,与没有一个合理的思路去解决这个问题。 有了好的思路,还要去实现,用代码去实现自己的想法,实现后,增加相对应的校验,并且辅助测试代码进行测试。