Fork me on GitHub

217.存在重复元素


这道题采用的是hashset 如果重复的话就return true
方法不难

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

另外一种是排序完在进行判断是否有重复的

 public static boolean sContainsDuplicate(int[] nums)
    {
        Arrays.sort(nums);
        if (nums.length <= 1)
        {
            return false;
        }
        int tem = nums[0];
        for (int i = 1; i < nums.length; i++)
        {
            if (nums[i] == tem)
            {
                return true;
            } else
            {
                tem = nums[i];
            }
        }
        return false;
    }
posted @ 2019-07-08 12:29  cznczai  阅读(163)  评论(0编辑  收藏  举报