some more problems
This commit is contained in:
parent
e7b17e4450
commit
8181578c11
|
@ -0,0 +1,12 @@
|
|||
impl Solution {
|
||||
pub fn max_profit(prices: Vec<i32>) -> i32 {
|
||||
prices
|
||||
.iter()
|
||||
.fold((prices[0], 0), |(min, max_diff), &price| {
|
||||
if price < min {
|
||||
return (price, max_diff);
|
||||
}
|
||||
(min, max_diff.max(price - min))
|
||||
}).1
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
// Assume shift operators are allowed
|
||||
impl Solution {
|
||||
#[inline]
|
||||
pub fn negative(n: i32) -> i32 {
|
||||
if n.is_positive() {
|
||||
return !(n - 1);
|
||||
}
|
||||
n
|
||||
}
|
||||
pub fn divide(dividend: i32, divisor: i32) -> i32 {
|
||||
let positive = dividend ^ divisor >= 0;
|
||||
let negative_divisor = Solution::negative(divisor);
|
||||
let negative_answer = (0..negative_divisor.leading_ones()) // Preform all arithmetic in negative because of larger available range of numbers
|
||||
.rev() // Reverse to get most extreme subdivisor first
|
||||
.map(|n| negative_divisor << n) // Generate subdivisors
|
||||
.fold((0, Solution::negative(dividend)), |(quotient, carry), subdivisor| {
|
||||
if subdivisor >= carry {
|
||||
return ((quotient << 1) - 1, carry - subdivisor);
|
||||
}
|
||||
return (quotient << 1, carry);
|
||||
}).0;
|
||||
if positive {
|
||||
let answer = !negative_answer;
|
||||
if answer != std::i32::MAX {
|
||||
return answer + 1;
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
negative_answer
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
impl Solution {
|
||||
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
|
||||
// Get longer & shorter side to optimise memory a little
|
||||
let (longer, shorter) = if nums1.len() > nums2.len() {
|
||||
(nums1.into_iter(), nums2.into_iter())
|
||||
} else {
|
||||
(nums2.into_iter(), nums1.into_iter())
|
||||
};
|
||||
// Get counts of each element of shorter vector
|
||||
let mut counts: HashMap<i32, i32> = shorter
|
||||
.fold(HashMap::new(), |mut counts, n| {
|
||||
counts.insert(n, 1 + *counts.get(&n).unwrap_or(&0));
|
||||
counts
|
||||
});
|
||||
// Filter longer vector using the counts of the elements of the shorter vector
|
||||
longer
|
||||
.filter(|n| {
|
||||
let count = *counts.get(n).unwrap_or(&0);
|
||||
counts.insert(*n, count - 1);
|
||||
count.is_positive()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue