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

  • 相关阅读:
    javascript基础
    DOM操作
    js各种弹框
    ZeroMQ,史上最快的消息队列(转)
    mysql 存储过程
    java数据结构与算法(二)----栈和队列
    java数据结构与算法(一)----数组简单排序
    软件开发流程(转)
    Digest [information value filtering]
    Facebook 的系统架构(转)
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4887334.html
Copyright © 2020-2023  润新知