当前位置:网站首页>2020-11-07:已知一个正整数数组,两个数相加等于N并且一定存在,如何找到两个数相乘最小的两个数?
2020-11-07:已知一个正整数数组,两个数相加等于N并且一定存在,如何找到两个数相乘最小的两个数?
2020-11-07 23:08:00 【福大大架构师每日一题】
福哥答案2020-11-07:
1.哈希法。 2.排序+双指针夹逼。
golang代码如下:
package main
import (
"fmt"
"sort"
)
const INT_MAX = int(^uint(0) >> 1)
func main() {
nums := []int{2, 1, 3, 4, 5, 6, 9, 8, 7}
fmt.Println(twoSumMultiplication1(nums, 12), "哈希法")
fmt.Println(twoSumMultiplication2(nums, 12), "排序+双指针夹逼")
}
//哈希法
func twoSumMultiplication1(nums []int, target int) int {
map0 := make(map[int]struct{})
min := INT_MAX
for i := 0; i < len(nums); i++ {
complement := target - nums[i] //差值 = 目标值-元素值
if _, ok := map0[complement]; ok { //如果字典里有差值,说明已经找到了
//确保complement是较小的那个值
if complement > nums[i] {
complement, nums[i] = nums[i], complement
}
//谁小保存谁
if complement < min {
min = complement
//如果最小值是1,就不用循环了。
if min == 1 {
break
}
}
} else {
//如果字典里没有差值,缓存数组的当前值
map0[nums[i]] = struct{}{}
}
}
return min
}
//排序+双指针夹逼
func twoSumMultiplication2(nums []int, target int) int {
//排序
sort.Slice(nums, func(i, j int) bool {
return nums[i] < nums[j]
})
sumtemp := 0
min := INT_MAX
for i, j := 0, len(nums)-1; i < j; {
sumtemp = nums[i] + nums[j]
if target == sumtemp {
if min > nums[i] {
min = nums[i]
if min == 1 {
break
}
}
i++
} else if target > sumtemp {
i++
} else {
j--
}
}
return min
}
执行结果如下:
版权声明
本文为[福大大架构师每日一题]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4553401/blog/4707758
边栏推荐
- Qt混合Python开发技术:Python介绍、混合过程和Demo
- The instanceof operator in ecmascript7 specification
- Data transmission of asynchronous serial communication controlled by group bus communication
- ECMAScript7规范中的instanceof操作符
- laravel8更新之维护模式改进
- Search and replace of sed
- How to think in the way of computer
- 获取树形菜单列表
- Implementation of Caesar cipher
- leetcode之判断路径是否相交
猜你喜欢
Learn Scala if Else statement
[C + + learning notes] how about the simple use of the C + + standard library STD:: thread?
The road of cloud computing: a free AWS cloud server
leetcode之判断路径是否相交
Basic knowledge of C + +
LadonGo开源全平台渗透扫描器框架
These core technology of object-oriented, after you master it, you can have a good interview
京淘项目day09
Improvement of maintenance mode of laravel8 update
Everything is 2020, LINQ query you are still using expression tree
随机推荐
Thinkphp6中where条件中字段与字段比较条件的写法
AFO
ECMAScript7规范中的instanceof操作符
什么都2020了,LINQ查询你还在用表达式树
一次公交卡被“盗刷”事件带来的思考
Awk implements SQL like join operation
It's time to end bertology
学习Scala IF…ELSE 语句
awk实现类sql的join操作
Android Basics - RadioButton (radio button)
supervisor进程管理安装使用
Implementation of Caesar cipher
C / C + + Programming Notes: what are the advantages of C compared with other programming languages?
wanxin金融
Face recognition: attack types and anti spoofing techniques
工作1-3年的程序员,应该具备怎么样的技术能力?该如何提升?
Static + code block + polymorphism + exception
The emergence and significance of micro service
Web安全(一)---浏览器同源策略
Git code submission operation, and git push prompt failed to push some refs'xxx '