LeetCode简单题:217. 存在重复元素(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/contains-duplicate/
要点:hashmap
用暴力双循环法会超时,因为复杂度为O(n^2)。
Python,C++,Java都用了相同的哈希表法。
遇到没遇过的值就加入哈希表,如果发现已经加入过,说明重复。
java中还能用hashset代替hashmap。

二.Python实现

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        hashmap = {}
        length=len(nums)
        for i in range(0,length):
            if hashmap.get(nums[i])!=None:
                return True;
            hashmap[nums[i]] = 1 
       
        return False

三.C++实现

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_map<int,int> hashmap;
        int length=nums.size();
    
        for(int i=0;i<length;i++){
            if(hashmap[nums[i]]) return true;
            else{
                hashmap[nums[i]]=1;
            }
        }

        return false;

    }
};

四.java实现

class Solution {
    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;
}

}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容