Contains Duplicate && Contains Duplicate II

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.

解法一
这道题不算难题,就是使用一个哈希表,遍历整个数组,如果哈希表里存在,返回false,如果不存在,则将其放入哈希表中,代码如下:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_map<int, int> m;
        for (int i = 0; i < nums.size(); ++i) {
        //find()如果找到返回下标,未找到则返回最后一个元素的下标
            if (m.find(nums[i]) != m.end()) return true;
            ++m[nums[i]];
        }
        return false;
    }
};

这题还有另一种解法,就是先将数组排个序,然后再比较相邻两个数字是否相等,时间复杂度取决于排序方法,代码如下:

解法二

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

参考:http://www.cnblogs.com/grandyang/p/4537029.html

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

在上面的基础上找到数组是否有重复的数,同时重复数的下标间隔不超过k。

解法一:
同样适用unorder_map来解决这个问题,如果map里面已经有了这个数就比较下标,如果符合要求返回true;如果不符合要求则更新该数的下标。

bool containsNearbyDuplicate(vector<int>& nums, int k) {
    if (nums.size() <= 1){
        return false;
    }
    unordered_map<int, int> m;
    for (int i = 0; i < nums.size(); i++){

        if (m.find(nums[i]) != m.end() && m[nums[i]] >= i - k){
            return true;
        }

        m[nums[i]] = i;
    }
    return false;
}

解法二:
使用set来实现。

bool containsNearbyDuplicate(vector<int>& nums, int k) {
    // the set only record k (or less than k) numbers before nums[i]
    set<int> st;
    for (int i = 0; i < nums.size(); ++i) {
        if (st.find(nums[i]) != st.end()) {
            return true;
        }
        if (st.size() < k) {
            st.insert(nums[i]);
        } else {
            // insert first, or wrong when k=0
            st.insert(nums[i]);
            st.erase(nums[i - k]);
        }
    }
    return false;
}

参考:https://github.com/illuz/leetcode/tree/master/solutions/219.Contains_Duplicate_II

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值