题意:
解题思路:
思路:
注意点://4 - 2 = 2如果是本身,则跳过
if($target == $num && $cnt == 1) continue;
PHP代码实现:
class TwoSum {
/**
* Initialize your data structure here.
*/
function __construct() {
$this->map = [];
}
/**
* Add the number to an internal data structure..
* @param Integer $number
* @return NULL
*/
function add($number) {
++$this->map[$number];
}
/**
* Find if there exists any pair of numbers which sum is equal to the value.
* @param Integer $value
* @return Boolean
*/
function find($value) {
foreach($this->map as $num => $cnt){
$target = $value - $num;
//4 - 2 = 2如果是本身,则跳过
if($target == $num && $cnt == 1) continue;
if(isset($this->map[$target])) return true;
}
return false;
}
}
go代码实现:
type TwoSum struct {
m map[int]int
}
/** Initialize your data structure here. */
func Constructor() TwoSum {
return TwoSum{map[int]int{}}
}
/** Add the number to an internal data structure.. */
func (this *TwoSum) Add(number int) {
this.m[number]++
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
func (this *TwoSum) Find(value int) bool {
for n, c := range this.m {
diff := value - n
if n != diff {
if c1 := this.m[diff]; c1 > 0 {
return true
}
} else {
//证明不是本身
if c > 1 {return true}
}
}
return false
}
/**
* Your TwoSum object will be instantiated and called as such:
* obj := Constructor();
* obj.Add(number);
* param_2 := obj.Find(value);
*/