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++;
               }
           }
        }
  • 相关阅读:
    MFC深入浅出读书笔记第一部分
    给对话框添加背景
    相对路径与绝对路径之比较
    线程同步的四种方式以及串口通信
    DirectShow简单入门程序
    两个对话框之间的通信
    websphere部署war包
    Struts2的基础知识
    iBatis基础知识
    Struts1的基础知识
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5161434.html
Copyright © 2011-2022 走看看