0

#yyds干货盘点# 解决剑指offer:和为S的两个数字

 1 year ago
source link: https://blog.51cto.com/u_15488507/5341839
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# 解决剑指offer:和为S的两个数字

原创

97的风 2022-05-29 23:11:12 博主文章分类:面试题 ©著作权

文章标签 数组 代码实现 i++ 文章分类 Java 编程语言 阅读数131

1.简述:

输入一个升序数组 array 和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,返回任意一组即可,如果无法找出这样的数字,返回一个空数组即可。

[1,2,4,7,11,15],15
[4,11]
返回[4,11]或者[11,4]都是可以的
[1,5,11],10
不存在,返回空数组
[1,2,3,4],5
[1,4]
返回[1,4],[4,1],[2,3],[3,2]都是可以的
[1,2,2,4],4
[2,2]

2.代码实现:

import java.util.*;
public class Solution {
public ArrayList FindNumbersWithSum(int [] array,int sum) {
ArrayList res = new ArrayList();
//创建哈希表,两元组分别表示值、下标
HashMap mp = new HashMap();
//在哈希表中查找target-numbers[i]
for(int i = 0; i < array.length; i++){
int temp = sum - array[i];
//若是没找到,将此信息计入哈希表
if(!mp.containsKey(temp)){
mp.put(array[i], i);
}
else{
//取出数字添加
res.add(temp);
res.add(array[i]);
break;
}
}
return res;
}
}
,>,>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK