1. Split numbers
Given an array of ints, for example [6, 4, -3, 0, 5, -2, -1, 0, 1, -9]
,
implement in one of the following languages
to move all positive integers to the left, all negative integers to the right,
and all zeros to the middle.You are not allowed to consume extra O(n) storage space, aka.
your algorithm space complexity should be O(1).
2. Serialize reversed list
Given a “reversed list”, whose first tuple value is the id of string type, and second tuple value is the path to locate the id in a structured document.
For example, {"1": "bar", "2": "foo.bar", "3": "foo.foo", "4": "baz.cloudmall.com", "5": "baz.cloudmall.ai"}
Your mission is to transform the list back to a document in JSON format.
For example, a legit JSON for the above list would be:
{
"bar": "1",
"foo": {
"bar": "2",
"foo": "3"
},
"baz": {
"cloudmall": {
"com": "4",
"ai": "5"
}
}
}
第一题
用空间复杂度O(1) 将[6, 4, -3, 0, 5, -2, -1, 0, 1, -9],将负数移到右边,正数移到左边。
def move1(array):
if not array:
return None
n = len(array)
if n <= 1:
return array
i = 0
j = n - 1
while i < j:
if array[j] < 0:
j -= 1
if array[i] >= 0:
i += 1
# 必须是 array[j] >= 0 ,否则会出现array[i]=-2, array[j] = 0
if array[i] < 0 and array[j] >= 0:
array[i], array[j] = array[j], array[i]
return array
def move2(array):
if not array:
return None
n = len(array)
if n <= 1:
return array
j = -1
i = 0
# 用来记录第一个负数的位置,并且和后面的
while i < n:
if array[i] < 0 and j == -1:
j = i
if array[i] >= 0 and j != -1:
array[i], array[j] = array[j], array[i]
# 非常重要,相当于把i又拉回去了
i = j
j = -1
i += 1
return array
if __name__ == '__main__':
test = [6, 4, -3, 0, 5, -2, -1, 0, 1, -9]
print(move1(test))
print(move2(test))
# 以上两种算法的空间复杂度均为O(1)
第二题
{“1”: “bar”, “2”: “foo.bar”, “3”: “foo.foo”, “4”: “baz.cloudmall.com”, “5”: “baz.cloudmall.ai”}
将其进反向序列化.
import json
test = {"1": "bar", "2": "foo.bar", "3": "foo.foo", "4": "baz.cloudmall.com", "5": "baz.cloudmall.ai"}
if isinstance(test, str):
test = json.loads(test)
tmp = []
for k, v in test.items():
cnt = v.count('.')
if cnt == 0:
_ = dict()
_[v] = k
tmp.append(_)
else:
keys = v.split('.')[::-1]
dict_ = [{} for _ in keys]
stack = []
for i, key, dic in zip(range(len(keys)), keys, dict_):
if i == 0:
dic[key] = k
else:
dic[key] = stack[-1]
stack.append(dic)
tmp.append(stack[-1])
i = 0
while i < len(tmp):
if i == 0:
ret_dict = tmp[i]
else:
ret_dict = ret_dict.update(tmp[i])
i += 1
print(ret_dict)