用Go检查给定数组中元素是否存在双倍数的程序实例(Golang)

47 阅读1分钟

概述

给出一个数组。目的是找出是否有任何数字的双倍数也存在。

例子1

Input: [8,5,4,3]
Output: true
Explanation: 4 and 8

例子2

Input: [1,3,7,9]
Output: false
Explanation: There exists no number for which its double exist

我们的想法是在这里使用一个地图。对于每个元素,我们将检查并返回真,如果

  • 如果它的倍数存在于地图中

  • 如果数字是偶数,那么其一半存在于地图中

程序

下面是同样的程序

package main

import "fmt"

func checkIfExist(arr []int) bool {
	numMap := make(map[int]bool)

	for i := 0; i < len(arr); i++ {
		if numMap[arr[i]*2] {
			return true
		}
		if arr[i]%2 == 0 && numMap[arr[i]/2] {
			return true
		}
		numMap[arr[i]] = true
	}
	return false
}

func main() {
	output := checkIfExist([]int{8, 5, 4, 3})
	fmt.Println(output)

	output = checkIfExist([]int{1, 3, 7, 9})
	fmt.Println(output)

}

输出:

true
false