(leetcode题解)Contains Duplicate

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.

题意给定一个数组,查找数组是否存在重复项。

解决方法很多,hash表或者排序后查找相邻两项相同都可以实现,hash表的C++实现如下:

bool containsDuplicate(vector<int>& nums) {
        unordered_map<int,int> hash;
        for(auto &i:nums)
        {
            hash[i]++;
            if(hash[i]==2)
                return true;
        }
        return false;
    }

 

Contains Duplicate II

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 absolute difference between i and j is at most k.

题意给定一个数组和整数k,找出数组中是否有两个不同的索引i和j,使得nums [i] = nums [j],i和j之间的绝对差值最多为k。

这道题我的思路依旧是用hash表先找到出现次数大于等于2的数,再定位他们的位置,如果位置只差在k之内则返回true。

C++实现如下:

bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int,int> hash;
        int j=0;
        for(auto &i:nums)
        {
            hash[i]++;
            if(hash[i]>=2)
            {
                for(int n=0;n<j;n++)
                {
                    if(nums[n]==i)
                        if(j-n<=k)
                            return true;
                }
            }
            j++;
        }
        return false;
    }

 

网上运用hash表的另一种做法就是在hash表中存放数组的位置,这样就减少的对相应的位置的查找。C++实现如下,以供参考对比:

bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int,int> hash;
        for(int i=0;i<nums.size();i++)
        {
            if(hash.find(nums[i])!=hash.end()&&i-hash[nums[i]]<=k)
                return true;
            else
                hash[nums[i]]=i;
        }
        return false;
    }

 

转载于:https://www.cnblogs.com/kiplove/p/6995089.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值