File tree 1 file changed +60
-0
lines changed
scripts/algorithms/M/Minimum Time to Repair Cars
1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 816 ms (Top 100.0%) | Memory: 11.80 MB (Top 100.0%)
2
+
3
+ type Target = i64 ;
4
+ type UseValue = i64 ;
5
+ fn lower_bound ( arr : & Vec < Target > , x : & UseValue ) -> usize {
6
+ let mut low = 0 ;
7
+ let mut high = arr. len ( ) ;
8
+ while low != high {
9
+ let mid = ( low + high) / 2 ;
10
+ match arr[ mid] . cmp ( x) {
11
+ std:: cmp:: Ordering :: Less => {
12
+ low = mid + 1 ;
13
+ }
14
+ std:: cmp:: Ordering :: Equal | std:: cmp:: Ordering :: Greater => {
15
+ high = mid;
16
+ }
17
+ }
18
+ }
19
+ low
20
+ }
21
+ impl Solution {
22
+ pub fn repair_cars ( ranks : Vec < i32 > , cars : i32 ) -> i64 {
23
+ let n = ranks. len ( ) ;
24
+ let cars = cars as i64 ;
25
+
26
+ if n == 1 {
27
+ return ranks[ 0 ] as i64 * cars * cars
28
+ }
29
+
30
+ let ranks = ranks. into_iter ( ) . map ( |v| v as i64 ) . collect :: < Vec < i64 > > ( ) ;
31
+ let mut memo = vec ! [ 0 ; 10usize . pow( 6 ) ] ;
32
+ for i in 1 ..10i64 . pow ( 6 ) {
33
+ memo[ i as usize ] = i * i;
34
+ }
35
+
36
+ let mut left = 0 ;
37
+ let mut right = 10i64 . pow ( 10 ) ;
38
+ while left < right {
39
+ let mid = ( left+right) / 2 ;
40
+ let mut temp = 0 ;
41
+
42
+ for i in 0 ..n {
43
+ let num_square = mid / ranks[ i] ;
44
+ let ti = lower_bound ( & memo, & num_square) ;
45
+ if memo[ ti] == num_square {
46
+ temp += ti as i64 ;
47
+ } else {
48
+ temp += ti as i64 - 1 ;
49
+ }
50
+ }
51
+
52
+ if temp < cars {
53
+ left = mid + 1 ;
54
+ } else {
55
+ right = mid;
56
+ }
57
+ }
58
+ right
59
+ }
60
+ }
You can’t perform that action at this time.
0 commit comments