[算法学习]给定一个整型数组,找出两个整数为指定整数的和(3)

问题描述:
设计一个类,包含如下两个成员函数:
Save(int input) 插入一个整数到一个整数集合里。
Test(int target) 检查是否存在两个数和为输入值。如果存在着两个数,则返回true,否则返回false
允许整数集合中存在相同值的元素

分析:
[算法学习]给定一个整型数组,找出两个整数为指定整数的和(2)不同,这里需要算出的是存不存在这两个数,可以在上一篇的基础上修改一下数据结构,HashMap其中key是数值,value是数值个数,然后需要作两步判断,map中存在数的两倍等于目标数,这时需要value=2才返回true


理一理代码思路

(1). 写Save(int input)。这个就简单了,只需判断是否存在input为key,有就value+1,没有就value=1。代码如下:

1
2
3
4
5
6
7
8
9
public void Save(int input)
{

int count = 0;
if (map.containsKey(input))
{
count = map.get(input);
}
map.put(input, count + 1);
}

(2). 检查是否存在两个数和为输入值。上面的分析已经讲得差不多,这里就直接贴代码。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public boolean Test(int target)
{

Iterator<Integer> iterator = map.keySet().iterator();
while (iterator.hasNext())
{
int one = iterator.next();
int two = target - one;
System.out.println("one:"+one+" two:"+two);
if (map.containsKey(two))
{
// two<<1等价于two*2
if (!(target ==two<<1 && map.get(two) == 1))
{
return true;
}
}
}
return false;
}

整合代码最终如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.HashMap;
import java.util.Iterator;

public class TwoNumOfSum3
{

// key:数值,value:数值对应的个数
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

/**
* 插入一个整数到一个整数集合里
* @param input
*/

public void Save(int input)
{

int count = 0;
if (map.containsKey(input))
{
count = map.get(input);
}
map.put(input, count + 1);
}

/**
* 检查是否存在两个数和为输入值
* @param target
* @return 如果存在着两个数,则返回true,否则返回false
*/

public boolean Test(int target)
{

Iterator<Integer> iterator = map.keySet().iterator();
while (iterator.hasNext())
{
int one = iterator.next();
int two = target - one;
System.out.println("one:"+one+" two:"+two);
if (map.containsKey(two))
{
if (!(target ==two<<1 && map.get(two) == 1))
{
return true;
}
}
}
return false;
}

/**
* @param args
*/

public static void main(String[] args)
{

TwoNumOfSum3 t=new TwoNumOfSum3();
t.Save(5);
t.Save(10);
t.Save(4);
t.Save(7);
System.out.println(t.Test(12));
}
}