herrDeng網內搜尋

自訂搜尋

Ads

2025年5月17日 星期六

C/C++/Py3使用荷蘭旗演算3 pointer解Leetcode 75 Sort Colors

C C++ Py3使用荷蘭旗演算3 pointer解Leetcode 75 Sort Colors
一次走訪演算採用於荷蘭旗演算法。
[Py3解請進]
------------
 one-pass algorithm is applied the algorithm for Dutch national flag.
[Python C++採陣列排序速解字串問題Leetcode 451 Sort Characters By Frequency]https://www.youtube.com/watch?v=YfS4OMooZes
  1. class Solution:
  2. def sortColors(self, nums: List[int]) -> None:
  3. """
  4. Do not return anything, modify nums in-place instead.
  5. """
  6. red, white, blue=0, 1, 2
  7. l, m, r=0, 0, len(nums)-1
  8. while m<=r:
  9. x=nums[m]
  10. if x==red:
  11. nums[l], nums[m]=nums[m], nums[l]
  12. l+=1
  13. m+=1
  14. elif x==white:
  15. m+=1
  16. else:
  17. nums[m], nums[r]=nums[r], nums[m]
  18. r-=1
  19.  

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章