2022年 11月 16日

python–lintcode31.数组划分

描述

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

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

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


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

您在真实的面试中是否遇到过这个题?  

样例

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

挑战

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

OK.本题的算法说白了还是两个指针上的操作,与快排的思想很类似。先在左边找到大于K的值,再在右边找到小于K的值,然后交换他们。不过这一题跟快排的不一样在于当end–的时候,while中的判断有等号。

代码如下:

  1. class Solution:
  2. """
  3. @param nums: The integer array you should partition
  4. @param k: An integer
  5. @return: The index after partition
  6. """
  7. def partitionArray(self, nums, k):
  8. # write your code here
  9. if(nums==None or len(nums)==0):return 0
  10. start,end=0,len(nums)-1
  11. while(start<end):
  12. while(start<end and nums[end]>=k):
  13. end-=1
  14. while(start<end and nums[start]<k):
  15. start+=1
  16. if(nums[start]>=k and nums[end]<k):
  17. temp=nums[start]
  18. nums[start]=nums[end]
  19. nums[end]=temp
  20. start+=1
  21. end-=1
  22. print(nums)
  23. if(nums[start]<k):
  24. return start+1
  25. else:return start
  26. s = Solution()
  27. print(s.partitionArray([9,9,9,8,9,8,7,9,8,8,8,9,8,9,8,8,6,9],9))