LeetCode:217. Contains Duplicate 解题

217. Contains Duplicate
Difficulty: Easy
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.

题目的意思是:给你个整型的数组,看看是否有元素相同,如果相同则返回true,如果没有则返回false。

第一思想是遍历检查,这个直接就时间超时了,这里就补贴代码了。后来看到Tags里面写但是hashtable,所以这里应该要和Hash相结合把。

写了个和hashmap应用解决的方法。

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

 但是提交后发现,非常慢,效率不高,不知道是否有人知晓比较好的解决方法,希望告知,谢谢。

 -------------------------------------------------------------------------------------------------

更新:6/4/2016 12:50:28 AM

经过排序之后,比较临近的元素这样效率更高!!

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);
        int length = nums.length;
        for (int i = 0; i < length; i ++) {
            if (i != length - 1 && nums[i] == nums[i + 1]){
                return true;
            } else if (i == length - 1) {
                return false;
            }
        }
        return false;
    }
}

猜你喜欢

转载自rayfuxk.iteye.com/blog/2303004
今日推荐