@@ -12,21 +12,21 @@ class Solution {}
1212 */
1313
1414extension Solution {
15- class func twoSum( nums: [ Int ] , _ target: Int ) -> [ Int ] {
16-
17- guard nums. count > 1 else { return [ ] }
18-
19- var map = [ Int: Int] ( )
20-
21- for i in 0 ..< nums. count {
15+ class func twoSum( nums: [ Int ] ? , _ target: Int ) -> [ Int ] ? {
16+
17+ guard let nums = nums , nums . count > 1 else { return nil }
18+
19+ var map = [ Int: Int] ( )
20+
21+ for i in 0 ..< nums. count {
2222 if let value = map [ nums [ i] ] {
2323 return [ value + 1 , i + 1 ]
2424 }
25-
25+
2626 map [ target - nums[ i] ] = i
2727 }
28-
29- return [ ]
28+
29+ return nil
3030 }
3131}
3232
@@ -35,9 +35,46 @@ extension Solution {
3535 */
3636
3737let twoSumNums = [ 2 , 7 , 11 , 15 ]
38- let target = 9
38+ let twoSumTarget = 9
3939
40- Solution . twoSum ( nums: twoSumNums, target)
40+ Solution . twoSum ( nums: twoSumNums, twoSumTarget)
41+
42+ /**
43+ * 167. Two Sum II - Input arary is sorted
44+ * https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
45+ */
46+
47+ extension Solution {
48+ class func twoSumII( nums: [ Int ] ? , _ target: Int ) -> [ Int ] ? {
49+ guard let nums = nums, nums. count > 1 else { return nil }
50+
51+ var start = 0
52+ var end = nums. count - 1
53+
54+ while start < end {
55+ if nums [ start] + nums[ end] == target {
56+ return [ start + 1 , end + 1 ]
57+ }
58+
59+ if nums [ start] + nums[ end] < target {
60+ start += 1
61+ } else {
62+ end -= 1
63+ }
64+ }
65+
66+ return nil
67+ }
68+ }
69+
70+ /*:
71+ ### Usage
72+ */
73+
74+ let twoSumIINums = [ 2 , 7 , 11 , 15 ]
75+ let twoSumIITarget = 9
76+
77+ Solution . twoSum ( nums: twoSumIINums, twoSumIITarget)
4178
4279/**
4380 * 217. Contains Duplicate
@@ -47,10 +84,10 @@ Solution.twoSum(nums: twoSumNums, target)
4784extension Solution {
4885 class func containsDuplicate( nums: [ Int ] ? ) -> Bool {
4986 guard let nums = nums, nums. count > 1 else { return false }
50-
87+
5188 return nums. count > Set ( nums) . count
5289 }
53-
90+
5491}
5592
5693/*:
@@ -69,20 +106,20 @@ Solution.containsDuplicate(nums: nums2)
69106 */
70107
71108extension Solution {
72- class func containsDuplicateII( nums: [ Int ] ? , _ k: Int ) -> Bool {
109+ class func containsDuplicateII( nums: [ Int ] ? , _ k: Int ) -> Bool {
73110 guard let nums = nums, nums. count > 1 else { return false }
74-
111+
75112 var dict = [ Int: Int] ( )
76-
113+
77114 for i in 0 ..< nums. count {
78115 guard let index = dict [ nums [ i] ] , i - index <= k else {
79116 dict [ nums [ i] ] = i
80117 continue
81118 }
82-
119+
83120 return true
84121 }
85-
122+
86123 return false
87124 }
88125}
@@ -94,4 +131,3 @@ extension Solution {
94131Solution . containsDuplicateII ( nums: nums1, 3 )
95132Solution . containsDuplicateII ( nums: nums1, 5 )
96133Solution . containsDuplicateII ( nums: nums2, 2 )
97-
0 commit comments