217. Contains Duplicate

来源:互联网 发布:淘宝店铺怎么关注链接 编辑:程序博客网 时间:2024/06/05 03:47

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.

解法一:Language-Java Time-O(n) Space-O(n) Run Time-15ms
解题思路:
利用HashMap记录每个元素出现的次数,这种解法有时候会超时

public class Solution {    public boolean containsDuplicate(int[] nums) {        Map<Integer, Integer> map = new HashMap<Integer, Integer>();        boolean bool = false;        for(int i = 0; i < nums.length; i ++)        {            if(map.containsKey(nums[i]))            {                map.put(nums[i], map.get(nums[i]) +1);                //如果出现了两次以上                if(map.get(nums[i]) >= 2)                {                    bool = true;                    break;                }            }else            {                map.put(nums[i], 1);            }        }        return bool;    }}

解法二:Language-Java Time-O(n) Space-O(n) Run Time-14ms
解题思路:
利用HashSet存放所有的元素,如果set中元素总个数小于nums中元素的个数,就说明含有重复的元素,这种解法有时也会超时

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

解法三:Language-Java Time-O(n) Space-O(n)
解题思路:在解法二的基础上,加入判断是否有一样的元素。
解法三-1.Run Time:14ms 有时会超时

public class Solution {    public boolean containsDuplicate(int[] nums) {        Set<Integer> set = new HashSet<Integer>();        for(int i : nums)        {            //如果set中有一样的            if(set.contains(i)) return true;            set.add(i);        }        return false;    }}

解法三-2.Run Time:9ms
注:set.add(i)的返回值为boolean类型,如果返回true,说明set中不含元素i,把元素i加入到set中。

public class Solution {    public boolean containsDuplicate(int[] nums) {        Set<Integer> set = new HashSet<Integer>();        for(int i : nums)        {            //如果set中有一样的            if(!set.add(i)) return true;        }        return false;    }}

解法四:Language-Java Time-O(nlogn) Space-O(1) Run Time-5ms
解题思路:先排序,然后判断有没有重复的元素

public class Solution {    public boolean containsDuplicate(int[] nums) {        int count = 0;        Arrays.sort(nums);        //i从1开始        for(int i = 1; i < nums.length; i ++)        {            if(nums[i] == nums[i-1])            {                return true;            }        }        return false;    }}
0 0
原创粉丝点击