当前位置:网站首页>[算法] 剑指offer2 golang 面试题6:排序数组中的两个数字之和
[算法] 剑指offer2 golang 面试题6:排序数组中的两个数字之和
2022-07-06 09:18:00 【邓嘉文Jarvan】
[算法] 剑指offer2 golang 面试题6:排序数组中的两个数字之和
题目1:
给定一个已按照 升序排列 的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。
函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 0 开始计数 ,所以答案数组应当满足 0 <= answer[0] < answer[1] < numbers.length 。
假设数组中存在且只存在一对符合条件的数字,同时一个数字不能使用两次。
示例 1:
输入:numbers = [1,2,4,6,10], target = 8
输出:[1,3]
解释:2 与 6 之和等于目标数 8 。因此 index1 = 1, index2 = 3 。
示例 2:
输入:numbers = [2,3,4], target = 6
输出:[0,2]
示例 3:
输入:numbers = [-1,0], target = -1
输出:[0,1]
提示:
2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers 按 递增顺序 排列
-1000 <= target <= 1000
仅存在一个有效答案
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kLl5u1
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1:
//思路1: 双指针
//left,right
//如果左边加右边小于target,left ++
//如果左边加右边大于target,right --
//相等返回 {left,right}
代码
func twoSum(numbers []int, target int) []int {
//思路1: 双指针
//left,right
//如果左边加右边小于target,left ++
//如果左边加右边大于target,right --
//相等返回 {left,right}
//参数处理
if len(numbers) < 2 {
return nil
}
//双指针
left,right := 0,len(numbers) - 1
for left < right{
tempTarget := numbers[left] + numbers[right]
if tempTarget == target {
return []int{
left,right}
}else if tempTarget < target {
left ++
}else if tempTarget > target {
right --
}
}
//没有找到返回空
return nil
}
测试
边栏推荐
- Unity场景跳转及退出
- Problèmes avec MySQL time, fuseau horaire, remplissage automatique 0
- Common DOS commands
- FairyGUI循環列錶
- 【RTKLIB 2.4.3 b34 】版本更新简介一
- [Nodejs] 20. Koa2 onion ring model ----- code demonstration
- FairyGUI条子家族(滚动条,滑动条,进度条)
- Unity3D基础入门之粒子系统(属性介绍+火焰粒子系统案例制作)
- 2021.11.10 compilation examination
- Introduction to the daily practice column of the Blue Bridge Cup
猜你喜欢
NRF24L01故障排查
第一人称视角的角色移动
PR 2021 quick start tutorial, first understanding the Premiere Pro working interface
RTKLIB: demo5 b34f.1 vs b33
idea中好用的快捷键
Single chip Bluetooth wireless burning
Derivation of logistic regression theory
FairyGUI人物状态弹窗
There is no red exclamation mark after SVN update
Database course design: college educational administration management system (including code)
随机推荐
[leetcode19]删除链表中倒数第n个结点
FairyGUI循環列錶
Problèmes avec MySQL time, fuseau horaire, remplissage automatique 0
About using @controller in gateway
编译原理:源程序的预处理及词法分析程序的设计与实现(含代码)
(5) Introduction to R language bioinformatics -- ORF and sequence analysis
MySQL time, time zone, auto fill 0
Unity scene jump and exit
[offer78]合并多个有序链表
Combination of fairygui check box and progress bar
NRF24L01故障排查
Single chip Bluetooth wireless burning
Affichage du changement de valeur du Buff de gain de l'interface graphique de défaillance
Itext 7 生成PDF总结
[Offer18]删除链表的节点
Introduction to the daily practice column of the Blue Bridge Cup
[leetcode622] design circular queue
Unity3D,阿里云服务器,平台配置
Gateway fails to route according to the service name, and reports an error service unavailable, status=503
Database course design: college educational administration management system (including code)