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.

 
 
 
代码:
方法一:
 1 public class Solution {
 2     public boolean containsDuplicate(int[] nums) {
 3         Set<Integer> hs = new HashSet<Integer>();
 4         for (int i = 0; i < nums.length; ++i) {
 5             if (hs.contains(nums[i])) {
 6                 return true;
 7             }
 8             hs.add(nums[i]);
 9         }
10         return false;
11     }
12 }

 

方法二:

 1 public class Solution {
 2     public boolean containsDuplicate(int[] nums) {
 3         Arrays.sort(nums);
 4         for (int i = 1; i < nums.length; ++i) {
 5             if (nums[i] == nums[i - 1]) {
 6                 return true;
 7             }
 8         }
 9         return false;
10     }
11 }

 

posted @ 2017-03-25 13:13  Deribs4  阅读(133)  评论(0编辑  收藏  举报