Leetcode75. Sort Colors
先用partition的思想做了一下,发现其实根本不需要那么复杂,只是用了partition的左右双指针的思想而已。
class Solution {
public void sortColors(int[] nums) {
if(nums==null|nums.length<2) return;
int left = 0,right = nums.length-1;//left represent position for next 0;right for next 2
int index = 0;
while(index<=right){
if(nums[index]==0) {
swap(nums,index,left++);
}
if(nums[index]==2) {
swap(nums,index,right--);
index--; //important
}
index++;
}
}
private void swap(int[] n,int a,int b){
int temp = n[a];
n[a] = n[b];
n[b] = temp;
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Sort Colors.
Memory Usage: 37.3 MB, less than 54.03% of Java online submissions for Sort Colors.

浙公网安备 33010602011771号