LeetCode 之 Contains Duplicate I II III — C++ 实现

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.

给定一个整型数组,找出数组中是否包含两个相同的数。如果数组中至少包含两个相同的数,返回 true,如果没有相同的数,返回 false。

分析:

法1:排序,然后查找是否有两个连续的相等元素。

法2:哈希法,使用 set 或者 map 记录已经出现过的数,若果再次找到返回true,否则返回 false。

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        if(nums.empty()) //空
        {
            return false;
        }
        
        map<int, int> count;
        int numsSize = nums.size();
        for(int index = 0; index < numsSize; ++index)
        {
            if(count[nums[index]] == 0) //数字还没有出现过
            {
                count[nums[index]] = 1;
            }
            else //出现两次
            {
                return true;
            }
        }
        
        return false;
    }
};

Contains Duplicate II

 

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

给定一个整型数组和整数 k,找出是否存在两个不同的索引 i 和 j 使 nums[i] = nums[j] ,且 i 和 j 的差最大为 k。

分析

    哈希法。map 以值为 key,索引为 val,当找到相同值时判断当前索引和 val的差值,如果大于 val-key>k,则将索引替换,继续查找,否则返回 true。

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if(nums.empty())//空
        {
            return false;
        }
        
        map<int, int> contain;//键存储数值,值存储位置
        
        int numsSize = nums.size();
        int lastPos = 0;
        for(int index = 0; index < numsSize; ++index)
        {
            if(contain.find(nums[index]) == contain.end())//数字还未加入map
            {
                contain[nums[index]] = index;
            }
            else//找到两个相等的数字
            {
                if(index - contain[nums[index]] <= k)//距离不大于k
                {
                    return true;
                }
                else
                {
                    contain[nums[index]] = index; //否则换成当前位置
                }
            }
        }
        
        return false;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值