【算法】【线性表】【数组】寻找文件副本

1  题目

设备中存有 n 个文件,文件 id 记于数组 documents。若文件 id 相同,则定义为该文件存在副本。请返回任一存在副本的文件 id

示例 1:

输入:documents = [2, 5, 3, 0, 5, 0]
输出:0 或 5

提示:

  • 0 ≤ documents[i] ≤ n-1
  • 2 <= n <= 100000

2  解答

class Solution {
    public int findRepeatDocument(int[] documents) {
        Set<Integer> sets = new HashSet<>(documents.length);
        for (int document : documents) {
            if (sets.contains(document)) {
                return document;
            }
            sets.add(document);
        }
        return -1;    
    }
}

加油。

posted @ 2024-04-02 10:55  酷酷-  阅读(6)  评论(0编辑  收藏  举报