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.

思路:

这道题做了很久,开始思路是挨个比较,最大复杂度为n2,最后看了别人的思路,醒悟可以用map做,因为map 的key是不允许重复的(第一次觉醒,原来还可以用map,之前压根没想到)

编码:

import java.util.*;
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]))
                return true;
            else
                map.put(nums[i],i);
        }
        return false;
    }
}

 

posted on 2015-09-20 17:01  cainiao15  阅读(113)  评论(0编辑  收藏  举报

导航