LintCode-数组划分

题目描述:

  给出一个整数数组nums和一个整数k。划分数组(即移动数组nums中的元素),使得:

    • 所有小于k的元素移到左边
    • 所有大于等于k的元素移到右边

  返回数组划分的位置,即数组中第一个位置i,满足nums[i]大于等于k。

 注意事项

  你应该真正的划分数组nums,而不仅仅只是计算比k小的整数数,如果数组nums中的所有元素都比k小,则返回nums.length。

样例

  给出数组nums=[3,2,2,1]和 k=2,返回 1

 1 public class Solution {
 2     /** 
 3      *@param nums: The integer array you should partition
 4      *@param k: As description
 5      *return: The index after partition
 6      */
 7     public int partitionArray(int[] nums, int k) {
 8        int length = nums.length;
 9          for(int i=0;i<length;i++){
10              if(nums[i]>=k){
11                  for(int j=length-1;j>=i;j--){
12                      if(nums[j]<k){
13                          int temp;
14                          temp = nums[i];
15                          nums[i] = nums[j];
16                          nums[j] = temp;
17                          length = j+1;
18                          break;
19                      }
20                      if(j==i){
21                          return j;
22                      }
23                  }
24              }
25          }
26          return nums.length;
27     }
28 }
原文地址:https://www.cnblogs.com/xiaocainiao2hao/p/5364709.html