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.

数组中如果出现重复的元素返回True,反之
方法一:使用Map复杂度o(n)

    public boolean containsDuplicate(int[] nums) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int num:nums)
        {
            if(!map.containsKey(num))
                map.put(num,1);
            else
                return true;
        }
        return false;
    }

方法二:先排序,再遍历,复杂度o(n)

  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;
    }

posted on 2017-10-25 20:05  Wanna_Go  阅读(157)  评论(0编辑  收藏  举报

导航