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;
         }


      

  • 相关阅读:
    [笔记]一道C语言面试题:IPv4字符串转为UInt整数
    linux内核代码注释 赵炯 第三章引导启动程序
    bcd码
    2章 perl标量变量
    1章 perl入门
    perl第三章 列表和数组
    浮动 float
    文字与图像
    3.深入理解盒子模型
    4.盒子的浮动和定位
  • 原文地址:https://www.cnblogs.com/jachin01/p/7291576.html
Copyright © 2011-2022 走看看