905. Sort Array By Parity
Given an array nums of non-negative integers, return an array consisting of all the even elements of nums, followed by all the odd elements of nums.
You may return any answer array that satisfies this condition.
Example 1:
Input: nums = [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
- 1 <= nums.length <= 5000
- 0 <= nums[i] <= 5000
Solution 나의 코드 [Runtime: 80ms, Memory Usage: 15.1MB]
[Runtime beats 64.06% of python 3 submission] [Memory usage beats 87.51% of python3 submission]
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
for idx in range(len(nums))[::-1]:
if nums[idx] % 2 != 0:
back = nums.pop(idx)
nums.append(back)
return nums
Solution 나의 코드2 [Runtime: 72ms, Memory Usage: 15.1MB]
[Runtime beats 94.63% of python 3 submission] [Memory usage beats 25.84% of python3 submission]
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]: # using two pointer
i = 0
j = len(nums) - 1
while(i != j):
if(nums[i] % 2 == 0):
i = i + 1 #If the element is even, there's no need to move it, just move ahead
else:
nums[i], nums[j] = nums[j], nums[i]
j = j - 1 # Element moved to jth index is odd, so we move to j-1.
# i = i + 1, we aren't going to do this, because the element that just moved to the ith index can be an odd element.
return nums
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
front = 0 #front
back = len(nums)-1
while front < back :
if nums[front] % 2 == 0: # even
front += 1
else:
nums[front], nums[back] = nums[back], nums[front]
back -= 1
return nums
'LeetCode' 카테고리의 다른 글
1051. Height Checker (0) | 2021.07.13 |
---|---|
27. Remove Element (0) | 2021.07.13 |
283. Move Zeroes (0) | 2021.07.12 |
1299. Replace Elements with Greatest Element on Right Side (0) | 2021.07.06 |
941. Valid Mountain Array (0) | 2021.07.06 |
댓글