Leetcode - 217. Contains Duplicate
Leetcode - 217. Contains Duplicate
- Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
func containsDuplicate(nums []int) bool {
numMap:= make(map[int]int)
for _, j:=range(nums){
_, ok:= numMap[j]
if ok{
return true
}else{
numMap[j]+=1
}
}
return false
}
Another Approach
1
2
3
4
5
6
7
8
9
10
11
func containsDuplicate(nums []int) bool {
sort.Ints(nums) // sort the slice
// use a loop to compare each element with its next element
for i := 0; i < len(nums)-1; i++ {
// if any two elements are the same, return true
if nums[i] == nums[i+1] {
return true
}
}
return false // if no duplicates are found, return false
}
This post is licensed under CC BY 4.0 by the author.