zoukankan      html  css  js  c++  java
  • 【Leetcode】【Easy】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.

    解题:

    题目很简单,判断数组中是否含有重复数字,有重复则返回true,否则返回false;

    两种思路:

    1、不使用多余空间,先对数组进行排序o(nlogn),在依次检查相邻元素是否有重复o(n),整体时间复杂度o(nlogn),空间复杂度o(1);

    2、使用hash表判断数字是否重复,用空间换时间。时间复杂度o(n),空间复杂度o(n);

    代码(hash):

     1 class Solution {
     2 public:
     3     bool containsDuplicate(vector<int>& nums) {
     4         map<int, bool> num_map;
     5         map<int, bool>::iterator iter;
     6         
     7         for (int i = 0; i < nums.size(); ++i) {
     8             iter = num_map.find(nums[i]);
     9             if (iter != num_map.end())
    10                 return true;
    11             num_map[nums[i]] = true;
    12         }
    13         
    14         return false;
    15     }
    16 };
  • 相关阅读:
    3月30日
    3月29日
    3月26日
    3月24
    3月22日
    3月20日
    博弈论基础
    $burnside$引理与$pacute olya$定理
    min-max容斥
    模板
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4606620.html
Copyright © 2011-2022 走看看