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三倍的时间,我也不知道怎么回事。

  • 相关阅读:
    相对路径与绝对路径的区别
    c语言 蛇形填空
    Java最大公约数 最小公倍数
    c语言 韩信点兵
    c语言倒三角形
    Java 分解质因数
    Java 求水仙花数
    Java 求素数
    Java基于OpenCV实现走迷宫(图片+路线展示)
    Java之函数式接口@FunctionalInterface详解(附源码)
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4887334.html
Copyright © 2011-2022 走看看