Lintcode31 Partition Array solution題解

【題目描述】

Given an array nums of integers and an int k, partition the array (i.e move the elements in "nums") such that:All elements < k are moved to the left;All elements >= k are moved to the right;Return the partitioning index, i.e the first index i 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

給出一個整數數組 nums 和一個整數 k。劃分數組(即移動數組 nums 中的元素),使得:所有小於k的元素移到左邊;所有大於等於k的元素移到右邊;返回數組劃分的位置,即數組中第一個位置 i,滿足 nums[i] 大於等於 k。

注意:你應該真正的劃分數組 nums,而不僅僅只是計算比 k 小的整數數,如果數組 nums 中的所有元素都比 k 小,則返回 nums.length。

【題目鏈接】

http://www.lintcode.com/en/problem/partition-array/

【題目解析】

容易想到的一個辦法是自左向右遍歷,使用right保存大於等於 k 的索引,i則爲當前遍歷元素的索引,總是保持i >= right, 那麼最後返回的right即爲所求。

自左向右遍歷,遇到小於 k 的元素時即和right索引處元素交換,並自增right指向下一個元素,這樣就能保證right之前的元素一定小於 k. 注意if判斷條件中i >= right不能是i > right, 否則需要對特殊情況如全小於 k 時的考慮,而且即使考慮了這一特殊情況也可能存在其他 bug. 具體是什麼 bug 呢?歡迎提出你的分析意見~

有了解過 Quick Sort 的做這道題自然是分分鐘的事,使用左右兩根指針 left,right 分別代表小於、大於等於 k 的索引,左右同時開工,直至 left>right.

大循環能正常進行的條件爲 left<=right, 對於左邊索引,向右搜索直到找到小於 k 的索引爲止;對於右邊索引,則向左搜索直到找到大於等於 k 的索引爲止。注意在使用while循環時務必進行越界檢查!

找到不滿足條件的索引時即交換其值,並遞增left, 遞減right. 緊接着進行下一次循環。最後返回left即可,當nums爲空時包含在left = 0之中,不必單獨特殊考慮,所以應返回left而不是right.

【參考答案】

http://www.jiuzhang.com/solutions/partition-array/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章