LintCode 31. partitionArray 数组划分

31. partitionArray 数组划分

题目连接

lintcode 31 partitionArray 数组划分git

题目描述

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

全部小于k的元素移到左边
全部大于等于k的元素移到右边
返回数组划分的位置,即数组中第一个位置 i,知足 nums[i] 大于等于 k。数组

  1. 注意事项

你应该真正的划分数组 nums,而不单单只是计算比 k 小的整数数,若是数组 nums 中的全部元素都比 k 小,则返回 nums.length。测试

  1. 样例

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

  1. 挑战

使用 O(n) 的时间复杂度在数组上进行划分。get

分析

简单来讲就是快排跑一圈it

代码

githubio

class Solution {
public:
    /**
     * @param nums: The integer array you should partition
     * @param k: An integer
     * @return: The index after partition
     */
    int partitionArray(vector<int> &nums, int k) {
        // write your code here
        int i,j;
        int n = nums.size();
        if(n==0) return 0;
        i = 0;
        j=n-1;
        while(i<j)
        {
            while(i<=j && nums[i]<k) i++;
            while(i<=j && nums[j]>=k) j--;
            if(i<j)
            {
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j] = tmp;
                i++;
                j--;
            }
        }
        return i;
    }
};
测试数据
相关文章
相关标签/搜索