文章 224
评论 6
浏览 200764
Array - 217. Contains Duplicate

Array - 217. Contains Duplicate

217、Contains Duplicate

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: false

思路:

很简单的一题,只用找出数组中有没有重复的数字,用set或者map做就可以。

代码:

java:

class Solution {

    public boolean containsDuplicate(int[] nums) {

         return IntStream.of(nums).distinct().count() != nums.length;                
    }
}

go:

func containsDuplicate(nums []int) bool {

    if nums == nil || len(nums) == 0 {return false}
    
    maps := make(map[int]bool)
    for _, v := range nums {
        if maps[v] {
            return true
        } else {
            maps[v] = true
        }
    }
    return false
}

标题:Array - 217. Contains Duplicate
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/06/12/1560347478426.html

Nothing just happens, it's all part of a plan.

取消