zoukankan      html  css  js  c++  java
  • LeetCode -- Contains Duplicate

    Question:

    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.

    Analysis:

    题目描述:给出一个由正整数构成的数组,如果数组中包含重复元素则返回true,若无重复元素则返回false。

    思考:1.由于题目并没有给出要求不能使用额外的空间,而且数组是无序的,因此一种思路是使用HashMap记录已经遍历过的数组元素,使用的时间效率是查找HashMap的时间,空间复杂度O(n).

    2.若题目要求不能使用额外空间的话,一种方式是先对数组排序,然后找到是否有重复元素。但是这样时间复杂度较高。有O(n2)

    Answer:

    public class Solution {
        public static boolean containsDuplicate(int[] nums) { //放到HashMap里面
            if(nums.length == 0 || nums.length == 1)
                    return false;
            HashMap<Integer, Integer> ht = new HashMap<Integer, Integer>();
            for(int i=0; i<nums.length; i++) {
                    if(ht.containsKey(nums[i]))
                        return true;
                    else {
                        ht.put(nums[i], 1);
                    }
            }
            return false;
        }
    }
  • 相关阅读:
    JVM01---简介
    SpringBoot-01创建项目,实例
    git的三种提交方式(目前两种)
    Spring-事务
    JDK及CGLIB动态代理-AOP4种增强
    Spring-静态代理
    Spring-Aop
    初识jvm-1.Java类的加载机制
    java公开课-06-实用类
    java公开课-05-集合及Socket网络编程(简介)
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4820025.html
Copyright © 2011-2022 走看看