217Contains Duplicate

来源:互联网 发布:php驾校考试系统源码 编辑:程序博客网 时间:2024/05/06 01:58

题目链接:https://leetcode.com/problems/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.

解题思路:

  • 哈希 map 轻松搞定。
  • 之前鬼使神差的使用 List 里面的 contains()方法,超时。 自己写的快速排序,然后比较相邻两个元素是否相等,超时。
  • 虽然本能地想到哈希 containsKey() 方法,但居然又联想到 List 中的 Contains(),说明是概念不清。哈希查找与数组查找原理不同。通常哈希查找一个元素的速度,远快于数组中的查找!!!
public class Solution {    public boolean containsDuplicate(int[] nums) {        if(nums == null || nums.length == 0)            return false;        int len = nums.length;        HashMap<Integer, Integer> map = new HashMap();        for(int i = 0; i < len; i ++) {            if(map.containsKey(nums[i]))                return true;            map.put(nums[i], 1);        }        return false;    }}
16 / 16 test cases passed.Status: AcceptedRuntime: 508 ms
0 0