217. Contains Duplicate

来源:互联网 发布:数据挖掘十大算法书评 编辑:程序博客网 时间:2024/06/11 16:18

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.

这道题普遍的思路就是创建一个HashSet,边判断边添加元素,如果发现已经存在的元素就返回True,代码如下:

 public boolean containsDuplicate(int[] nums) {
       // 特殊情况处理
       if(nums == null || nums.length == 0 || nums.length == 1){
           return false;
       }
       
       Set<Integer> hashSet = new HashSet<Integer>();
       for(int i=0; i < nums.length; i++){
           if(hashSet.contains(nums[i])){
               return true;
           }else{
               hashSet.add(nums[i]);
           }
       }
       return false; 
    }

发现上述方式是行之有效的方式,在遇到需要两重循环迭代解决的问题的时候,我们可以考虑采用HashMap或者HashSet边判断边添加元素的方式来将复杂度从O(n2)降至O(n),下面是两种时间复杂度稍微高的方式:

时间复杂度O(n2) 空间复杂度O(1)

public boolean containsDuplicate(int[] nums) {
       // 时间复杂度 O(n2) 空间复杂度O(1)
       // 特殊情况处理
       if(nums == null || nums.length == 0 || nums.length == 1){
           return false;
       }
       
       for(int i=0; i < nums.length; i++){
           for(int j=i + 1; j < nums.length; j++){
               if(nums[i] == nums[j]){
                   return true;
               }
           }
       }
       return false;
    }这是最容易想到的方式,但是这会产生超时

时间复杂度O(nlogn) 空间复杂度O(1) 不考虑排序中所占用的内存空间

public boolean containsDuplicate(int[] nums) {
       // 时间复杂度 O(n2) 空间复杂度O(1)
       // 特殊情况处理
       if(nums == null || nums.length == 0 || nums.length == 1){
           return false;
       }
       
       Arrays.sort(nums);
       for(int i = 1; i < nums.length; i++){
           if(nums[i] == nums[i - 1]){
               return true;
           }
       }
       
       return false;
    }这种情况不会产生超时,也比较容易想到

0 0
原创粉丝点击