golang_算法: leetcode_数组04-存在重复

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/weixin_43851310/article/details/87907718
import "fmt"

//1.
func containsDuplicate1(nums []int) bool {
	for i := 0; i < len(nums); i++ {
		for j := i + 1; j < len(nums); j++ {
			if nums[i] == nums[j] {
				return true
			}
		}
	}
	return false
}

//2.利用map键值对中键唯一的特性,默认为false,
// 如果存在了,设置true。如果为true了,判断已经存在
func containsDuplicate2(nums []int) bool {
	hash := make(map[int]bool)
	for _,v := range nums {
		if hash[v] == true {
			return true
		}else{
			hash[v] = true
		}
	}
	return false
}

//3.利用map进行值的判断
func containsDuplicate(nums []int) bool {
	m := make(map[int]struct{})
	for _,v := range nums {
		_,ok := m[v]
		if ok {
			return true
		}else{
			m[v] = struct{}{} //struct{} 代表一个空值
		}
	}
	return false
}

func main() {
	nums := []int{1,1,1,0}
	t := containsDuplicate(nums)
	fmt.Println(t)
}

Output:

true

猜你喜欢

转载自blog.csdn.net/weixin_43851310/article/details/87907718