leetcode问题:存在重复元素

给定一个整数数组,判断是否存在重复元素 ---1。

如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

示例 1:

输入: [1,2,3,1]
输出: true

示例 2:

输入: [1,2,3,4]
输出: false

示例 3:

输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
解法1:原创 10ms
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;
        
    }
}
解法2:23ms
class Solution {
    public boolean containsDuplicate(int[] nums) {
       HashSet<Integer> hs=new HashSet<>();
        boolean flag=false;
        for(int i=0;i<nums.length && !flag;i++){
            if(!hs.contains(nums[i])){
                hs.add(nums[i]);
            }
            else{
                flag=true;
            }
        }
        return flag;
        
    }
}
存在重复元素----2
给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 ij 的差的绝对值最大为 k

示例 1:

输入: nums = [1,2,3,1], k= 3
输出: true

示例 2:

输入: nums = [1,0,1,1], k=1
输出: true

示例 3:

输入: nums = [1,2,3,1,2,3], k=2
输出: false

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
      if(nums.length == 0)return false;
        else
        {
            HashMap<Integer,Integer>map = new HashMap<Integer,Integer>();
            for(int i = 0; i < nums.length; i++)
            {
                if(map.containsKey(nums[i]) && i-map.get(nums[i]) <= k)
                {
                    return true;
                }
                else
                {
                    map.put(nums[i], i);
                }
            }
            return false;
        }
        
    }
}



posted @ 2019-03-27 23:47  keep-the-faith  阅读(436)  评论(0编辑  收藏  举报