问题描述:
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);