leetcode-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.

分析


解决方案1(C++)


用C++的话,判断一个数组中是否有重复的元素,可以先排序,如果有重复的,那么这两个元素一定是相邻的,做判断即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
if(nums.size() <2){
return false;
}
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size()-1; i++){
if(nums[i] == nums[i+1]){
return true;
}
}
return false;
}
};

解决方案2(Python)


在 Python 中,有一种集合类型 set,根据集合的定义,重复元素之记录一次,可以根据这一定义判断

1
2
3
4
5
6
7
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(nums) > len(set(nums))

解决方案3(Golang)


1
2
3
4
5
6
7
8
9
10
func containsDuplicate(nums []int) bool {
for index, item := range nums {
for i := index+1; i < len(nums); i++ {
if item == nums[i] {
return true
}
}
}
return false
}

相关问题


题目来源