Lintcode143 Sort Colors || solution 题解

来源:互联网 发布:淘宝上架商品搜不到 编辑:程序博客网 时间:2024/05/17 19:21

【题目描述】

Given an array ofnobjects withkdifferent colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.

Notice

You are not suppose to use the library's sort function for this problem.

k <= n

给定一个有n个对象(包括k种不同的颜色,并按照1到k进行编号)的数组,将对象进行分类使相同颜色的对象相邻,并按照1,2,...k的顺序进行排序。

【注】:

1、对于这个问题,不应该使用库的排序函数。

2、k<=n

【题目链接】

www.lintcode.com/en/problem/sort-colors-ii/

【题目解析】

利用两个指针的方法,设定pl和pr,左右两个指针,初始位置分别为数组两端,pl = 0, pr = colors.length - 1. 同时,由于题目限制条件,已知min和max,因此可以据此作为比较,来决定如何移动pl,pr两个指针。不断对满足min和max条件的colors进行swap,就可以在in-place的条件下,做到sorting colors,这种算法的空间复杂度为O(1), 而时间复杂度:这种方法的时间复杂度为O(n^2): T(n) = T(n - 2) + n。

【参考答案】

www.jiuzhang.com/solutions/sort-colors-ii/


原创粉丝点击