zoukankan      html  css  js  c++  java
  • 217. 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.

    Example 1:

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

    Example 2:

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

    Example 3:

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

    Approach #1: C++.

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

      

    Approach #2: Java.

    class Solution {
        public boolean containsDuplicate(int[] nums) {
            Set<Integer> set = new HashSet<Integer>();
            for (int i : nums)
                if (!set.add(i))
                    return true;
            return false;
        }
    }
    

      

    Approach #3: Python.

    class Solution(object):
        def containsDuplicate(self, nums):
            """
            :type nums: List[int]
            :rtype: bool
            """
            return len(nums) != len(set(nums))
    

      

    Time SubmittedStatusRuntimeLanguage
    a few seconds ago Accepted 28 ms python
    a few seconds ago Accepted 13 ms java
    4 minutes ago Accepted 24 ms cpp
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    2017.5.8下午
    2017.5.8上午
    2017.5.5下午
    2017.5.5上午
    2017.5.4下午
    WPF DataGrid LoadingRow style 滚动失效
    centos nginx 环境变量
    Kettle-03-定时转换
    Kettle-02-转换
    Kettle-01-安装(CentOS 7 离线)
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9963361.html
Copyright © 2011-2022 走看看