leetcode之Contains Duplicate 问题

来源:互联网 发布:edusoho源码下载 编辑:程序博客网 时间:2024/05/20 07:34

问题描述:

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.

题目意思非常简单,就是让你判断一下数组中有没有相同的数字。

问题来源:Contains Duplicate (具体地址:https://leetcode.com/problems/contains-duplicate/#/description)

思路:这道题解法非常的多啦!下面罗列几种常见的解法:

          1)采用两层循环,i从0到nums.length - 1,j从i + 1到nums.length - 1,然后判断两个数是否相等即可,时间复杂度为O(n^2),空间复杂度为O(1);

          2)先对数组进行排序,然后遍历一边数组,判断有没有前一个数等于后一个数的情况出现,有则返回true,否则则返回false,时间复杂度为O(nlgn),空间复杂度为O(1);

          3)采用集合来解决,每次遍历一个数的时候,判断该数是否包含在集合中了,没在的话则马上添加进集合,在的话就说明添加的是重复的数,时间复杂度为O(n),空间复杂度是O(n);

          4)应该是最简短的代码了,理解起来也特别容易,在这采用的是jdk8的新特性,采用流的概念和数组长度来进行处理,下面也会给出这种代码。不过这种代码由于底层封装的太好了,底层执行需要大量时间,所以执行时间比较长。

代码:




原创粉丝点击