題目:
給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,
下標 ,a ,b , c 對應數相加等於 targe 找出所有滿足條件且不重復的三元組下標
解析:
在一個list里面找出來三個數字使這三個數字相加等於目標targe,
這里是一個list 我們去循環這里面的元素,我們利用for循環, 第一個取來,然后后剩下的元素分別取循環上一個循環剩下的元素。這樣保證了不重復,最后驗證下,如果找出來的數字的值滿足a+b+c=targe ,且三個數不相等,我們認為查詢正確。
那么我們看下python代碼是如何實現的
def findthree(nums:list,targe:int): if len(nums)<3: return False result=[] for a in range(len(nums)): for b in range(len(nums))[a:]: for c in range(len(nums))[b:]: try: if nums[a]+nums[b]+nums[c]==targe and a!=b and b!=c and a!=c : result.append((a,b,c)) except: return False return result
那么我們看下測試代碼
import unittest from findthree import findthree class TestCae(unittest.TestCase): def setUp(self) -> None: pass def tearDown(self) -> None: pass def testone(self): reslt=findthree([],6) self.assertFalse(reslt) def testtwo(self): reslt = findthree([1], 6) self.assertFalse(reslt) def testthree(self): reslt = findthree([1,'2'], 6) self.assertFalse(reslt) def testFor(self): reslt = findthree([1,'2',"2"], 6) self.assertFalse(reslt) def testfive(self): reslt = findthree([1,2,3], 6) self.assertEqual(reslt,[(0,1,2)]) def testsix(self): reslt = findthree([1,2,3,3], 6) self.assertEqual(reslt,[(0,1,2),(0,1,3)]) if __name__=="__main__": unittest.main()
看下運行結果:
看下最后代碼的覆蓋率
這樣我們就測試完畢我們寫的代碼了。 那么我們認為目前測試用例覆蓋了百分之百路徑下面所有的分支,認為代碼沒有bug,測試通過。
接下來,我們看下java版本的實現
public class Fintrhee { public List<Map<String,Integer>> find(List<Integer> list, Integer targert){ List<Map<String,Integer>> resultList=new ArrayList<>(); if (list.size()<3){ return null; } for (int a=0;a<list.size();a++ ){ for(int b=a;b<list.size();b++){ for(int c=b;c<list.size();c++){ if (list.get(a)+list.get(b)+list.get(c)==targert && !new Integer(a).equals(new Integer(b))&&!new Integer(a).equals(new Integer(c))&&!new Integer(c).equals(new Integer(b))){ Map<String,Integer> map=new HashMap<>(); map.put("a",a); map.put("b",b); map.put("c",c); resultList.add(map); } } } } return resultList; } }
測試代碼:
public class FintrheeTest { @Test public void testFind() { Fintrhee fintrhee=new Fintrhee(); List<Integer> integerList=new ArrayList<>(); integerList.add(0); List<Map<String,Integer>> maps=fintrhee.find(integerList,1); assertEquals(null,maps); } @Test public void test2Find() { Fintrhee fintrhee=new Fintrhee(); List<Integer> integerList=new ArrayList<>(); integerList.add(1); integerList.add(2); integerList.add(3); List<Map<String,Integer>> maps=fintrhee.find(integerList,1); List<Map<String,Integer>> mapList=new ArrayList<>(); assertEquals(maps,mapList); } @Test public void test3Find() { Fintrhee fintrhee=new Fintrhee(); List<Integer> integerList=new ArrayList<>(); integerList.add(1); integerList.add(2); integerList.add(3); List<Map<String,Integer>> maps=fintrhee.find(integerList,6); List<Map<String,Integer>> mapList=new ArrayList<>(); Map<String,Integer> map=new HashMap<>(); map.put("a",0); map.put("b",1); map.put("c",2); mapList.add(map); assertEquals(maps,mapList); } }
測試結果:
覆蓋率:
刷題還在繼續,文章優化在下面公眾號首發,