给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。
如果数组中每个元素都不相同,则返回 false。
[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() |
[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=newArrayList<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=newArrayList<Integer>(); list.add(0); list.add(0); boolean rest=four.find(list); assertTrue(rest); } @Test publicvoid 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]
测试结果: