Partition Array II

update Aug 21, 2017 16:10

LintCodearrow-up-right

Partition an unsorted integer array into three parts:

  • The front part < low

  • The middle part >= low & <= high

  • The tail part > high

Return any of the possible solutions.

Notice

low <= high in all testcases.

Example

Given [4,3,4,1,2,3,1,2], and low = 2 and high = 3.
Change to [1,1,2,3,2,3,4,4].   
([1,1,2,2,3,3,4,4] is also a correct answer, but [1,2,1,2,3,3,4,4] is not)

Challenge

  • Do it in place.

  • Do it in one pass (one loop).

Basic Idea:

和 sort Colors 的思路一样,使用left和right两个指针分别跟踪 <low 和 >high 元素的边界index,用另一个指针从左向右扫描。但要注意边界条件。

Java Code: