标签:var png 手动 bre 固定 thml color sum nbsp
给定一个包含n个整数的数组nums,判断nums中是否存在三个元素a,b,c,使得a + b + c = 0?找出满足所有满足条件的且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]
思路如下:
var nums = [-1, 0, 1, 2, -1, -4] func threeSum(_ nums: [Int]) -> [[Int]] { guard nums.count > 2 else {return [] }//数组长度小于等于2,则返回空 let numsSort = nums.sorted()//数组排序 var resultArr = [[Int]]() for i in 0..<numsSort.count { if i > 0 && numsSort[i] == numsSort[i - 1] {continue}//重复过滤 let target = 0 - numsSort[i] //将a + b + c = 0,转化为 a + b = -c var low: Int = i + 1 var high: Int = numsSort.count - 1 while low < high { let sum = numsSort[low] + numsSort[high] if sum == target { let result = [numsSort[i], numsSort[low],numsSort[high]] resultArr.append(result) while low < high && numsSort[low] == numsSort[low + 1] { low = low + 1 } while low < high && numsSort[high] == numsSort[high - 1]{ high = high - 1 } low = low + 1 high = high - 1 } else if sum < target { low = low + 1 } else { high = high - 1 } } } return resultArr } var results: [[Int]] = threeSum(nums)
思路如下:
numsSorted[low]和numsSorted[high],计算三个数的是否为target = 0,如果满足则添加进结果集
2. 如果numsSorted[i]大于0,如果已经排好序之后,则三数之和必然无法等于0,结束循环
3. 如果 numsSorted[i] == numsSorted[i−1],则说明该数字重复,会导致结果重复,所以应该跳过
4. 当sum == 0 ,numsSorted[low] == numsSorted[low + 1]则会导致结果重复,应该跳过
5. 当sum == 0 ,numsSorted[high] == numsSorted[high + 1]则会导致结果重复,应该跳过
var nums = [-1, 0, 1, 2, -1, -4] func threeSum(_ nums: [Int]) -> [[Int]] { guard nums.count > 2 else {return []} var resultArr = [[Int]]() var numsSorted: [Int] = nums.sorted() for i in 0..<numsSorted.count { if numsSorted[i] > 0 {break} if i > 0 && numsSorted[i] == numsSorted[i - 1] {continue} var low = i + 1 var high = numsSorted.count - 1 while low < high { let target = numsSorted[i] + numsSorted[low] + numsSorted[high] if target == 0 { let result: [Int] = [numsSorted[i], numsSorted[low], numsSorted[high]] resultArr.append(result) while (low < high && numsSorted[low] == numsSorted[low + 1]) { // low ++//在swift3中low++被移除了 low += 1 } while low < high && numsSorted[high] == numsSorted[high - 1] { high -= 1 } low += 1 high -= 1 } else if target < 0 { low += 1 } else { high -= 1 } } } return resultArr } var results: [[Int]] = threeSum(nums) print(results)
上面的两份代码可以直接运行查看结果,都是如下
如果想进大公司,还是希望大家能手动敲写一下,对自己还是很有用的!!!
标签:var png 手动 bre 固定 thml color sum nbsp
原文地址:https://www.cnblogs.com/guohai-stronger/p/11735699.html