diff --git a/leetcode/kth-largest-element-in-a-stream/solution_1422880127.rs b/leetcode/kth-largest-element-in-a-stream/solution_1422880127.rs new file mode 100644 index 0000000..eebddb4 --- /dev/null +++ b/leetcode/kth-largest-element-in-a-stream/solution_1422880127.rs @@ -0,0 +1,45 @@ +struct KthLargest { + k: usize, + nums: Vec +} + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl KthLargest { + fn new(k: i32, mut nums: Vec) -> Self { + let k = k as usize; + let length = nums.len(); + let mut kths = vec![-10001i32; k]; + nums.sort(); + if length > k{ + kths[0..].copy_from_slice(&nums[length-k..]); + } else if length != 0{ + kths[k - length..].copy_from_slice(&nums[0..]); + } + Self{ + k, + nums: kths + } + } + + fn add(&mut self, val: i32) -> i32 { + let k = self.k; + match self.nums.binary_search(&val){ + Ok(0) | Err(0) => (), + Ok(idx) | Err(idx) => { + self.nums.copy_within(1..idx, 0); + self.nums[idx - 1] = val; + } + } + self.nums[0] + } +} + +/** + * Your KthLargest object will be instantiated and called as such: + * let obj = KthLargest::new(k, nums); + * let ret_1: i32 = obj.add(val); + */ \ No newline at end of file