sweet1cris

Untitled

Jan 9th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.30 KB | None | 0 0
  1. // 参考程序1
  2. public class Solution {
  3.     /**
  4.      * @param nums an integer array
  5.      * @param low an integer
  6.      * @param high an integer
  7.      * @return nothing
  8.      */
  9.     public void partition2(int[] nums, int low, int high) {
  10.         // Write your code here
  11.         if (nums == null || nums.length <= 1) {
  12.             return;
  13.         }
  14.        
  15.         int pl = 0, pr = nums.length - 1;
  16.         int i = 0;
  17.         while (i <= pr) {
  18.             if (nums[i] < low) {
  19.                 swap(nums, pl, i);
  20.                 pl++;
  21.                 i++;
  22.             } else if (nums[i] > high) {
  23.                 swap(nums, pr, i);
  24.                 pr--;
  25.             } else {
  26.                 i ++;
  27.             }
  28.         }
  29.     }
  30.    
  31.     private void swap(int[] nums, int i, int j) {
  32.         int tmp = nums[i];
  33.         nums[i] = nums[j];
  34.         nums[j] = tmp;
  35.     }
  36. }
  37.  
  38. // 参考程序2
  39. public class Solution {
  40.     /**
  41.      * @param nums an integer array
  42.      * @param low an integer
  43.      * @param high an integer
  44.      * @return nothing
  45.      */
  46.     public void partition2(int[] nums, int low, int high) {
  47.         // Write your code here
  48.         int left = 0;
  49.         int right = nums.length - 1;
  50.  
  51.         // 首先把区间分为 < low 和 >= low 的两个部分
  52.         while(left <= right) {
  53.             while(left <= right && nums[left] < low) {
  54.                 left ++;
  55.             }
  56.             while(left <= right && nums[right] >= low) {
  57.                 right --;
  58.             }
  59.  
  60.             if(left <= right) {
  61.                 int tmp = nums[left];
  62.                 nums[left] = nums[right];
  63.                 nums[right] = tmp;
  64.                 left ++;
  65.                 right --;
  66.             }
  67.         }
  68.  
  69.         // 然后从 >= low 的部分里分出 <= high 和 > high 的两个部分
  70.         right = nums.length - 1;
  71.         while(left <= right) {
  72.             while(left <= right && nums[left] <= high) {
  73.                 left ++;
  74.             }
  75.             while(left <= right && nums[right] > high) {
  76.                 right --;
  77.             }
  78.             if(left <= right) {
  79.                 int tmp = nums[left];
  80.                 nums[left] = nums[right];
  81.                 nums[right] = tmp;
  82.                 left ++;
  83.                 right --;
  84.             }
  85.         }
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment