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

  • 相关阅读:
    Tcp抓包以及Tcp状态
    Wireshark抓包使用指南
    服务端tcp syn无响应,无回复
    升级openssh
    平滑升级Nginx
    Memcached 未授权访问漏洞修复
    服务端高并发分布式架构演进之路
    es索引查询与删除
    申请elasticsearch中x-pack插件许可证及授权
    独立安装ab压力测试工具及测试nginx性能
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4887334.html
Copyright © 2011-2022 走看看