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


      

  • 相关阅读:
    iOS CALayer 学习(2)
    iOS CALayer 学习(1)
    iOS 绘画学习(5)
    iOS 绘画学习(4)
    果冻视图制作教程
    15个名不见经传的Unix命令
    WEB服务器2--IIS架构(转)
    WEB服务器1--开篇
    HTTP协议5之代理--转
    HTTP协议4之缓存--转
  • 原文地址:https://www.cnblogs.com/jachin01/p/7291576.html
Copyright © 2011-2022 走看看