|
1 | 1 | class Solution {
|
2 | 2 |
|
3 |
| -func binarySearch<T:Comparable>(inputArr: [T], searchItem: T) -> Int? { |
4 |
| - var lowerIndex = 0 |
5 |
| - var upperIndex = inputArr.count - 1 |
6 |
| - |
7 |
| - while (lowerIndex < upperIndex) { |
8 |
| - let currentIndex = (lowerIndex + upperIndex)/2 |
9 |
| - if (inputArr[currentIndex] <= searchItem) { |
10 |
| - lowerIndex = currentIndex + 1 |
11 |
| - } else { |
12 |
| - upperIndex = currentIndex |
13 |
| - }} |
14 |
| - |
15 |
| - if (inputArr[upperIndex] <= searchItem) {return upperIndex + 1} |
16 |
| - return lowerIndex |
17 |
| - |
18 |
| -} |
19 |
| - |
20 |
| - |
21 |
| -func jobScheduling(_ startTime: [Int], _ endTime: [Int], _ profit: [Int]) -> Int { |
22 |
| - let zipList = zip(zip(startTime, endTime), profit) |
23 |
| - var table: [(startTime:Int, endTime:Int, profit:Int, cumsum: Int)] = [] |
24 |
| - |
25 |
| - for ((x,y),z) in zipList { |
26 |
| - table.append((x,y,z, 0)) |
27 |
| - } |
28 |
| - table.sort(by: {$0.endTime < $1.endTime}) |
29 |
| - let sortedEndTime = endTime.sorted() |
30 |
| - |
31 |
| - var profits: [Int] = [0] |
32 |
| - for iJob in table { |
33 |
| - let index: Int! = binarySearch(inputArr: sortedEndTime, searchItem: iJob.startTime) |
34 |
| - if profits.last! < profits[index] + iJob.profit { |
35 |
| - profits.append(profits[index] + iJob.profit) |
36 |
| - } else { |
37 |
| - profits.append(profits.last!) |
38 |
| - } |
39 |
| - } |
40 |
| - return (profits.last!) |
41 |
| - } |
| 3 | + func binarySearch<T: Comparable>(inputArr: [T], searchItem: T) -> Int? { |
| 4 | + var lowerIndex = 0 |
| 5 | + var upperIndex = inputArr.count - 1 |
| 6 | + |
| 7 | + while lowerIndex < upperIndex { |
| 8 | + let currentIndex = (lowerIndex + upperIndex) / 2 |
| 9 | + if inputArr[currentIndex] <= searchItem { |
| 10 | + lowerIndex = currentIndex + 1 |
| 11 | + } else { |
| 12 | + upperIndex = currentIndex |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + if inputArr[upperIndex] <= searchItem { |
| 17 | + return upperIndex + 1 |
| 18 | + } |
| 19 | + return lowerIndex |
| 20 | + } |
| 21 | + |
| 22 | + func jobScheduling(_ startTime: [Int], _ endTime: [Int], _ profit: [Int]) -> Int { |
| 23 | + let zipList = zip(zip(startTime, endTime), profit) |
| 24 | + var table: [(startTime: Int, endTime: Int, profit: Int, cumsum: Int)] = [] |
| 25 | + |
| 26 | + for ((x, y), z) in zipList { |
| 27 | + table.append((x, y, z, 0)) |
| 28 | + } |
| 29 | + table.sort(by: { $0.endTime < $1.endTime }) |
| 30 | + let sortedEndTime = endTime.sorted() |
| 31 | + |
| 32 | + var profits: [Int] = [0] |
| 33 | + for iJob in table { |
| 34 | + let index: Int! = binarySearch(inputArr: sortedEndTime, searchItem: iJob.startTime) |
| 35 | + if profits.last! < profits[index] + iJob.profit { |
| 36 | + profits.append(profits[index] + iJob.profit) |
| 37 | + } else { |
| 38 | + profits.append(profits.last!) |
| 39 | + } |
| 40 | + } |
| 41 | + return profits.last! |
| 42 | + } |
42 | 43 | }
|
0 commit comments