Skip to content

Commit

Permalink
Add 455 assign cookies
Browse files Browse the repository at this point in the history
  • Loading branch information
escwxyz committed Apr 20, 2023
1 parent c63f94b commit 7083a95
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 0 deletions.
53 changes: 53 additions & 0 deletions rust/src/assign_cookies_455.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use crate::Solution;

impl Solution {
#[allow(dead_code)]
pub fn find_content_children(g: Vec<i32>, s: Vec<i32>) -> i32 {
if s.is_empty() {
return -0;
}

let mut count: i32 = 0;

let mut a: Vec<i32> = g;
a.sort();

let mut b: Vec<i32> = s;
b.sort();

let mut p = 0;
let mut q = 0;

while p < a.len() && q < b.len() {
if b[q] >= a[p] {
count += 1;
q += 1;
p += 1;
} else {
q += 1;
}
}

count
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_one() {
assert_eq!(
Solution::find_content_children(vec![1, 2, 3], vec![1, 1]),
1
);
}
#[test]
fn test_two() {
assert_eq!(
Solution::find_content_children(vec![1, 2], vec![1, 2, 3]),
2
);
}
}
2 changes: 2 additions & 0 deletions rust/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
mod assign_cookies_455;
mod container_with_most_water_11;
mod find_range_in_array_34;
mod is_subsquence_392;
mod minimum_common_value_2540;
mod move_zeroes_283;
mod remove_element_27;
mod reverse_string_344;

pub(crate) struct Solution;
40 changes: 40 additions & 0 deletions typescript/src/455-assign-cookies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Problem: https://leetcode.com/problems/assign-cookies/
* @param g - greedy array
* @param s - cookie array
* @returns count
*
*/
export const findContentChildren = (g: number[], s: number[]): number => {
if (s.length === 0) return 0

let count = 0

const a = g.sort((a, b) => a - b)
const b = s.sort((a, b) => a - b)

let p = 0
let q = 0

while (p < a.length && q < b.length) {
if (b[q] >= a[p]) {
count++
p++
q++
} else {
q++
}
}

return count
}

if (import.meta.vitest) {
const { test, expect } = import.meta.vitest
test('test one', () => {
expect(findContentChildren([1, 2, 3], [1, 1])).toBe(1)
})
test('test two', () => {
expect(findContentChildren([1, 2], [1, 2, 3])).toBe(2)
})
}

0 comments on commit 7083a95

Please sign in to comment.