LeetCode Sort Colors

 2023-09-09 阅读 30 评论 0

摘要:1.题目leetcode 5?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,

1.题目


leetcode 5?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.

leetcode121?

2.解决方式


class Solution {
public:void sortColors(int A[], int n) {int left = 0;int right = n - 1;int current = 0;while(current <= right){if(A[current] == 0){swap(A[left], A[current]);++left;++current;}else if(A[current] == 2){swap(A[current], A[right]);--right;}else{++current;}}}
};

思路:首先题目的意思把一个仅仅有0。1,2的乱序数组排序成000111222的次序。由于仅仅有3个数。所以能够用3个变量来交换,把0都换到前面,把2都换到后面。用一个指向开头,用一个指向结尾,把2都换到尾部去。

http://www.waitingfy.com/archives/1634

转载于:https://www.cnblogs.com/llguanli/p/7018376.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/21573.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息