Leet Code OJ 217. Contains Duplicate [Difficulty: Easy]

来源:互联网 发布:文字特效软件下载 编辑:程序博客网 时间:2024/04/29 13:42

题目:
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.

思路分析:
题意是给定一个整形数组,如果里面的元素都不重复,返回false,否则返回true。以下的做法使用map作为临时存储,记录元素是否出现。

代码实现(时间复杂度O(n)):

public class Solution {    public static boolean containsDuplicate(int[] nums) {        Map<Integer, Boolean> map = new HashMap<>();        for (int num : nums) {            Object o = map.get(num);            if (o == null) {                map.put(num, true);            } else {                return true;            }        }        return false;    }}
1 0
原创粉丝点击