forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp0000_template.rs
1864 lines (1582 loc) · 60.6 KB
/
p0000_template.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub struct Solution {}
// problem: https://leetcode.com/problems/find-right-interval/
// discuss: https://leetcode.com/problems/find-right-interval/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
use std::{collections::HashMap, hash::Hash};
use std::collections::BTreeMap;
use std::collections::HashSet;
pub fn left_rightmost_smaller_idx(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut left_rightmost_smaller_idx = vec![-1i32;n];
let mut stack : Vec<usize> = vec![];
for (i, &num) in nums.iter().enumerate() {
while let Some(&last_idx) = stack.last() {
if !(nums[last_idx] < num) {
stack.pop();
} else {
break;
}
}
if let Some(&last_idx) = stack.last() {
left_rightmost_smaller_idx[i] = last_idx as i32;
} else {
left_rightmost_smaller_idx[i] = -1;
}
stack.push(i);
}
left_rightmost_smaller_idx
}
struct UnionFindInt {
parents: Vec<usize>,
subset_sizes: Vec<usize>,
pub max_subset_size: usize,
pub subset_count: usize,
}
impl UnionFindInt {
fn new(element_count : usize) -> UnionFindInt {
let mut uf = UnionFindInt{
parents: (0..element_count).collect(),
subset_sizes: vec![1;element_count],
max_subset_size: 1,
subset_count: element_count};
uf
}
fn find_root(&self, element_id : usize) -> usize {
let mut root = element_id;
while root != self.parents[root] {
root = self.parents[root];
}
root
}
fn find_root_with_compression(&mut self, element_id : usize) -> usize {
let root = self.find_root(element_id);
// path compression
let mut element_id = element_id;
while self.parents[element_id] != root {
let tmp = self.parents[element_id];
self.parents[element_id] = root;
element_id = tmp;
}
root
}
fn union(&mut self, e1 : usize, e2 : usize) -> bool {
let root1 = self.find_root_with_compression(e1);
let root2 = self.find_root_with_compression(e2);
if root1 == root2 { return false; }
if self.subset_sizes[root1] < self.subset_sizes[root2] {
// anchor root1 tree under root2 tree
self.parents[root1] = root2;
self.subset_sizes[root2] += self.subset_sizes[root1];
self.max_subset_size = std::cmp::max(self.max_subset_size, self.subset_sizes[root2]);
} else {
self.parents[root2] = root1;
self.subset_sizes[root1] += self.subset_sizes[root2];
self.max_subset_size = std::cmp::max(self.max_subset_size, self.subset_sizes[root1]);
}
self.subset_count -=1;
true
}
}
struct UnionFind<T :Eq + Hash + Clone> {
parents: HashMap<T,T>,
subset_sizes: HashMap<T, usize>,
pub max_subset_size: usize,
pub subset_count: usize,
}
impl<T : Eq + Hash + Clone> UnionFind<T> {
fn new() -> UnionFind<T> {
let mut uf = UnionFind{
parents: HashMap::new(),
subset_sizes: HashMap::new(),
max_subset_size: 0,
subset_count: 0};
uf
}
fn new_with(elements : &HashSet<T>) -> UnionFind<T> {
let mut uf = UnionFind{
parents: HashMap::new(),
subset_sizes: HashMap::new(),
max_subset_size: 1,
subset_count: elements.len()};
for e in elements {
uf.parents.insert(e.clone(),e.clone());
uf.subset_sizes.insert(e.clone(),1);
}
uf
}
// None if element is not found.
fn find(&self, element : &T) -> Option<T> {
if !self.parents.contains_key(element) {
return None;
}
let mut root = element.clone();
while root != *self.parents.get(&root).unwrap() {
root = self.parents.get(&root).unwrap().clone();
}
Some(root)
}
fn find_along_compression(&mut self, element : &T) -> Option<T> {
if let Some(root) = self.find(element) {
// path compression: redirects each node in the path to the root.
let mut element = element.clone();
while element != *self.parents.get(&element).unwrap() {
let tmp = self.parents[&element].clone();
*self.parents.get_mut(&element).unwrap() = root.clone();
element = tmp;
}
Some(root)
} else {
None
}
}
// return whether the union has performed.
fn union(&mut self, e1 : &T, e2 : &T ) -> bool {
let root1 = self.find_along_compression(e1);
let root2 = self.find_along_compression(e2);
if root1.is_none() {
// assume to insert this e1 and then do union
self.parents.insert(e1.clone(),e1.clone());
self.subset_sizes.insert(e1.clone(),1);
self.subset_count+=1;
}
if root2.is_none() {
// assume to insert this e1 and then do union
self.parents.insert(e2.clone(),e2.clone());
self.subset_sizes.insert(e2.clone(),1);
self.subset_count+=1;
}
let root1= root1.unwrap_or(e1.clone());
let root2= root2.unwrap_or(e2.clone());
if root1 == root2 {return false;}
let root1_size = *self.subset_sizes.get(&root1).unwrap();
let root2_size = *self.subset_sizes.get(&root2).unwrap();
// concat the smaller tress to the larger
if root1_size < root2_size {
*self.parents.get_mut(&root1).unwrap() = root2.clone();
*self.subset_sizes.get_mut(&root2).unwrap() += root1_size;
} else {
*self.parents.get_mut(&root2).unwrap() = root1.clone();
*self.subset_sizes.get_mut(&root1).unwrap() += root2_size;
}
self.max_subset_size = std::cmp::max(self.max_subset_size, root1_size + root2_size);
self.subset_count-=1;
true
}
}
struct BinarySearch {}
impl BinarySearch {
pub fn first_equal(nums: Vec<i32>, target: i32) -> i32 {
let mut low = 0i32;
let mut high = (nums.len() - 1) as i32;
while low <= high {
let mid = (low + high) / 2;
let mid_num = nums[mid as usize];
if mid_num < target {
low = mid + 1;
} else if nums[mid as usize] > target {
high = mid - 1;
} else if 0 < mid && nums[(mid-1) as usize] == mid_num {
high = mid - 1;
} else {
return mid;
}
}
-1
}
pub fn last_equal(nums: Vec<i32>, target: i32) -> i32 {
let mut low = 0i32;
let mut high = (nums.len() - 1) as i32;
while low <= high {
let mid = (low + high) / 2;
let mid_num = nums[mid as usize];
if mid_num < target {
low = mid + 1;
} else if nums[mid as usize] > target {
high = mid - 1; // if mid is usize and mid=0, this wil panic.
} else if (mid as usize) < nums.len() - 1 && nums[(mid+1) as usize] == mid_num {
low = mid + 1;
} else {
return mid;
}
}
-1
}
pub fn first_gt(nums: Vec<i32>, target: i32) -> i32 {
let mut low = 0i32;
let mut high = (nums.len() - 1) as i32;
while low <= high {
let mid = (low + high) / 2;
let mid_num = nums[mid as usize];
// println!("low={}, mid={}, high={}, mid_num={}, target={}", low, mid, high, mid_num, target);
if target < mid_num {
if mid == 0 || nums[(mid-1) as usize] <= target {
return mid;
}
high = mid - 1;
} else {
low = mid + 1;
}
}
-1
}
pub fn first_ge(nums: Vec<i32>, target: i32) -> i32 {
let mut low = 0i32;
let mut high = (nums.len() - 1) as i32;
while low <= high {
let mid = (low + high) / 2;
let mid_num = nums[mid as usize];
// println!("low={}, mid={}, high={}, mid_num={}, target={}", low, mid, high, mid_num, target);
if target <= mid_num {
if mid == 0 || nums[(mid-1) as usize] < target {
return mid;
}
high = mid - 1;
} else {
low = mid + 1;
}
}
-1
}
// assert_eq!(Solution::last_lt(vec![1,1,3,3,5,5],2), 2);
pub fn last_lt(nums: Vec<i32>, target: i32) -> i32 {
let mut low = 0i32;
let mut high = (nums.len() - 1) as i32;
let l = nums.len() as i32;
while low <= high {
let mid = (low + high) / 2;
let mid_num = nums[mid as usize];
// println!("low={}, mid={}, high={}, mid_num={}, target={}", low, mid, high, mid_num, target);
if mid_num < target {
if mid == l - 1 || target <= nums[(mid+1) as usize] {
return mid;
}
low = mid + 1;
} else {
high = mid - 1;
}
}
-1
}
pub fn last_le(nums: Vec<i32>, target: i32) -> i32 {
let mut low = 0i32;
let mut high = (nums.len() - 1) as i32;
let l = nums.len() as i32;
while low <= high {
let mid = (low + high) / 2;
let mid_num = nums[mid as usize];
// println!("low={}, mid={}, high={}, mid_num={}, target={}", low, mid, high, mid_num, target);
if mid_num <= target {
if mid == l - 1 || target < nums[(mid+1) as usize] {
return mid;
}
low = mid + 1;
} else {
high = mid - 1;
}
}
-1
}
}
// Use vector to represent a heap so that any element can be randomly accessed, but the element count must be fixed.
use std::cmp::Ordering;
#[derive(Debug)]
pub struct VecHeap<K: Clone + Hash + Eq, W:Ord + Clone, V: Clone>{
elements: Vec<(K,W,V)>,
key2idx: HashMap<K, usize>,
}
impl<K: Clone + Hash + Eq, W:Ord + Clone, V: Clone> VecHeap<K,W,V>{
pub fn new(keys: Vec<K>, weights : Vec<W>, values : Vec<V>) -> VecHeap<K,W,V> {
let mut vh = VecHeap{elements: vec![], key2idx: HashMap::new()};
let n = keys.len();
for i in 0..keys.len() {
let idx = vh.elements.len();
vh.key2idx.insert(keys[i].clone(), idx);
vh.elements.push((keys[i].clone(), weights[i].clone(), values[i].clone()));
}
for i in (0..(n/2)).rev() {
vh.topdown_heapify(i, n);
}
vh
}
pub fn reweight_with_default(&mut self, key: &K, weight: &W, default_value: V) -> bool {
if let Some((k,w,v)) = self.remove(key) {
self.insert(k, weight.clone(),v);
true
} else {
self.insert(key.clone(), weight.clone(),default_value);
false
}
}
pub fn reweight(&mut self, key: &K, weight: &W) -> bool {
if let Some((k,w,v)) = self.remove(key) {
self.insert(k, weight.clone(),v);
true
} else {
false
}
}
pub fn remove(&mut self, key : &K) -> Option<(K,W,V)> {
if let Some(&removed_pos) = self.key2idx.get(key) {
// swap the removed element with the last element.
self.key2idx.remove(key);
if removed_pos == self.elements.len() - 1 {
self.elements.pop()
} else {
//swap the removed element wit the last.
let removed = self.elements[removed_pos].clone();
let last_entry = self.elements.pop().unwrap();
self.key2idx.insert(last_entry.0.clone(), removed_pos);
self.elements[removed_pos] = last_entry;
// topdown_heapify from the removed pos
self.topdown_heapify(removed_pos, self.len());
Some(removed)
}
} else {
None
}
}
pub fn insert(&mut self, key: K, weight: W, value: V) -> bool {
if self.key2idx.get(&key).is_none() {
let last_pos = self.elements.len();
self.key2idx.insert(key.clone(), last_pos);
self.elements.push((key, weight, value));
self.bottomup_heapify(last_pos);
true
} else {
false
}
}
pub fn bottomup_heapify(&mut self, start_pos : usize) {
if 0 < start_pos {
let parent_pos = (start_pos + 1) / 2 - 1;
if self.elements[parent_pos].1.cmp(&self.elements[start_pos].1) == Ordering::Less {
self.elements.swap(parent_pos, start_pos);
self.key2idx.insert(self.elements[start_pos].0.clone(), start_pos);
self.key2idx.insert(self.elements[parent_pos].0.clone(), parent_pos);
self.bottomup_heapify(parent_pos);
}
}
}
pub fn topdown_heapify(&mut self, start_pos: usize, max_len: usize ) {
let left_pos = 2 * start_pos + 1;
let right_pos = 2 * (start_pos + 1);
let mut large_pos = None;
let mut large_weight = self.elements[start_pos].1.clone();
if left_pos < max_len && large_weight.cmp(&self.elements[left_pos].1) == Ordering::Less {
large_weight = self.elements[left_pos].1.clone();
large_pos = Some(left_pos);
}
if right_pos < max_len && large_weight.cmp(&self.elements[right_pos].1) == Ordering::Less {
large_weight = self.elements[right_pos].1.clone();
large_pos = Some(right_pos);
}
if let Some(large_pos) = large_pos {
self.elements.swap(start_pos, large_pos);
self.key2idx.insert(self.elements[start_pos].0.clone(), start_pos);
self.key2idx.insert(self.elements[large_pos].0.clone(), large_pos);
self.topdown_heapify(large_pos, max_len);
}
}
pub fn max(&self) -> Option<&(K,W,V)> {
self.elements.get(0)
}
pub fn len(&self) -> usize {
self.elements.len()
}
}
use core::fmt::Debug;
pub fn heap_sort<T: Clone + Hash + Ord + Debug> (nums: &mut Vec<T>) {
let n = nums.len();
let mut vh = VecHeap::new(nums.clone(),
nums.clone(), nums.clone());
// println!("vh.elements={:?}", vh.elements);
// println!("vh.key2idx={:?}", vh.key2idx);
for i in (0..n).rev() {
vh.elements.swap(0, i);
vh.topdown_heapify(0, i);
}
nums.clear();
for entry in vh.elements {
nums.push(entry.0);
}
}
struct BitOp{}
impl BitOp {
pub fn zero_right_digits(x : i32, digit_count: usize) -> i32 {
x & (!0 << digit_count)
}
pub fn nth_digit(x : i32, n : usize) -> i32 {
(x >> n) & 1
}
// if n-th digit is 1, return 2^n, else 0.
// n starts from 0.
pub fn nth_digit_power(x : i32, n : usize) -> i32 {
x & (1 << n)
}
pub fn set_nth_digit_one(x: i32, n: usize) -> i32 {
x | (1 << n)
}
pub fn set_nth_digit_zero(x: i32, n: usize) -> i32 {
x & (!(1 << n))
}
// inclusive of nth
pub fn set_zero_from_nth(x: i32, n: usize) -> i32 {
x & ((1 << n) - 1)
}
// inclusive of nth
pub fn set_zero_to_nth(x: i32, n: usize) -> i32 {
x & (!((1 << (n + 1)) - 1))
}
// set the least significant bit-1 to 0.
pub fn set_lsb1_zero(x: i32) -> i32 {
x & (x-1)
}
// 2^(pos of lsb 1)
pub fn lsb1_power(x: i32) -> i32 {
x & -x
}
pub fn digit1_count(mut x: i32) -> usize {
let mut count = 0;
while x != 0 {
x = Self::set_lsb1_zero(x);
count+=1;
}
count
}
// the largest power of 2 le to x
pub fn largest_power(mut x : u32) -> u32 {
// println!("{:#032b}", x);
x = x | (x>>1);
// println!("{:#032b}", x);
x = x | (x>>2);
// println!("{:#032b}", x);
x = x | (x>>4);
// println!("{:#032b}", x);
x = x | (x>>8);
// println!("{:#032b}", x);
x = x | (x>>16);
// println!("{:#032b}", x);
x = (x+1)>>1;
// println!("{:#032b}", x);
x
}
pub fn is_power_of_2(x : u32) -> bool {
x & (x-1) == 0
}
pub fn add(mut a : u32, mut b : u32) -> u32 {
while b != 0 {
let carry = a & b;
a = a ^ b;
b = carry << 1;
}
a
}
pub fn divide(mut dividend : u32, divisor : u32) -> u32 {
let mut answer = 0u32;
while dividend >= divisor {
let mut base = divisor;
let mut cur_answer = 1u32;
while dividend >= base << 1 {
base = base << 1;
cur_answer = cur_answer << 1;
}
answer |= cur_answer;
dividend -= base;
}
answer
}
}
#[derive(Debug, Clone, Copy)]
struct StrUtil{}
impl StrUtil {
// transform a string to a char vec for a constant-time complexity to reference a i-th char.
pub fn str_to_char_vec(s : String) -> Vec<char> {
s.chars().collect()
}
pub fn char2idx(c : char) ->usize {
let base_idx = 'a' as u8 as usize;
let c_idx = c as u8 as usize;
c_idx - base_idx
}
pub fn str2int(s : String) -> i32 {
s.parse::<i32>().unwrap()
}
pub fn int2str(i : i32) -> String {
i.to_string()
}
pub fn misc(s : String) {
let s : & str = &s[..];
let sub : String = s[1..2].to_owned();
let mut hello = String::from("Hello, ");
hello.push('w'); // concat char
hello.push_str("orld!"); // append str
let sentence: &'static str = "the quick brown fox jumps over the lazy dog";
// word typed as &str
for word in sentence.split_whitespace().rev() {
// println!("> {}", word);
}
// Heap allocate a string
let alice = String::from("I like dogs");
// Allocate new memory and store the modified string there
let bob: String = alice.replace("dog", "cat");
let ascii = 'a';
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc: char = 0x1b_u8.into();
assert!(ascii.is_ascii());
assert!(uppercase_a.is_ascii_alphabetic());
assert!(!zero.is_ascii_alphabetic());
assert!(zero.is_ascii_alphanumeric());
assert!(!percent.is_ascii_alphanumeric());
assert!(!space.is_ascii_control());
assert!(lf.is_ascii_control());
assert!(zero.is_ascii_digit());
assert!(!percent.is_ascii_digit());
assert!(g.is_ascii_lowercase());
assert!(!zero.is_ascii_lowercase());
assert!(!zero.is_ascii_punctuation());
assert!(percent.is_ascii_punctuation());
assert_eq!(vec!["a".to_owned(), "b".to_owned()].join("-"), "a-b".to_owned());
}
}
struct TreeUtil {}
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::VecDeque;
use crate::util::tree::{TreeNode, to_tree};
impl TreeUtil {
pub fn bfs(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut traversed : Vec<i32> = vec![];
if let Some(ref root_node) = root {
type NodeWithLevel = (Rc<RefCell<TreeNode>>, usize);
let mut queue : VecDeque<NodeWithLevel> = VecDeque::new();
queue.push_back((Rc::clone(root_node), 1));
while let Some(head_entry) = queue.pop_front() {
let cur_node : Rc<RefCell<TreeNode>> = head_entry.0;
let cur_level : usize = head_entry.1;
traversed.push(cur_node.borrow().val);
// left_node typed with &Rc<RefCell<TreeNode>>
if let Some(left_node) = cur_node.borrow().left.as_ref() {
queue.push_back((Rc::clone(left_node), cur_level+1));
};
// right_node typed with &Rc<RefCell<TreeNode>>
if let Some(right_node) = cur_node.borrow().right.as_ref() {
queue.push_back((Rc::clone(right_node), cur_level+1));
};
}
}
traversed
}
pub fn preorder(root: &Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
if root.is_some() {
let mut r = vec![root.as_ref().unwrap().borrow().val];
r.extend(Self::preorder(&root.as_ref().unwrap().borrow().left));
r.extend(Self::preorder(&root.as_ref().unwrap().borrow().right));
r
} else {
vec![]
}
}
pub fn inorder(root: &Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
if root.is_some() {
let mut r = vec![];
r.extend(Self::preorder(&root.as_ref().unwrap().borrow().left));
r.push(root.as_ref().unwrap().borrow().val);
r.extend(Self::preorder(&root.as_ref().unwrap().borrow().right));
r
} else {
vec![]
}
}
pub fn postorder(root: &Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
if root.is_some() {
let mut r = vec![];
r.extend(Self::preorder(&root.as_ref().unwrap().borrow().left));
r.extend(Self::preorder(&root.as_ref().unwrap().borrow().right));
r.push(root.as_ref().unwrap().borrow().val);
r
} else {
vec![]
}
}
pub fn vec2bst_helper(nums : &[i32], size: i32) -> Option<Rc<RefCell<TreeNode>>> {
if size <= 0 {
None
} else {
// biase to left half so that mid will not overflow.
let mid = size / 2;
let left_size = mid;
let right_size = size - 1 - mid;
let node = Rc::new(RefCell::new(TreeNode::new(nums[mid as usize])));
if 0 < mid {
node.borrow_mut().left = Self::vec2bst_helper(&nums[0..(mid as usize)], left_size);
}
if mid+1 < size {
node.borrow_mut().right = Self::vec2bst_helper(&nums[(mid+1) as usize..], right_size);
}
Some(node)
}
}
pub fn vec2bst(nums : Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
Self::vec2bst_helper(&nums[..], nums.len() as i32)
}
}
struct VecUtil{}
impl VecUtil {
pub fn sort(v : &mut Vec<i32>) {
v.sort_by(|a : &i32,b: &i32|{a.cmp(b)});
v.sort_by(|a,b|{
if a < b {
return std::cmp::Ordering::Less;
} else if a == b {
return std::cmp::Ordering::Equal;
} else {
return std::cmp::Ordering::Greater;
}
});
}
pub fn range2vec(from_inclusive: i32, to_exclusive : i32) -> Vec<i32> {
(from_inclusive..to_exclusive).collect()
}
pub fn incre_foreach(v : &mut Vec<i32>) {
v.iter_mut().for_each(|x : &mut i32|{*x+=1})
}
pub fn incre_foreach_to_vec(v: &Vec<i32>) -> Vec<i32> {
v.iter().map(|x : &i32|{x+1}).collect()
}
pub fn stack() {
let mut s = vec![];
s.push(0);
let e : Option<i32> = s.pop();
}
pub fn queue() {
use std::collections::VecDeque;
let mut q: VecDeque<i32> = VecDeque::new();
q.push_back(0);
let e : Option<i32> = q.pop_front();
}
pub fn split() {
let mut a = vec![1,2,3];
let b = a.split_off(1usize);
assert_eq!(a, vec![1]);
assert_eq!(b, vec![2,3]);
}
pub fn iterator_misc() {
let mut xs = vec![0;100];
let processed : Vec<i32> = xs.into_iter()
.skip(5) // skip the previous 5 elements
.filter(|x : &i32|{*x < 50}) // filter by a predicate
.take(10).collect(); // only consider the first 10.
let _filter_by_idx : Vec<i32> = processed.iter().enumerate().filter(|&(idx, _)|{idx != 1}).map(|(_, &v)|{v}).collect();
let e1 : Option<&i32> = processed.iter().next();
let e10 : Option<&i32> = processed.iter().nth(10);
let last : Option<&i32> = processed.iter().last();
let sum : i32 = processed.iter().sum();
let count : usize = processed.iter().count();
let a1 = [1, 2, 3];
let a2 = [4, 5, 6];
let mut iter = a1.iter().zip(a2.iter());
assert_eq!(iter.next(), Some((&1, &4)));
assert_eq!(iter.next(), Some((&2, &5)));
assert_eq!(iter.next(), Some((&3, &6)));
assert_eq!(iter.next(), None);
let a = ["1", "two", "NaN", "four", "5"];
// Filter_map: The returned iterator yields only the values for which the supplied closure returns Some(value).
let mut iter = a.iter().filter_map(|s| s.parse().ok());
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(5));
assert_eq!(iter.next(), None);
let words = ["alpha", "beta", "gamma"];
// Flat_map: Creates an iterator that works like map, but flattens nested structure.
let merged: String = words.iter()
.flat_map(|s| s.chars())
.collect();
assert_eq!(merged, "alphabetagamma".to_owned());
let a = [1, 2, 3];
let (even, odd): (Vec<i32>, Vec<i32>) = a
.iter()
.partition(|&n| n % 2 == 0);
assert_eq!(even, vec![2]);
assert_eq!(odd, vec![1, 3]);
// Fold
let a = [1, 2, 3];
let sum = a.iter().fold(0, |acc : i32, x : &i32| {acc + x});
assert_eq!(sum, 6);
// All/any: Tests if every/any element of the iterator matches a predicate.
let a = [1, 2, 3];
assert!(a.iter().all(|x : &i32| *x > 0));
assert!(a.iter().any(|x : &i32| *x > 0));
// Find: find an element idx from left
// position/rposition: right the element index
let a = [1, 2, 3, 2];
assert_eq!(a.iter().find(|x : &&i32| **x == 2), Some(&2));
assert_eq!(a.iter().position(|x : &i32| *x == 2), Some(1usize));
assert_eq!(a.iter().rposition(|x : &i32| *x == 2), Some(3usize));
let m : Option<&i32> = a.iter().max(); // min or max_by_key, max_by
assert_eq!(m, Some(&3));
}
pub fn misc() {
let mut xs = vec![1i32, 2, 3];
// Insert new element at the end of the vector
xs.push(4);
assert_eq!(xs, vec![1,2,3,4]);
// The `len` method yields the number of elements currently stored in a vector
assert_eq!(xs.len(), 4);
// Indexing is done using the square brackets (indexing starts at 0)
assert_eq!(xs[1], 2);
// `pop` removes the last element from the vector and returns it
assert_eq!(xs.pop(), Some(4));
// `Vector`s can be easily iterated over
// println!("Contents of xs:");
// x typed as &i32
for x in xs.iter() {
// println!("> {}", x);
}
// x typed as &mut i32
for x in xs.iter_mut() {
*x +=1;
}
// A `Vector` can also be iterated over while the iteration
// count is enumerated in a separate variable (`i`)
// i typed as usize. x typed as &i32
for (i, x) in xs.iter().enumerate() {
// println!("In position {} we have value {}", i, x);
}
}
}
struct MapUtil{}
impl MapUtil {
pub fn hashmap_misc() {
let mut map : HashMap<String, String> = HashMap::new();
let k1 = String::from("k1");
let v1 = String::from("v1");
let prev_val : Option<String> =map.insert(k1, v1); // k1, v1 is consumed here.
assert_eq!(prev_val, None);
// map.insert(k1,v1); illegal.
let k1 = String::from("k1");
let v1 = String::from("v11");
let prev_val : Option<String> =map.insert(k1, v1); // k1, v1 is consumed here.
assert_eq!(prev_val, Some(String::from("v1")));
let k1 = String::from("k1");
let v1 = String::from("v11");
assert_eq!(map[&k1], v1);
// basic
let mut map = HashMap::new();
map.insert(1, "a".to_owned());
map.insert(2, "b".to_owned());
map.insert(3, "c".to_owned());
assert_eq!(map.get(&1), Some(&"a".to_owned()));
assert_eq!(map.get(&4), None);
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&4), false);
// insert with default
*(map.entry(5).or_insert("d".to_owned()))= "dd".to_owned();
assert_eq!(map.get(&5), Some(&"dd".to_owned()));
if let Some(x) = map.get_mut(&1) {
*x = "b".to_owned();
}
assert_eq!(map[&1], "b".to_owned());
// iteration:
// key typed as &i32, value typed as &String
for key in map.keys() {
// println!("{}", key);
}
for val in map.values_mut() {
*val = "asd".to_owned();
}
for val in map.values() {
// println!("{}", val);
}
for (key, val) in map.iter() {
// println!("key: {} val: {}", key, val);
}
for (_, val) in map.iter_mut() {
*val = "asd".to_owned();
}
assert_eq!(map.remove_entry(&1), Some((1, "asd".to_owned())));
assert_eq!(map.remove(&1), None);
map.clear();
}
pub fn orderedmap_misc() {
use std::ops::Bound::Included;
let mut om : BTreeMap<String, String> = BTreeMap::new();
om.insert("k1".to_owned(), "v1".to_owned());
om.insert("k2".to_owned(), "v2".to_owned());
// the smallest entry
assert_eq!(om.iter().next(), Some((&"k1".to_owned(), &"v1".to_owned())));
// the greatest entry
assert_eq!(om.iter().next_back(), Some((&"k2".to_owned(), &"v2".to_owned())));
let mut map = BTreeMap::new();
map.insert(3, "a".to_owned());
map.insert(5, "b".to_owned());
map.insert(8, "c".to_owned());
use std::ops::Range; // [start, end)
use std::ops::RangeInclusive; // [start, end]
use std::ops::RangeTo; // (-inf, end)
use std::ops::RangeToInclusive; // (-inf, end]
use std::ops::RangeFrom; // [start, +inf)
use std::ops::RangeFull; // [-inf, +inf]
// key, value typed with &
// for (key, value) in map.range(Range{start:3, end:7}) {
for (key, value) in map.range(RangeInclusive::new(3, 5)) {
println!("{}: {}", key, value);
}
for (key, value) in map.range_mut(RangeFull) {
// *key = 1; key is always immutable.
*value = "d".to_owned();
// println!("{}: {}", key, value);
}
// last key less
assert_eq!(map.range(RangeTo{end : 5}).next_back(), Some((&3, &"d".to_owned())));
// last key less or equal to
assert_eq!(map.range(RangeToInclusive{end : 5}).next_back(), Some((&5, &"d".to_owned())));
// first key greater or equal to
assert_eq!(map.range(RangeFrom{start : 7}).next(), Some((&8, &"d".to_owned())));
assert_eq!(map.range(RangeFrom{start : 8}).next(), Some((&8, &"d".to_owned())));
assert_eq!(map.range(RangeFrom{start : 9}).next(), None);
}