判断一个数组是否存在重复元素
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.
两种解法
-
首先先到的是哈希表,代码如下:
class Solution { public boolean containsDuplicate(int[] nums) { Map<Integer,Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i])){ return true; } map.put(nums[i],i); } return false; } }时间复杂度是O(n),空间复杂度是O(n)
-
也可以通过排序,由于比较排序算法,比如堆排序,可以在最坏情况下具有O(nlogn) 的时间复杂度。因此,排序经常是很好的预处理方法。排序之后,我们可以扫描已排序的数组,以查找是否有任何连续的重复元素。
时间复杂度 : O(nlog n) 排序的复杂度是 O(nlog n),扫描的复杂度是 O(n)。整个算法主要由排序过程决定,因此是 O(nlog n)。
空间复杂度 : O(1) 这取决于具体的排序算法实现,通常而言,使用堆排序的话,是 O(1)