0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rust Lang) leetcode: 26. Remove Duplicates from Sorted Array

Posted at

code

// 1. Not hash set

struct Solution{}

impl Solution {
    pub fn remove_duplicates(v: &mut Vec<i32>) -> i32 {
        let mut i=0; let mut j=0;
        let mut buff: Vec<i32>= Vec::new();
        let nested_v= v.clone();
        
        for e in v{
            let duplicated= nested_v.iter().filter(|&n| *n == *e).count();
            if buff.iter().filter(|n| n == &e).count() >= 1 {
                continue;
            }else{
                buff.push(*e);
            }
        }

        buff.len() as i32
    }
}

fn main() {
    let result= Solution::remove_duplicates(&mut Vec::from([0_i32,0,1,1,1,2,2,3,3,4]));
    assert_eq!(result, 5);
}



// 1. https://stackoverflow.com/questions/57739755/how-could-rust-multiply-i32-with-i32
// pivot 1 and 2 have a same address vector
// if pivot_1 == pivot_2{
//     buff.push(*pivot_1);
// }else{
//     continue;
// }

// 2. https://stackoverflow.com/questions/45353757/how-to-count-the-elements-in-a-vector-with-some-value-without-looping


// 2. Hash set
struct Solution{}

use std::collections::HashSet;

impl Solution {
    pub fn remove_duplicates(v: &mut Vec<i32>) -> i32 {
        let mut seen = HashSet::new();
        
        for e in v{
            seen.insert(e);
        }
        
        seen.len() as i32
    }
    
}

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

    #[test]
    fn it_works() {
        let mut inpute= Vec::from([1,1,2]);
        let result = Solution::remove_duplicates(&mut inpute);
        assert_eq!(result, 2);
    }

    #[test]
    fn it_works2() {
        let mut inpute= Vec::from([0,0,1,1,1,2,2,3,3,4]);
        let result = Solution::remove_duplicates(&mut inpute);
        assert_eq!(result, 5);
    }
}

// Constraints:
// 1 <= nums.length <= 3 * 104
// -100 <= nums[i] <= 100
// nums is sorted in non-decreasing order.

Ref

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?