Can anyone recorrect this code? Code is not working properly. The output should be a square sorted array. Example :Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] I’m using Leetcode platform.
class Solution(object): def sortedSquares(self, nums: List[int]): out = [] for num in nums: out.append(num**2) self.sorte(out) def sorte(self, out): if len(out)<2: return out else: return self.sorte([each for each in out[1:] if each < out[0]]) + [out[0]] + self.sorte([each for each in out[1:] if each >= out[0]])
Advertisement
Answer
Accepted solution:
class Solution: def sortedSquares(self, A: List[int]) -> List[int]: out = [x*x for x in A] return sorted(out)
If you still want to do like yours check if this can help:
class Solution: def sortedSquares(self, A: List[int]) -> List[int]: out = [] for num in A: out.append(num**2) return self.sorte(out) def sorte(self, out): if len(out)<2: return out else: return self.sorte([each for each in out[1:] if each < out[0]]) + [out[0]] + self.sorte([each for each in out[1:] if each >= out[0]])