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

    判断数组里面是否有重复的,很简单:

     1 class Solution {
     2 public:
     3     bool containsDuplicate(vector<int>& nums) {
     4         int sz = nums.size();
     5         if (sz <= 1) return true;
     6         sort(nums.begin(), nums.end());
     7         for (int i = 0; i < sz; ++i){
     8             if (nums[i] == nums[i - 1])
     9                 return false;
    10         }
    11         return true;
    12     }
    14 };

     java版本,用HashSet来做的,这样的效率应该比上面的要高上不少,代码如下:

    public class Solution {
        public boolean containsDuplicate(int[] nums) {
            Set<Integer> s = new HashSet<Integer>();
            for(int i = 0; i< nums.length; ++i){
                if(!s.contains(nums[i])){
                    s.add(nums[i]);
                }else
                    return true;
            }
            return false;
        }
    }

    c++的Hash代码也写一遍试试:

    class Solution {
    public:
        bool containsDuplicate(vector<int>& nums) {
           int sz = nums.size();
           unordered_set<int> s;
           for(int i = 0; i < sz; ++i){
               if(s.find(nums[i]) == s.end()){
                   s.insert(nums[i]);
               }else
                    return true;
           }
           return false;
        }
    };

    发现实际上比java的runtime还是要慢上不少,大概用了java三倍的时间,我也不知道怎么回事。

  • 相关阅读:
    9本Java程序员必读的书
    最短路径问题:dijkstar
    RSA加密算法
    BFC 浅谈
    纯css3配合vue实现微信语音播放效果
    Vue内置组件keep-alive的使用
    vim常用命令
    Java实体映射工具MapStruct的使用
    hexo文章编写部分语法总结以及hexo使用
    高级进程间通信
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4887334.html
Copyright © 2011-2022 走看看