File tree Expand file tree Collapse file tree 5 files changed +92
-0
lines changed
product-of-array-except-self
validate-binary-search-tree Expand file tree Collapse file tree 5 files changed +92
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func threeSum( _ nums: [ Int ] ) -> [ [ Int ] ] {
3
+ let nums = nums. sorted ( )
4
+ var answer : Set < [ Int ] > = [ ]
5
+ for (index, num) in nums. enumerated ( ) {
6
+ var leftIndex = index + 1
7
+ var rightIndex = nums. endIndex - 1
8
+ while leftIndex < rightIndex {
9
+ let sum = num + nums[ leftIndex] + nums[ rightIndex]
10
+ if sum == 0 {
11
+ answer. insert ( [ num, nums [ leftIndex] , nums [ rightIndex] ] )
12
+ leftIndex += 1
13
+ rightIndex -= 1
14
+ } else if sum < 0 {
15
+ leftIndex += 1
16
+ } else if sum > 0 {
17
+ rightIndex -= 1
18
+ }
19
+ }
20
+ }
21
+
22
+ return Array ( answer)
23
+ }
24
+ }
25
+
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func climbStairs( _ n: Int ) -> Int {
3
+ var dictionary : [ Int : Int ] = [ : ]
4
+ for i in 1 ... n {
5
+ if i < 3 {
6
+ dictionary [ i] = i
7
+ } else {
8
+ if let value1 = dictionary [ i - 1 ] ,
9
+ let value2 = dictionary [ i - 2 ] {
10
+ dictionary [ i] = value1 + value2
11
+ }
12
+ }
13
+ }
14
+ return dictionary [ n] ?? 0
15
+ }
16
+ }
17
+
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func productExceptSelf( _ nums: [ Int ] ) -> [ Int ] {
3
+ var answer : [ Int ] = Array ( repeating: 1 , count: nums. endIndex)
4
+ for i in 1 ..< nums. endIndex {
5
+ answer [ i] = answer [ i - 1 ] * nums[ i - 1 ]
6
+ }
7
+
8
+ var suffix = 1
9
+ for i in ( 0 ..< nums. endIndex) . reversed ( ) {
10
+ answer [ i] *= suffix
11
+ suffix *= nums [ i]
12
+ }
13
+
14
+ return answer
15
+ }
16
+ }
17
+
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func isAnagram( _ s: String , _ t: String ) -> Bool {
3
+ var sDictionary : [ Character : Int ] = [ : ]
4
+ var tDictionary : [ Character : Int ] = [ : ]
5
+ for char in s {
6
+ sDictionary [ char] = ( sDictionary [ char] ?? 0 ) + 1
7
+ }
8
+ for char in t {
9
+ tDictionary [ char] = ( tDictionary [ char] ?? 0 ) + 1
10
+ }
11
+ return sDictionary == tDictionary
12
+ }
13
+ }
14
+
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ private var prev : Int ?
3
+
4
+ func isValidBST( _ root: TreeNode ? ) -> Bool {
5
+ inorder ( root)
6
+ }
7
+
8
+ private func inorder( _ root: TreeNode ? ) -> Bool {
9
+ guard let root = root else { return true }
10
+
11
+ guard inorder ( root. left) else { return false }
12
+
13
+ if let prev = prev, root. val <= prev { return false }
14
+ prev = root. val
15
+
16
+ return inorder ( root. right)
17
+ }
18
+ }
19
+
You can’t perform that action at this time.
0 commit comments