Skip to content

Commit 4c9c04e

Browse files
authored
Add syntax color for code
1 parent ffc4ee7 commit 4c9c04e

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

3Sum and 4Sum/README.md

+7-7
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ You'll make use of these two rules to create an efficient algorithm.
2626

2727
Since you pre-sort the array, duplicates will be adjacent to each other. You just need to skip over duplicates by comparing adjacent values:
2828

29-
```
29+
```swift
3030
extension Collection where Element: Equatable {
3131

3232
/// In a sorted collection, replaces the given index with a successor mapping to a unique element.
@@ -44,7 +44,7 @@ extension Collection where Element: Equatable {
4444

4545
A similar implementation is used to get the unique index *before* a given index:
4646

47-
```
47+
```swift
4848
extension BidirectionalCollection where Element: Equatable {
4949

5050
/// In a sorted collection, replaces the given index with a predecessor that maps to a unique element.
@@ -64,15 +64,15 @@ extension BidirectionalCollection where Element: Equatable {
6464

6565
You'll keep track of 3 indices to represent the 3 numbers. The sum at any given moment is `array[l] + array[m] + array[r]`:
6666

67-
```
67+
```swift
6868
m -> <- r
6969
[-4, -1, -1, 0, 1, 2]
7070
 l
7171
```
7272

7373
The premise is quite straightforward (given that you're familiar with 2Sum). You'll iterate `l` through the array. For every iteration, you also apply the 2Sum algorithm to elements after `l`. You'll check the sum every time you moving the indices to check if you found match. Here's the algorithm:
7474

75-
```
75+
```swift
7676
func threeSum<T: BidirectionalCollection>(_ collection: T, target: T.Element) -> [[T.Element]] where T.Element: Numeric & Comparable {
7777
let sorted = collection.sorted()
7878
var ret: [[T.Element]] = []
@@ -110,23 +110,23 @@ func threeSum<T: BidirectionalCollection>(_ collection: T, target: T.Element) ->
110110

111111
Foursum is a very straightforward extension to the threeSum algorithm. In threeSum, you kept track of 3 indices:
112112

113-
```
113+
```swift
114114
m -> <- r
115115
[-4, -1, -1, 0, 1, 2]
116116
 l
117117
```
118118

119119
For fourSum, you'll keep track of 4:
120120

121-
```
121+
```swift
122122
mr -> <- r
123123
[-4, -1, -1, 0, 1, 2]
124124
 l ml ->
125125
```
126126

127127
Here's the code for it (notice it is very similar to 3Sum):
128128

129-
```
129+
```swift
130130
func fourSum<T: BidirectionalCollection>(_ collection: T, target: T.Element) -> [[T.Element]] where T.Element: Numeric & Comparable {
131131
let sorted = collection.sorted()
132132
var ret: [[T.Element]] = []

0 commit comments

Comments
 (0)