[LeetCode]Sort Colors

本文介绍了一种不使用库排序函数的三色排序算法,通过两个指针实现0、1、2三种颜色(分别用整数0、1、2表示)的数组排序。此算法能够有效地将相同颜色的对象相邻排列,并按红、白、蓝的顺序组织。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Note:

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

题意:将一堆乱序的0,1,2组成的数组将其他排成0,1,2有序的

题解:采用2个指针,start记录0前面的数为止,end为2的为止,遍历数组遇到0,与前面的数交换,遇到2与后面的数交换。

code:

package com.leetcode.mair;

public class Solution75{
	
	public void sortColors(int[] nums) {
    
		int start=0,end = nums.length-1;
		
		if(nums.length<2)
			return;
		
		for(int i=0; i<nums.length; i++){
			
			if(nums[i] == 0){
			   swap(nums, start++, i);
			  
			}else if(nums[i] == 2){ // i--,交换后继续比较,避免未比较的数
				swap(nums, end--, i--);
			}
		}
    }
	public void swap(int nums[],int x,int y){
		  int temp = nums[x];
		   nums[x] = nums[y];
		   nums[y] = temp;
	}
	public static void main(String[] args) {
		
		int nums[] = {2,2};
		new Solution75().sortColors(nums);
		for(int i=0; i<nums.length; i++){
			System.out.print(nums[i]+" ");
		}
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值