Partition Array
Question
Given an array nums
of integers and an int k
, partition the array (i.e move the elements in "nums") such that:
- All
elements < k
are moved to the left - All
elements >= k
are moved to the right
Return the partitioning index, i.e the first index i nums[i] >= k.
Example
If nums = [3,2,2,1]
and k=2
, a valid answer is 1
.
Note You should do really partition in array nums instead of just counting the numbers of integers smaller than k.
If all elements in nums are smaller than k, then return nums.length
Challenge Can you partition the array in-place and in O(n)?
Analysis
Test Cases:
- empty string
- all elements are smaller than k
- all elements are larger than k
Thoughts
和sort color的题差不多,类似quick sort的做法 这里我直接用了sort color的模板改了一下
Solution
class Solution:
"""
@param nums: The integer array you should partition
@param k: As description
@return: The index after partition
"""
def partitionArray(self, nums, k):
# write your code here
# you should partition the nums by k
# and return the partition index as description
numRed = 0
numBlue = 0
length = len(nums)
index = 0
while index <= length - 1 - numBlue:
if nums[index] < k:
nums = self.swap(nums, numRed, index)
numRed += 1
index += 1
elif nums[index] >= k:
nums = self.swap(nums, length - 1 - numBlue, index)
numBlue += 1
return index
def swap(self, nums, i, j):
tmp = nums[j]
nums[j] = nums[i]
nums[i] = tmp
return nums