[leetcode]217.Contains Duplicate

题目

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.

Example 1:

Input: [1,2,3,1]
Output: true
Example 2:

Input: [1,2,3,4]
Output: false
Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

解法一

思路

用set,如果没有遇到重复的,也就是如果某个元素添加set失败,则说明有重复的。

代码

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

解法二

思路

先给数组排序,然后遍历一遍比较相邻元素是否有相等的。时间复杂度取决于排序算法的复杂度。

代码

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

猜你喜欢

转载自www.cnblogs.com/shinjia/p/9785354.html
今日推荐