Problem Description:
Design a class that contains the following two member functions:
Save (int input) inserts an integer into an integer set.
Test (int target) checks if there are two numbers and is the input value. Returns true if there are two numbers, otherwise false
An element that allows the same value in an integer collection
Analysis:
and [algorithm learning] Given an integer array, find out two integers for the specified integer and (2) different, here need to figure out that there is no existence of these two numbers, you can modify the data structure on the basis of the previous article, HashMap where key is the value, value is the number of values, Then you need to make a two-step decision, twice times the number of numbers in the map is equal to the target number, which requires value=2 to return true
Rationale for a code of thought
(1). Write save (int input). This is simple, just to determine if there is input as key, there is value+1, no value=1. The code is as follows:
public void Save(int input)
{
int count = 0;
if (map.containsKey(input))
{
count = map.get(input);
}
map.put(input, count + 1);
}
(2). Checks if there are two numbers and is the input value. The above analysis has been said to be similar, here directly affixed to the code. The code is as follows:
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;
}
The integration code ends up as follows
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));
}
}
From for notes (Wiz)
[Algorithm learning] Given an integer array, find two integers for the specified integer and (3)