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


      

  • 相关阅读:
    链表数据-PHP的实现
    关于go的init函数
    socket小计
    很随笔
    go获取当前项目下所有依赖包
    关于synergy的问题
    二叉树的最大路径和
    大数求和
    重载<<运算符第二个参数必须加上const
    表达式求值
  • 原文地址:https://www.cnblogs.com/jachin01/p/7291576.html
Copyright © 2011-2022 走看看