如何检查切片中是否有重复项? [英] How to check if there are duplicates in a slice?

查看:43
本文介绍了如何检查切片中是否有重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种本地方法来检查切片是否有重复项?现在,我使用这个:

Is there a native way to check if a slice has duplicates? For now, I use this:

fn has_dup<T: PartialEq>(slice: &[T]) -> bool {
    for i in 1..slice.len() {
        if slice[i..].contains(&slice[i - 1]) {
            return true;
        }
    }
    false
}

fn main() {
    assert_eq!(has_dup(&[1, 2, 3, 2, 5, 6]), true);
    assert_eq!(has_dup(&[1, 2, 3, 4, 5, 6]), false);
}

但对于这种基本操作,我不喜欢使用手工代码.

but for this kind of basic operations, I do not like to use hand-made code.

如果标准库中没有可用的函数来执行此操作,是否可以优化我的代码?我知道索引切片不是最优化的方式(for i in slice {} vs for i in 0..slice.len() { slice[i] }).

If there is no available function to do this in the standard library, is it a way to optimize my code? I know that indexing the slice is not the most optimized way (for i in slice {} vs for i in 0..slice.len() { slice[i] }).

推荐答案

就算法复杂性而言,跟踪索引中的唯一值通常更好.如果你可以用 HashEq 检查相等性,你可以试试这个实用函数:

In terms of algorithmic complexity, it is often better to keep track of unique values in an index. If you can check equality with Hash and Eq, you can try this utility function:

fn has_unique_elements<T>(iter: T) -> bool
where
    T: IntoIterator,
    T::Item: Eq + Hash,
{
    let mut uniq = HashSet::new();
    iter.into_iter().all(move |x| uniq.insert(x))
}

assert!(!has_unique_elements(vec![10, 20, 30, 10, 50]));
assert!(has_unique_elements(vec![10, 20, 30, 40, 50]));
assert!(has_unique_elements(Vec::<u8>::new()));

游乐场

同样,如果您的元素没有实现 Hash 但确实实现了 Ord,你可以使用 BTreeSet 代替(游乐场).

Likewise, if your elements don't implement Hash but do implement Ord, you can use a BTreeSet instead (Playground).

这篇关于如何检查切片中是否有重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆