lc75 quick sort

Given an array of n elements including red, white and blue, sort them in place so that the elements of the same color ar...

Given an array of n elements including red, white and blue, sort them in place so that the elements of the same color are adjacent and arranged in the order of red, white and blue.
In this question, we use integers 0, 1 and 2 to represent red, white and blue, respectively.
be careful:
You can't use the sort function in the code base to solve this problem.

class Solution { public void sortColors(int[] nums) { recur(nums, 0, nums.length - 1); } private static void recur(int[] array, int start_real, int end_real) { int start = start_real; int end = end_real; int temp = array[start]; start++; while (start < end) { if (array[start] < temp && array[end] > temp) { start++; end--; continue; } if (array[start] >= temp && array[end] <= temp) { if (array[start] == temp && array[end] == temp) { start++; end--; continue; } int temp_02 = array[start]; array[start] = array[end]; array[end] = temp_02; start++; end--; continue; } if (array[start] >= temp && array[end] > temp) { end--; continue; } if (array[start] < temp && array[end] <= temp) { start++; continue; } } if (start == end) { if (temp < array[start]) { int temp_01; array[start_real] = array[start - 1]; array[start - 1] = temp; if (end - 2 > start_real) { recur(array, start_real, end - 2); } if (end_real > start) { recur(array, start, end_real); } } else { array[start_real] = array[start]; array[start] = temp; if (end - 1 > start_real) recur(array, start_real, end - 1); if (end_real > start + 1) recur(array, start + 1, end_real); } } else if (start > end) { array[start_real] = array[end]; array[end] = temp; if (end - 1 > start_real) { recur(array, start_real, end - 1); } if (end_real > start) { recur(array, start, end_real); } } else { } } }

AC screenshot

Other people's quick code

public int pivot(int[] A, int left, int right){ int p = A[left]; while(left < right){ while(left < right && A[right] >= p) right--; if(left < right){ A[left] = A[right]; left++; } while(left < right && A[left] <= p) left++; if(left < right){ A[right] = A[left]; right--; } } A[left] = p; return left; } public void qs(int[] A, int left, int right){ int i; if(left < right){ i = pivot(A, left, right); qs(A, left, i - 1); qs(A, i + 1, right); } }

30 June 2020, 00:19 | Views: 2787

Add new comment

For adding a comment, please log in
or create account

0 comments