LintCode问题图解-4

本文准备讲解1个简单的算法编程问题, 这个算法编程问题来自LintCode平台。不了解.LintCode平台的读者可以阅读笔者文章(在线编程平台推荐-LeetCode)。问题的英文版本描述如下:

Partition Array

Given an array nums of integers and an int k, partition the array (i.e move the elements in "nums") such that:

All elements <are moved to the left

All elements >=are moved to the right

Return the partitioning index, i.e the first index nums[i] >=k.

Notice

You should do really partition in array nums instead of just counting the numbers of integers smaller than k.

If all elements in nums are smaller than k, then return nums.length

Example

If nums =[3,2,2,1] and k=2, a valid answer is1.

问题的中文版本描述:

切分数组

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

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

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

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

注意事项

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

样例

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

标准的算法逐个处理数组的元素,将需要调换位置的元素调换位置。方案参见下图:


LintCode问题图解-4_第1张图片
标准的方案

现在公布1种高效的算法方案,该方案对应 LintCode 平台表现更强。不仅速度更快,而且已做排序。


LintCode问题图解-4_第2张图片
高效的算法方案

你可能感兴趣的:(LintCode问题图解-4)