diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index 64503cef..18b1de9b 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -266,6 +266,28 @@ var canConstruct = function(ransomNote, magazine) { }; ``` +Swift: +```swift +func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool { + var record = Array(repeating: 0, count: 26); + let aUnicodeScalarValue = "a".unicodeScalars.first!.value + for unicodeScalar in magazine.unicodeScalars { + // 通过record 记录 magazine 里各个字符出现的次数 + let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue) + record[idx] += 1 + } + for unicodeScalar in ransomNote.unicodeScalars { + // 遍历 ransomNote,在record里对应的字符个数做 -- 操作 + let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue) + record[idx] -= 1 + // 如果小于零说明在magazine没有 + if record[idx] < 0 { + return false + } + } + return true +} +``` ----------------------- diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index 4e61dc2f..1c3f45e7 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -220,8 +220,33 @@ var fourSumCount = function(nums1, nums2, nums3, nums4) { }; ``` - - +Swift: +```swift +func fourSumCount(_ nums1: [Int], _ nums2: [Int], _ nums3: [Int], _ nums4: [Int]) -> Int { + // key:a+b的数值,value:a+b数值出现的次数 + var map = [Int: Int]() + // 遍历nums1和nums2数组,统计两个数组元素之和,和出现的次数,放到map中 + for i in 0 ..< nums1.count { + for j in 0 ..< nums2.count { + let sum1 = nums1[i] + nums2[j] + map[sum1] = (map[sum1] ?? 0) + 1 + } + } + // 统计a+b+c+d = 0 出现的次数 + var res = 0 + // 在遍历大num3和num4数组,找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来。 + for i in 0 ..< nums3.count { + for j in 0 ..< nums4.count { + let sum2 = nums3[i] + nums4[j] + let other = 0 - sum2 + if map.keys.contains(other) { + res += map[other]! + } + } + } + return res +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)