LeetCode 217. Contains Duplicate

来源:互联网 发布:linux echo $ 编辑:程序博客网 时间:2024/06/08 17:08

问题描述:

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。这个题目的解法:使用一个hashset将所有出现过的数组记录下来,然后依次判断当前的值是否出现过。

代码实现:

 public boolean containsDuplicate(int[] nums) {         if (nums == null || nums.length == 0) {            return false;        }        Set<Integer> countSet = new HashSet<Integer>();        for (int num : nums) {            if (countSet.contains(num)) {                return true;            }            countSet.add(num);        }        return false;    }

问题改进:

在上面的解法中,使用hashset来记录过去出现过的数值。可能会消耗额外的时间代价。这里有一种解法是首先统计出当前数组中的最大的数和最小的数,然后建立一个boolean数组来表示对应的数书否出现过。这样能大大的加快运算速度。

代码实现:

public boolean containsDuplicate(int[] nums) {         if (nums == null || nums.length == 0) {            return false;        }        int max = Integer.MIN_VALUE;        int min = Integer.MAX_VALUE;        for (int num : nums) {            if (num > max) {                max = num;            }            if (num < min) {                min = num;            }        }        boolean[] signed = new boolean[max - min + 1];        for (int num : nums) {            if (signed[num - min]) {                return true;            }            signed[num - min] = true;        }        return false;    }

使用上面的方法可能出现溢出的情况,可能是 max = OX7FFFFFFF.ermin = OX80000000;的时候就会出现溢出的情况。