jinhuang1102

922. Sort Array By Parity II

Mar 4th, 2019
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. """
  2. 这题比如果可以用额外空间的话还是比较简单的,如果不能用额外空间的话,那个就需要下面的方法
  3. 1)create a pointer point the odd index from beginning. Go for each even index of the array A, if the element of even index is odd, find the even element in the odd index pointer, and then swap them.
  4. """
  5. class Solution(object):
  6.     def sortArrayByParityII(self, A):
  7.         """
  8.        :type A: List[int]
  9.        :rtype: List[int]
  10.        """
  11.         j = 1
  12.         for i in range(0, len(A), 2):
  13.             if A[i] % 2:
  14.                 while A[j] % 2:
  15.                     j += 2
  16.                    
  17.                 tmp = A[j]
  18.                 A[j] = A[i]
  19.                 A[i] = tmp
  20.                
  21.         return A
  22.  
  23.  
  24.  
  25. class Solution(object):
  26.     def sortArrayByParityII(self, A):
  27.         """
  28.        :type A: List[int]
  29.        :rtype: List[int]
  30.        """
  31.         odd = []
  32.         even = []
  33.        
  34.         for i in range(0, len(A)):
  35.             if A[i] % 2 == 0:
  36.                 even.append(A[i])
  37.             else:
  38.                 odd.append(A[i])
  39.        
  40.         res = [0] * len(A)
  41.         for i in range(0, len(A)):
  42.             if i % 2 == 0:
  43.                 res[i] = even.pop()
  44.             else:
  45.                 res[i] = odd.pop()
  46.                
  47.         return res
Advertisement
Add Comment
Please, Sign In to add comment