SHARE
TWEET

Untitled

a guest Jun 25th, 2019 50 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::collections::HashMap;
  2.  
  3. fn print_pairs(arr: &[i32], target: i32) {
  4.     let mut counts = HashMap::with_capacity(arr.len());
  5.  
  6.     for x in arr {
  7.         let y = target - x;
  8.         if let Some(count) = counts.get(&y).copied() {
  9.             for _ in 0..count {
  10.                 //                println!("{} + {} = {}", y, x, target);
  11.             }
  12.         }
  13.         *counts.entry(x).or_insert(0) += 1;
  14.     }
  15. }
  16.  
  17. use std::cmp::Ordering;
  18.  
  19. fn sort_print_pairs(arr: &mut [i32], target: i32) {
  20.     arr.sort();
  21.     let mut i = 0;
  22.     let mut j = arr.len() - 1;
  23.     while i < j {
  24.         let sum = arr[i] + arr[j];
  25.         match sum.cmp(&target) {
  26.             Ordering::Less => i += 1,
  27.             Ordering::Greater => j -= 1,
  28.             Ordering::Equal => {
  29.                 //                println!("{} + {} = {}", arr[i], arr[j], target);
  30.                 i += 1;
  31.                 j -= 1;
  32.             }
  33.         }
  34.     }
  35. }
  36.  
  37. use std::time::Instant;
  38.  
  39. fn main() {
  40.     let now = Instant::now();
  41.     let mut input: Vec<_> = (50_000 - 4_200_000..50_000).collect();
  42.     println!("vec creation: {:?}", now.elapsed());
  43.  
  44.     let target = 6;
  45.  
  46.     let now = Instant::now();
  47.     print_pairs(&input, target);
  48.     println!("print_pairs: {:?}", now.elapsed());
  49.  
  50.     println!("");
  51.  
  52.     let now = Instant::now();
  53.     sort_print_pairs(&mut input, target);
  54.     println!("sort_print_pairs: {:?}", now.elapsed());
  55. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top