75. Sort Colors

题目要求:

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

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

解题思路:
  • 三个指针进行移动,与目标数字进行比较,然后进行换位置。
  • 示意图
class Solution(object):
    def sortColors(self, nums):
        """
        :param nums: List[int]
        :return: void Do not return anything, modify nums in-place instead.
        """
        def triPartition(nums, target):
            i, j, n = 0, 0, len(nums) - 1

            while j <= n:
                if nums[j] > target:
                    nums[j], nums[n] = nums[n], nums[j]
                    n -= 1
                    
                elif nums[j] < target:
                    nums[i], nums[j] = nums[j], nums[i]
                    j += 1
                    i += 1
                else:
                    j += 1

        triPartition(nums, 1)

if __name__ == "__main__":
    A = [2, 1, 1, 0, 0, 2]
    Solution().sortColors(A)
    print(A)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。