LeetCode-Contains Duplicate 217

  • Problem:

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。

         该方法适合数组小的情况,因为耗时比较严重。

方案二:利用hashmap,遍历数组,将数组中的每一个数加入map中,如果map中没有这个数就加入下一个数,如果有这个数则返回true,遍历完之后返回false。

          该方法比较适合数组大的情况,查找效率较高。

  • anwser:

1 利用数组查找(其实应该先排序,然后查找相邻两个数是否相同)

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


2 利用HashSet

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值