Contains Duplicate -- 包含重复数字

17 篇文章 0 订阅

在Leetcode上看到一道题,跟之前做的关于找“Single Number" 有点类似。这次的题目是这样的:
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.

Example 1:
Input: [1,2,3,1]
Output: true

Example 2:
Input: [1,2,3,4]
Output: Falst

现在就直接上Java代码:

class Solution {
  public boolean containsDuplicate(int[] nums) {
    HashSet<Integer> set = new HashSet<Integer>();

    for(int i : nums) {
      if(set.contains(i)){
        return true;
      } else {
        set.add(i);
      }
    }
    return false;
  }
}

之前也想到一个方法,是先把数组进行排序,然后将排序好的数组进行相连两个进行比较,如果是相等的,就返回true, 否则返回false. 但是这种方法,用c来实现,跑出的结果是Runtime error, 这就不符合题目的要求的时间复杂度了。

如果有哪里写的不对,请指出来!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值