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

  • 相关阅读:
    iOS
    UI基本视图控制
    堆和栈的区别 ?
    单例模式
    Object-c的类可以多重继承么?可以实现多个接口么?Category是什么?重写一个类的方式用继承好还是分类好?为什么?
    id
    协议
    分类(类别)
    #import和#include以及@class三者的区别?
    内存管理
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4887334.html
Copyright © 2011-2022 走看看