标签:int 15 nums 3Sum list i1 length listElem leetCode
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
有空没空也得记得刷道题啊,不然乍一敲代码手生的很啊。
1 class Solution { 2 public List<List<Integer>> threeSum(int[] nums) { 3 List<List<Integer>> list = new ArrayList<>();//存放List<Integer>数组元素 4 Arrays.sort(nums); 5 int length = nums.length; 6 for (int i = 0; i < length-2; i++) { 7 if (i != 0 && nums[i] == nums[i-1]) 8 continue; 9 for (int j = i+1; j < length-1; j++) { 10 if (nums[i] + nums[j] + nums[length-1] < 0) 11 continue; 12 int th = nums[i] + nums[j]; 13 if(th > 0)//确保nums[i]+nums[j] < 0 14 continue; 15 16 for (int i1 = nums.length - 1; i1 > j; i1--) { 17 if (nums[i1] + th == 0) { 18 if (list.size() > 0) { 19 List<Integer> l = list.get(list.size()-1); 20 if (l.get(0) == nums[i] && l.get(1) == nums[j] && l.get(2) == nums[i1]) { 21 break; 22 } 23 } 24 ArrayList<Integer> listElem = new ArrayList<>(); 25 listElem.add(nums[i]); 26 listElem.add(nums[j]); 27 listElem.add(nums[i1]); 28 list.add(listElem); 29 break; 30 } 31 else if (nums[i1] + th < 0) 32 break; 33 } 34 } 35 } 36 37 return list; 38 } 39 }
标签:int,15,nums,3Sum,list,i1,length,listElem,leetCode 来源: https://www.cnblogs.com/yfs123456/p/10888385.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。