• 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;
        }
    };
    
    
  • 相关阅读:
    PHP mysqli_error() 函数
    PHP mysqli_error_list() 函数
    PHP mysqli_errno() 函数
    PHP mysqli_dump_debug_info() 函数
    PHP mysqli_data_seek() 函数
    PHP mysqli_debug() 函数
    PHP mysqli_connect() 函数
    PHP mysqli_connect_errno() 函数
    PHP mysqli_connect_error() 函数
    PHP mysqli_commit() 函数
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/9591200.html
Copyright © 2020-2023  润新知