Leetcode - Longest Word in Dictionary
Leetcode - Median of Two Sorted Arrays

Leetcode - Two Sum III - Data structure design

violet posted @ 5 年前 in 算法 with tags Algorithm Golang 2sum , 373 阅读

https://leetcode.com/problems/two-sum-iii-data-structure-design/

Design and implement a TwoSum class. It should support the following operations: add and find.

add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.

Example 1:

add(1); add(3); add(5);
find(4) -> true
find(7) -> 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
type TwoSum struct {
    nums []int
}
 
 
/** Initialize your data structure here. */
func Constructor() TwoSum {
    return TwoSum{
        nums: []int{},
    }
}
 
 
/** Add the number to an internal data structure.. */
func (this *TwoSum) Add(number int)  {
    this.nums = append(this.nums, number)
}
 
 
/** Find if there exists any pair of numbers which sum is equal to the value. */
func (this *TwoSum) Find(value int) bool {
    hash := map[int]bool{}
    for _, n := range this.nums{
        if hash[value-n] {
            return true
        }
        hash[n] = true
    }
    return false
}
 
 
/**
 * Your TwoSum object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Add(number);
 * param_2 := obj.Find(value);
 */
Horny Escorts in Deh 说:
4 年前

The red blossom Cheek will attract your mind.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter