LeetCode -- Contains Duplicate

Question:

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.

Analysis:

题目描述:给出一个由正整数构成的数组,如果数组中包含重复元素则返回true,若无重复元素则返回false。

思考:1.由于题目并没有给出要求不能使用额外的空间,而且数组是无序的,因此一种思路是使用HashMap记录已经遍历过的数组元素,使用的时间效率是查找HashMap的时间,空间复杂度O(n).

2.若题目要求不能使用额外空间的话,一种方式是先对数组排序,然后找到是否有重复元素。但是这样时间复杂度较高。有O(n2)

Answer:

public class Solution {
    public static boolean containsDuplicate(int[] nums) { //放到HashMap里面
        if(nums.length == 0 || nums.length == 1)
                return false;
        HashMap<Integer, Integer> ht = new HashMap<Integer, Integer>();
        for(int i=0; i<nums.length; i++) {
                if(ht.containsKey(nums[i]))
                    return true;
                else {
                    ht.put(nums[i], 1);
                }
        }
        return false;
    }
}
原文地址:https://www.cnblogs.com/little-YTMM/p/4820025.html