zoukankan      html  css  js  c++  java
  • 【LeetCode】217 & 219

     217 - 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.

    Solution 1: sort then compare the adjacent number

     1 class Solution {
     2 public:
     3     bool containsDuplicate(vector<int>& nums) {     //runtime:40ms
     4         if(nums.size()<=1)return false;
     5         sort(nums.begin(),nums.end());
     6         for(int i=1;i<nums.size();i++){
     7             if(nums[i-1]==nums[i])return true;
     8         }
     9         return false;
    10     }
    11 };

    Solution 2: map记录已存在的int

     1 class Solution {
     2 public:
     3     bool containsDuplicate(vector<int>& nums) {     //runtime:104ms
     4         if(nums.size()<=1)return false;
     5         map<int,bool> m;
     6         for(int i=0;i<nums.size();i++){
     7             if(m[nums[i]]==true)return true;
     8             m[nums[i]]=true;
     9         }
    10         return false;
    11     }
    12 };

     

    219 - Contains Duplicate II

    Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.

    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            map<int,int> m;
            for(int i=0;i<nums.size();i++){
                if(m.find(nums[i])==m.end())
                    m[nums[i]]=i;
                else{
                    if(i-m[nums[i]]<=k)
                        return true;
                    else
                        m[nums[i]]=i;
                }
            }
            return false;
        }
    };
  • 相关阅读:
    C#中的反射解析及使用(转)
    给GRUB添加新的项目
    EFI系统引导的一些零碎知识点
    Mysql 通用知识 2019-03-27
    为git关联编辑器(比如notepad++) Associating text editors with Git
    win10 右键添加“在此打开powershell”
    LINQ
    Git学习笔记——分支
    Docker 安装 mysql
    RestTemplateBuilder类
  • 原文地址:https://www.cnblogs.com/irun/p/4695783.html
Copyright © 2011-2022 走看看