zoukankan      html  css  js  c++  java
  • LeetCode(75):Sort Colors

    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.

    Note:

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

    题意:其实可以简单理解为对只包含0,1,2元素的数组进行排序,不能调用排序的库函数。

    思路:由于数组中只包含3个元素,排序的结果为0在数组的左部,1在中部,2在右部。所以可以可以使用双指针分别一个left和一个right分别指向数组的首元素和末尾元素。然后开始遍历,如果遇到0就和left所指的元素交换,left指针加1,如果遇到2就和right所指的元素交换,right指针减1,遇到1就跳过,直到和right相遇。

    代码:

    public void sortColors(int[] nums) {
           int temp=0;
           int left = 0,right=nums.length-1;
           int i=0;
           while(i<=right){
               if(nums[i]==0){
                   temp = nums[i];
                   nums[i] =nums[left];
                   nums[left] = temp;
                   left++;
                   i++;
               }else if(nums[i]==2){
                   temp = nums[i];
                   nums[i] =nums[right];
                   nums[right] = temp;
                   right--;
               }else {
                   i++;
               }
           }
        }
  • 相关阅读:
    启动docker 服务时 虚拟机端口转发 外部无法访问
    ADC滤波处理的十种方法
    ubuntu卸载软件
    Cannot fetch index base URL http://pypi.python.org/simple/
    pip命令详解
    QT入门
    tensorflow学习-第一章
    opencv学习-第一章
    二叉树详解
    C/C++内存地址划分
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5161434.html
Copyright © 2011-2022 走看看