zoukankan      html  css  js  c++  java
  • 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.

    给定整数数组,查找是否包含重复的数。如果任何一个数在数组中出现了至少两次,函数返回true;若每个数互不相同则返回false。

    学习一下jmnarloch的做法:

    public boolean containsDuplicate(int[] nums) {
    
            return nums.length != Arrays.stream(nums)
                    .distinct()
                    .count();
        }
    关于stream的介绍参考http://blog.csdn.net/happyheng/article/details/52832313
    Java8中提供了Stream对集合操作作出了极大的简化,学习了Stream之后,我们以后不用使用for循环就能对集合作出很好的操作。

    我的方法,时间复杂度和内存都是O(n)

    import java.util.HashSet;
    class Solution {
    public boolean containsDuplicate(int[] nums) {
    HashSet<Integer> set=new HashSet<Integer> ();
    for(int i=0;i<nums.length;i++) {
    if(set.contains(nums[i]))
    return true;
    else
    set.add(nums[i]);
    }
    return false;
    }
    }

  • 相关阅读:
    Interviewe(hdu3486)
    Cornfields(poj2019)
    C. Watching Fireworks is Fun(Codeforces 372C)
    A. Points on Line
    Fence(poj1821)
    7
    如何使用Visual Studio调试C#程序
    do…while语句
    通过ASP.NET Ajax技术模拟实现NBA比赛文字直播功能
    RecyclerView的基础用法
  • 原文地址:https://www.cnblogs.com/mafang/p/8458499.html
Copyright © 2011-2022 走看看