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++;
               }
           }
        }
  • 相关阅读:
    Alpha项目冲刺_博客链接合集
    项目系统设计
    项目需求分析
    项目选题
    项目展示
    原型设计 + 用户规格说明书
    测试与优化
    结对作业1
    MathExam6317
    js入门基础
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5161434.html
Copyright © 2011-2022 走看看