217. Contains Duplicate

问题描述

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.

题目链接:


思路分析

给定一个整形数组,判断数组中是否有至少两个元素相同。

只会用简单两层循环比较。

代码
class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        if (nums.size() <= 1)
            return false;
        int tmp;
        for(int i = 0; i < nums.size(); i++){
            tmp = nums[i];
            for(int j = i + 1; j < nums.size(); j++){
                if (nums[j] == tmp)
                    return true;
            }
        }
        return false;
    }
};

时间复杂度: O(n2)
空间复杂度: O(1)


反思

看到上天的反对数,就觉得这个题没有那么简单,我的算法跑出了1750ms,简直不能忍。
1.使用set
set的特性是,所有元素都会根据元素的键值自动排序,set的元素不像map那样可以同时拥有实值(value)和键值(key),set元素的键值就是实值,实值就是键值。set不允许两个元素有相同的键值。

所以原来的数组size()大就是有重复,否则是没有的。

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

时间复杂度: O(nlogn) 38ms
空间复杂度: O(1)

2.sort
将数组重新排序,然后就可以在常数时间完成比较

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        for (int i=0; i<int(nums.size())-1; i++) {
          if (nums[i]==nums[i+1])
              return true;
        }  
        return false;    
    }
};

时间复杂度: O(nlogn) 31ms
空间复杂度: O(1)

3.hash table (Java版)

public boolean containsDuplicate(int[] nums) {
    Set<Integer> set = new HashSet<>(nums.length);
    for (int x: nums) {
        if (set.contains(x)) return true;
        set.add(x);
    }
    return false;
}

时间复杂度: O(n)
空间复杂度: O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值