【数据结构入门_数组】 Leetcode 217.存在重复元素

原题链接:Leetcode 217. Contains Duplicate

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109


方法一:哈希表

思路:

遍历数据中的元素,如果它已经在哈希表中,就返回true,否则就将它插入哈希表

c++代码:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_set<int> s;

        for (auto n : nums){
            if(s.find(n) != s.end())
                return true;
            else
                s.insert(n);
        }
        return false;
    }
};

复杂度分析:

  • 时间复杂度:O(n),n个元素
  • 空间复杂度:O(n),需要一个哈希表,长度最大为n


方法二:排序

思路:

对数组进行排序,遍历判断是否和相邻元素相同

c++代码:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        sort(nums.begin(), nums.end());

        for(int i = 0; i < nums.size() - 1; i ++ ){
            if(nums[i] == nums[i + 1]) return true;
        }
        return false;
    }
};

复杂度分析:

  • 时间复杂度:O(nlogn) 时间开销主要在sort(),sort采用的是改进快速排序,复杂度为O(nlogn)
  • 空间复杂度:O(logn),同理,快速排序的空间复杂度为O(logn)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值