-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path977.py
71 lines (61 loc) · 1.67 KB
/
977.py
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Solution 1 查找最大的数值按次插入数组,最终逆序输出
"""
class Solution1(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = []
left = 0
right = len(nums) - 1
while left <= right:
left_ = nums[left] ** 2
right_ = nums[right] ** 2
if left_ > right_:
res.append(left_)
left += 1
else:
res.append(right_)
right -= 1
return res[::-1]
"""
Solution 2 使用最小的正序输出
"""
class Solution2(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = []
min_index = None
minimum = float('inf')
for index, num in enumerate(nums):
if num < minimum:
min_index = index
minimum = num
left = right = min_index
# flag =
while left != -1 or right != len(nums):
if left != -1:
left_ = nums[left] ** 2
else:
left_ = nums[0] ** 2
if right != len(nums):
right_ = nums[right] ** 2
else:
right_ = nums[-1] ** 2
if left_ < right_:
if left != -1:
left -= 1
res.append(left_)
else:
if right != len(nums):
right += 1
res.append(right_)
return res
if __name__ == '__main__':
soul = Solution2()
print(soul.sortedSquares([1, 3, 5, 6]))