前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T36-存在重复元素

【leetcode刷题】T36-存在重复元素

作者头像
木又AI帮
修改2019-07-18 09:59:50
3760
修改2019-07-18 09:59:50
举报
文章被收录于专栏:木又AI帮木又AI帮

【英文题目】(学习英语的同时,更能理解题意哟~)

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.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

【中文题目】

给定一个整数数组,判断是否存在重复元素。

如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

示例 1:

输入: [1,2,3,1]
输出: true

示例 2:

输入: [1,2,3,4]
输出: false

【思路】

这道题属于很常见的hash应用,直接遍历元素存入hash表,当hash表中存在相同元素时,则返回True。

当然还有更简单的实现方法:比较nums的元素个数以及将nums转换为集合后集合中元素个数。

【代码】

python版本

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        d = {}
        for n in nums:
            if n in d:
                return True
            d[n] = 
        return False
        # 更简洁
        # return len(nums) != len(set(nums))

C++版本

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        map<int, int> d;
        for(auto n: nums){
            if(d.find(n) != d.end())
                return true;
            d[n] = ;
        }
        return false;
        // set<int> s(nums.begin(), nums.end());
        // return nums.size() != s.size();
    }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-04-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档