算法系列——Contains Duplicate

来源:互联网 发布:上海德比软件 编辑:程序博客网 时间:2024/06/05 18:34

算法描述

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.

解题思路

利用哈希表统计出现值出现的次数,时间复杂度为O(n),空间复杂度为O(1)

程序实现

public class Solution {    public boolean containsDuplicate(int[] nums) {        Map<Integer,Integer> map=new HashMap<Integer,Integer>();        for(int i=0;i<nums.length;i++){            if(map.containsKey(nums[i])&&map.get(nums[i])!=i)                return true;            map.put(nums[i],i);        }        return false;    }}