31. 数组划分

题目

31. 数组划分

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

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

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

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

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

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

解析

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 low=0,high=nums.size()-1;
        
        int ret=0;
        while(low<=high)
        {
            while(low<=high&&nums[high]>=k)
                high--;
            while(low<=high&&nums[low]<k)
                low++;
            if(low<high) //易出现的bug,相等的时候不用做这样的操作!!!
            {
                swap(nums[low],nums[high]);
                high--;
                low++;
            }
        }
        return low;
    }
};

原文链接: https://www.cnblogs.com/ranjiewen/p/9591200.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    31. 数组划分

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/280805

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午5:10
下一篇 2023年2月15日 上午5:10

相关推荐