【Leetcode】217. Contains Duplicate

来源:互联网 发布:金融数据录入 编辑:程序博客网 时间:2024/05/17 02:22

方法一:

思路:

用一个set存储数组中出现过的元素,遍历数组元素,若该元素已存在于set中,则返回true,否则将其加入set。

public class Solution {    public boolean containsDuplicate(int[] nums) {        Set<Integer> set = new HashSet<Integer>();        int len = nums.length;        for (int i = 0; i < len; i++) {            if (set.contains(nums[i]))                return true;            else                set.add(nums[i]);        }        return false;    }}

Runtime:21ms


方法二:

思路:

先将数组排序,然后从第一个开始遍历,如果和后一个值相等,则返回true,终止。

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

时间复杂度为O(nlogn),空间复杂度为O(1)

Runtime:6ms
1 0
原创粉丝点击