Leetcode每日两题程序员数据结构和算法分析

Leetcode 217. Contains Duplicate

2017-11-27  本文已影响17人  ShutLove

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.

思路:
用哈希表记录已遍历的数字。

public boolean containsDuplicate(int[] nums) {
    if (nums == null || nums.length <= 1) {
        return false;
    }

    HashSet<Integer> set = new HashSet<>();
    for (int num : nums) {
        if (!set.add(num)) {
            return true;
        }
    }

    return false;
}

先对数组排序,然后看有没有相等的相邻数字。

public boolean containsDuplicate(int[] nums) {

    Arrays.sort(nums);
    for(int ind = 1; ind < nums.length; ind++) {
        if(nums[ind] == nums[ind - 1]) {
            return true;
        }
    }
    return false;
}
上一篇下一篇

猜你喜欢

热点阅读