zoukankan      html  css  js  c++  java
  • 217. Contains Duplicate (leetcode)

     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:两个循环嵌套,一个一个找是否有相同的,时间复杂度微O(n^2).  

    //思路2:排序,循环用前一个数减去后一个数,如果结果为0,那么返回true,时间复杂度是O(nlogn).

    //思路3 :利用set的不重复性,可得省时省力的解法,时间复杂度为O(n).

    思路1不再阐述

    思路2代码如下:

     public boolean containsDuplicate(int[] nums) {
            Arrays.sort(nums);
            for(int i=0;i<nums.length;i++)
            {if(i+1<nums.length)
                if(nums[i+1]-nums[i]==0)
                    return true;
            }
            return false;
        }

    思路3: Set.add( )方法可以用于这种情况,因为如果元素已经存在,它将返回false。

    代码如下:

    public  boolean containsDuplicate(int[] nums) {
             Set<Integer> set = new HashSet<Integer>();
             for(int i : nums)
                 if(!set.add(i))
                     return true; 
             return false;
         }


      

  • 相关阅读:
    給COMBOBOX增加VALUE和名称(完全解决)
    api控制系统服务
    .net 函数注析
    电容降压式电源
    光电耦合器的应用
    javascrip判断null和undefined
    光电耦合器
    Windows 系统错误代码
    Request.ServerVariables
    获得操作系统版本
  • 原文地址:https://www.cnblogs.com/jachin01/p/7291576.html
Copyright © 2011-2022 走看看