Skip to content

Commit 06e5333

Browse files
author
shangchun
committed
leetcode
1 parent d5080ea commit 06e5333

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

reverseInteger.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# @return an integer
2+
def reverse(x):
3+
maxint = 2**31 - 1
4+
if x > 0:
5+
sign = 1
6+
else:
7+
sign = -1
8+
x = -x
9+
r = 0
10+
while x:
11+
r = r * 10 + x % 10
12+
if r > maxint:
13+
return 0
14+
x = x / 10
15+
return r * sign
16+
17+
assert reverse(123) == 321
18+
assert reverse(-123) == -321
19+
assert reverse(0) == 0
20+
assert reverse(-1) == -1
21+
assert reverse(1) == 1
22+
assert reverse(100) == 1
23+
assert reverse(10000000003) == 0

twoSum.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# @return a tuple, (index1, index2)
2+
def twoSum(num, target):
3+
m = {}
4+
for k in range(len(num)):
5+
v = num[k]
6+
remain = target - v
7+
if remain in m:
8+
return (m[remain], k + 1)
9+
elif v not in m:
10+
m[v] = k + 1
11+
return -1
12+
13+
## UGLY CODE!
14+
# m = {}
15+
# length = len(num)
16+
# for i in range(length):
17+
# if num[i] not in m:
18+
# m[num[i]] = []
19+
# m[num[i]].append(i + 1);
20+
# keys = m.keys()
21+
# keys.sort()
22+
# i = 0
23+
# j = len(keys) - 1
24+
# print m
25+
# print keys
26+
# while i <= j:
27+
# print i
28+
# print j
29+
# s = keys[i] + keys[j];
30+
# if s > target:
31+
# j = j - 1
32+
# elif s < target:
33+
# i = i + 1
34+
# else:
35+
# if i == j and len(m[keys[i]]) == 1:
36+
# return -1
37+
# elif m[keys[i]][0] < m[keys[j]][-1]:
38+
# return (m[keys[i]][0], m[keys[j]][-1])
39+
# else:
40+
# return (m[keys[j]][-1], m[keys[i]][0])
41+
# return -1
42+
43+
assert twoSum([2, 7, 11, 15], 9) == (1, 2)
44+
assert twoSum([2, 5, 21, 12], 26) == (2, 3)
45+
assert twoSum([150, 24, 79, 50, 88, 345, 3], 200) == (1, 4)
46+
assert twoSum([2, 1, 9, 4, 4, 56, 90, 3], 8) == (4, 5)

0 commit comments

Comments
 (0)