(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