题意:

image.png

解题思路:

  1. 思路:
  2. 注意点://4 - 2 = 2如果是本身,则跳过
  3. if($target == $num && $cnt == 1) continue;

PHP代码实现:

  1. class TwoSum {
  2. /**
  3. * Initialize your data structure here.
  4. */
  5. function __construct() {
  6. $this->map = [];
  7. }
  8. /**
  9. * Add the number to an internal data structure..
  10. * @param Integer $number
  11. * @return NULL
  12. */
  13. function add($number) {
  14. ++$this->map[$number];
  15. }
  16. /**
  17. * Find if there exists any pair of numbers which sum is equal to the value.
  18. * @param Integer $value
  19. * @return Boolean
  20. */
  21. function find($value) {
  22. foreach($this->map as $num => $cnt){
  23. $target = $value - $num;
  24. //4 - 2 = 2如果是本身,则跳过
  25. if($target == $num && $cnt == 1) continue;
  26. if(isset($this->map[$target])) return true;
  27. }
  28. return false;
  29. }
  30. }

go代码实现:

  1. type TwoSum struct {
  2. m map[int]int
  3. }
  4. /** Initialize your data structure here. */
  5. func Constructor() TwoSum {
  6. return TwoSum{map[int]int{}}
  7. }
  8. /** Add the number to an internal data structure.. */
  9. func (this *TwoSum) Add(number int) {
  10. this.m[number]++
  11. }
  12. /** Find if there exists any pair of numbers which sum is equal to the value. */
  13. func (this *TwoSum) Find(value int) bool {
  14. for n, c := range this.m {
  15. diff := value - n
  16. if n != diff {
  17. if c1 := this.m[diff]; c1 > 0 {
  18. return true
  19. }
  20. } else {
  21. //证明不是本身
  22. if c > 1 {return true}
  23. }
  24. }
  25. return false
  26. }
  27. /**
  28. * Your TwoSum object will be instantiated and called as such:
  29. * obj := Constructor();
  30. * obj.Add(number);
  31. * param_2 := obj.Find(value);
  32. */