美文网首页LeetCode笔记
【LeetCode】判断存在重复元素

【LeetCode】判断存在重复元素

作者: 幽泉流霜 | 来源:发表于2019-10-24 21:54 被阅读0次

    给定一个整数数组,判断是否存在重复元素。

    如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

    示例 1:

    输入: [1,2,3,1]
    输出: true
    示例 2:

    输入: [1,2,3,4]
    输出: false
    示例 3:

    输入: [1,1,1,3,3,4,3,2,4,2]
    输出: true

    解题思路:关于重复的问题大部分都可以用HashSet来解决
    1、暴力法
    思路:把每个数字都两两比较一遍
    两次循环 时间复杂度O(n2)
    如果存在一样的数字就返回true
    遍历结束后返回false

     public static int singleNumber(int[] nums) {
       int temp = 0 ;
    //            for(int i = 0 ; i<nums.length-1;i++){
    //                temp = nums[i];
    //                for(int j = i+1 ; j<nums.length ;j++){
    //                    if(temp ==nums[j]){
    //                        return true;
    //                    }
    //                }
    //            }
    //            return false;
    }
    

    2关于重复的问题大部分都可以用HashSet来解决
    将数组的数字加入到HashSet中
    如果包含则返回true
    否则返回false

    class Solution {
        public boolean containsDuplicate(int[] nums) {
             Set<Integer> Hs = new HashSet<>(nums.length);
            for(int i = 0 ; i<nums.length;i++){
                if(Hs.contains(nums[i])){
                    return true;
                }
                Hs.add(nums[i]);
            }
            return false;
        }
    }
    

    相关文章

      网友评论

        本文标题:【LeetCode】判断存在重复元素

        本文链接:https://www.haomeiwen.com/subject/vbwvyctx.html