1.题目

给定一个整数数组,判断是否存在重复元素。

如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false

示例1:

  1. 输入: [1,2,3,1]
  2. 输出: true
  3. 输入: [1,2,3,4]
  4. 输出: false
  5. 输入: [1,1,1,3,3,4,3,2,4,2]
  6. 输出: true

2.思路

我记得这题之前做过一次了,为什么今天又见了?

那么还是老方法,先排序,如果有重复的就会排列在一起

    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                return true;
            }
        }
        return false;
    }

还有一种丧心病狂的疯狂调API方法

 public boolean containsDuplicate(int[] nums) {
            return Arrays.stream(nums).distinct().count() < nums.length;
    }

还有一种就是利用set的不重复性

    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<Integer>();
        for (int x : nums) {
            if (!set.add(x)) {
                return true;
            }
        }
        return false;
    }