LeetCode六月挑战(6.11) Sort Color解题方案

LeetCode六月挑战(6.11) Sort Color

Solution
Given an array with n objects colored red, white or blue, sort them in-place 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.

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

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

思路

(一)直接排序法
直接排序法,由于需要直接在原数组上,首先找到整个数组中最小的数,然后将他放在第一个,然后再找后面未排好数组中最小的数,放在未排序数组的第一位,以此类推。

(二) 设置三个指针,p0指向0的最右边,p2指向2的最左边,p1指向当前位置,如果p1指向的是0和p0交换,然后将p0和p1向右移动,如果p1指向的是2和p2交换,p1向右移动,p2向左移动,是1则继续。

代码

Java代码

第一种

class Solution {
    public void sortColors(int[] nums) {
        for(int i=0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;j++){
                if(nums[i]>nums[j]){
                    int tmp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = tmp;
                }
            }
        }
    }
}

第二种

class Solution {
    public void sortColors(int[] nums) {
        int p2 = nums.length-1;
        int p1=0;
        int p0=0;
        while (p1<=p2){
            if (nums[p1] == 0){
                int tmp = nums[p0];
                nums[p0] = nums[p1];
                nums[p1] = tmp;
                p0++;
                p1++;
            }else if(nums[p1] == 2){
                int tmp = nums[p2];
                nums[p2] = nums[p1];
                nums[p1] = tmp;
                p2--;
            }else{
                p1++;
            }
        }
    }
}

Python代码

第一种

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums);
        for i in range (-1,n):
            for j in range (i+1, n):
                if(nums[i]>nums[j]):
                    tmp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = tmp;

第二种

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        p2 = len(nums)-1;
        p1=0;
        p0=0;
        
        while p1<=p2:
            if nums[p1] == 0:
                nums[p0] , nums[p1] = nums[p1] , nums[p0];
                p1+=1;
                p0+=1;
            elif nums[p1] == 2:
                nums[p1] , nums[p2] = nums[p2] , nums[p1];
                p2-=1;
            else:
                p1+=1;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值