LeetCode實戰:存在重複元素

背景


題目英文

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

題目中文

給定一個整數數組,判斷是否存在重複元素。

如果任何值在數組中出現至少兩次,函數返回 true。如果數組中每個元素都不相同,則返回 false。

示例 1:

輸入: [1,2,3,1]
輸出: true

示例 2:

輸入: [1,2,3,4]
輸出: false

示例 3:

輸入: [1,1,1,3,3,4,3,2,4,2]
輸出: true

算法實現

public class Solution
{
    public bool ContainsDuplicate(int[] nums)
    {
        if (nums.Length < 2)
            return false;

        HashSet<int> h = new HashSet<int>();
        for (int i = 0; i < nums.Length; i++)
        {
            if (h.Contains(nums[i]))
                return true;
            h.Add(nums[i]);
        }
        return false;
    }
}

實驗結果

  • 狀態:通過
  • 18 / 18 個通過測試用例
  • 執行用時: 156 ms, 在所有 C# 提交中擊敗了 93.33% 的用戶
  • 內存消耗: 30.3 MB, 在所有 C# 提交中擊敗了 5.31% 的用戶

提交結果


相關圖文

1. “數組”類算法

2. “鏈表”類算法

3. “棧”類算法

4. “隊列”類算法

5. “遞歸”類算法

6. “字符串”類算法

7. “樹”類算法

8. “哈希”類算法

9. “搜索”類算法

10. “動態規劃”類算法

11. “回溯”類算法

12. “數值分析”類算法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章