Post

two sum

今天开始做leetcode!

选题:Two Sum

链接:https://oj.leetcode.com/problems/two-sum/

写了个最短式(显然通不过,这里只记录下我的思考)

1
2
3
for i in range(len(num)):
        if (target-num[i]) in num:
            return (i+1, num.index(target-num[i])+1)

python 还是很精简的!完成任务速度上还是杠杠的,可惜题目没有那么easy

看到这么一长串input 又说time limite 我也是醉了。网上看到如下code

1
2
3
4
5
6
dict = {}
for i in xrange(len(num)):
    x = num[i]
    if target-x in dict:
        return (dict[target-x]+1, i+1)
    dict[x] = i

好吧,学习了 xrange 和 range 在效率上的差异,index人家是新建dict,我是全num找

有人这样做:

1
2
3
4
5
d = {n:pos for pos,n in enumerate(num) }
for i,n in enumerate(num):
    if d.get(target-n):
        return (i+1, d[target-n]+1)
return None

这样写呢,感觉比较优雅,但内存开销较前者大

同时我也发现‘has_key()’ or ‘in’? 这里也值得学习和注意

1
return None

我觉得应该算程序的严谨吧

对规则重写

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
if str=='':
    return 0
if (str.find('- ') >= 0) or (str.find('-+') >= 0) or (str.find('+-') >= 0) or (str.find('++') >= 0) or (str.find('--') >= 0):
    return 0
    
if str[0] == '-':
    r='-0'
else:
    r='0'
result = 0
for i in str.split('-'):
    for j in i.strip():
        if j=='+':
            continue
        try:
            int(j)
            r=r+j
        except:
            result = result + int(r)
            if result > 2147483647:
                return 2147483647
            if result < -2147483648:
                return -2147483648
            return result
    result = result + int(r)
    r='-0'

if result > 2147483647:
    return 2147483647
if result < -2147483648:
    return -2147483648
return result 

最终

class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): dict = {} for i in xrange(len(num)): x = num[i] if target-x in dict: return (dict[target-x]+1, i+1) dict[x] = i

1
2
3
    for i in xrange(len(num)):
        if (target-num[i]) in num:
            return (i+1,num.index(target-num[i])+1)

Runtime: 60 ms

This post is licensed under CC BY 4.0 by the author.