LeetCode & Q217-Contains Duplicate-Easy

Array Hash Table

Description:

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.

my Solution:

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        HashSet temp = new HashSet();
        for (int num : nums) {
            temp.add(num);
        }
        return temp.size() < nums.length;
    }
}

HashSet因为不会存储重复元素,可以在这里使用,另一种用法就是调用HashSet.contains()

Other Solution:

public boolean containDuplicate(int[] nums) {
  Array.sort(nums);
  for (int i = 1; i < nums.length; i++) {
    if (nums[i] == nums[i-1]) {
      return true;
    }
  }
  return false;
}
原文地址:https://www.cnblogs.com/duyue6002/p/7204662.html