|
| 1 | +""" |
| 2 | +If all the numbers in the array is larger or equal than 0, all the square value will automatically be sorted. |
| 3 | +
|
| 4 | +If there are negatives in the array, we need to seperate the negatives and the others. |
| 5 | +To do that, we need to find the index of 0 or index of first positive element. We call the index `m`. |
| 6 | +So for the non-negative part, it is sorted already: `numbers[m:]`. |
| 7 | +The negative part sorted: `[-1*n for n in reversed(numbers[:m])]` |
| 8 | +
|
| 9 | +And now we apply the merge method in the merge sort. |
| 10 | +The method takes two sorted array and turn it into one. |
| 11 | +If you are not familiar it take a look at [this](https://leetcode.com/problems/merge-sorted-array/discuss/208832/Python-O(M%2BN)-Solution-Explained). |
| 12 | +After we got the sorted array, we compute all the squares and return. |
| 13 | +
|
| 14 | +The time complexity is O(N). |
| 15 | +The space complexity is O(N). |
| 16 | +""" |
| 17 | +class Solution(object): |
| 18 | + def sortedSquares(self, numbers): |
| 19 | + if not numbers: return numbers |
| 20 | + |
| 21 | + if numbers[0]>=0: |
| 22 | + return [n**2 for n in numbers] |
| 23 | + |
| 24 | + m = 0 |
| 25 | + for i, n in enumerate(numbers): |
| 26 | + if n>=0: |
| 27 | + m = i |
| 28 | + break |
| 29 | + |
| 30 | + A, B = numbers[m:], [-1*n for n in reversed(numbers[:m])] |
| 31 | + return [n**2 for n in self.merge(A, B)] |
| 32 | + |
| 33 | + def merge(self, A, B): |
| 34 | + a = b = 0 |
| 35 | + opt = [] |
| 36 | + while a<len(A) and b<len(B): |
| 37 | + if A[a]<B[b]: |
| 38 | + opt.append(A[a]) |
| 39 | + a+=1 |
| 40 | + else: |
| 41 | + opt.append(B[b]) |
| 42 | + b+=1 |
| 43 | + if a<len(A): opt.extend(A[a:]) |
| 44 | + if b<len(B): opt.extend(B[b:]) |
| 45 | + return opt |
| 46 | + |
| 47 | +""" |
| 48 | +How to approach problem like this? |
| 49 | +
|
| 50 | +**Mindset 1, think of the time complexity of your brute force.** |
| 51 | +In this case, simply square all the element and sort them. |
| 52 | +That is O(NLogN). |
| 53 | +So we are going to try to reduce it into O(N) or O(LogN) or O(1). |
| 54 | +
|
| 55 | +**Mindset 2, think of the time complexity that you are not able to reduce.** |
| 56 | +For example, I could not think of a way to square all the sorted element without O(N). |
| 57 | +So all other operation less or equal to O(N) does not effect the time complexity. |
| 58 | +When I am trying to find `m`, I can use binary search to search for it, the time complexity is O(LogN). |
| 59 | +But O(N) is fine, so I use this simpler approach. |
| 60 | +Sure, we can optimize it and make it faster. But it is not the bottle neck here. |
| 61 | +**I think what the interviwer wanted to see is you realizing the bottle neck and solve it.** |
| 62 | +""" |
0 commit comments