LeetCode存在重复元素快乐做题

简介: LeetCode存在重复元素快乐做题

一:题目描述

       给定一个整数数组,判断是否存在重复元素。

如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。

二:解决办法

       1:两层for循环,暴力解法

public class Solution {
    public bool ContainsDuplicate(int[] nums) {
 for (int i = 0; i < nums.Length; i++)
            {
                int number = nums[i];
                for (int j = i+1; j < nums.Length; j++)
                {
                    if (number == nums[j])
                    {
                        return true;
                    }
                }
            }
            return false;
    }
}

第一层循环将数找出来,第二次进行比较,时间复杂度为n*n。

2:HashTable,不能有同一键值数据

public class Solution {
    public bool ContainsDuplicate(int[] nums) {
             Hashtable hashtable = new Hashtable();
            for (int i = 0; i < nums.Length; i++)
            {
                try
                {
                    hashtable.Add(nums[i], i);
                }
                catch (Exception)
                {
                    return true;
                }
            }
            return false;
    }
}

使用了一层循环,效率变高。

3:List集合

public class Solution {
    public bool ContainsDuplicate(int[] nums) {
    ArrayList arrayList = new ArrayList();
            for (int i = 0; i < nums.Length; i++)
            {
                if ( arrayList.Count == 0)
                {
                    arrayList.Add(nums[0]);
                }
                if (!arrayList.Contains(nums[i]) )
                {
                    arrayList.Add(nums[i]);
                }
            }
            if (arrayList.Count<nums.Length)
            {
                return true;
            }
            return false;
        }
}

4:排序后将相邻两个比较

public bool ContainsDuplicate(int[] nums) {
    Array.Sort(nums);
            for (int i = 0; i < nums.Length-1; i++)
            {
                if (nums[i]==nums[i+1])
                {
                    return true;
                }
            }
            return false;
    }
目录
相关文章
|
2月前
|
算法 Java
[Java·算法·简单] LeetCode 27. 移除元素 详细解读
[Java·算法·简单] LeetCode 27. 移除元素 详细解读
27 1
|
2月前
|
算法 C语言
【C语言】Leetcode 27.移除元素
【C语言】Leetcode 27.移除元素
21 0
【C语言】Leetcode 27.移除元素
|
2月前
|
C++
两种解法解决 LeetCode 27. 移除元素【C++】
两种解法解决 LeetCode 27. 移除元素【C++】
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解
|
2月前
|
算法
LeetCode[题解] 1261. 在受污染的二叉树中查找元素
LeetCode[题解] 1261. 在受污染的二叉树中查找元素
16 1
|
4月前
leetcode:203. 移除链表元素(有哨兵位的单链表和无哨兵位的单链表)
leetcode:203. 移除链表元素(有哨兵位的单链表和无哨兵位的单链表)
19 0
|
9天前
|
算法
[leetcode] 快乐数 E
[leetcode] 快乐数 E
|
10天前
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
|
15天前
|
存储 算法
代码随想录算法训练营第五十九天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
代码随想录算法训练营第五十九天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
22 1
|
15天前
|
算法
代码随想录算法训练营第五十七天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
代码随想录算法训练营第五十七天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
15 3

热门文章

最新文章