首页 > 其他分享 >75.Sort Colors

75.Sort Colors

时间:2022-11-13 21:35:03浏览次数:47  
标签:Sort temp nums int Colors high 75 low white

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放到最前面,2放到最后面

class Solution {

    public void sortColors(int[] nums) {

       if (nums == null || nums.length < 2)

          return;

       int low = 0;

       int high = nums.length - 1;

       for (int i = low; i <= high;) {//注意i要和low,high比较,找到0时,i才加1,找到2时,i不动的

          if (nums[i] == 0) {

              int temp = nums[i];

              nums[i] = nums[low];

              nums[low] = temp;

              i++;//必须要有,否则输入是[0,0]的话,low一直自增nums[low]会越界

              low++;

          } else if (nums[i] == 2) {

              int temp = nums[i];

              nums[i] = nums[high];

              nums[high] = temp;

             high--; 

          } else

             i++;

       }

   }

}

标签:Sort,temp,nums,int,Colors,high,75,low,white
From: https://www.cnblogs.com/MarkLeeBYR/p/16887026.html

相关文章

  • 75.颜色分类
    给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。我们使用整数 0、 1 和 2 ......
  • 791. 自定义字符串排序 ----- 自定义sort、权值排序、计数排序
    给定两个字符串order和s。order的所有单词都是唯一的,并且以前按照一些自定义的顺序排序。对s的字符进行置换,使其与排序的 order 相匹配。更具体地说,如果在 or......
  • Java:自定义排序与sort()函数
    自定义排序与Arrays.sort()本篇题目来源:2022/11/13Leetcode每日一题:https://leetcode.cn/problems/custom-sort-string给定两个字符串order和s。order的所有单词都......
  • AtCoder Beginner Contest 277 F Sorting a Matrix
    SortingaMatrix拓扑序首先可以明确无论怎么交换行列,原本在同一行或者同一列的元素,还是会处于同一行或者同一列条件一每行每行地看,如果能满足从小到大的条件,说明第......
  • Sort List
    SourceSortalinkedlistinO(nlogn)timeusingconstantspacecomplexity.题解1-归并排序(链表长度求中间节点)链表的排序操作,对于常用的排序算法,能达到O(n......
  • Redis有序集合Zset(sorted set)
    Redis有序集合zset与普通集合set非常相似,是一个没有重复元素的字符串集合。不同之处是有序集合的每个成员都关联了一个评分(score),这个评分(score)被用来按照从最低分到最高......
  • #10075. 「一本通 3.2 练习 1」农场派对
    图上每个点有一头牛,现在牛群聚集到点X上聚会,然后又回到各自的点,而且牛只走最短路径问所有最短路中最长的一条(路径包含来回) 正反跑一次 spfa(X), spfa(i), an......
  • CF1750E 题解
    没看懂官方社论,只好自力更生了。我们很容易知道,对于一段区间,其代价就是多余的括号数(左右括号中多出来的括号数)加上不属于多余括号,但没有匹配的左或右括号数。即左括号总量......
  • CF1753D Beach Sol
    看到这种要先满足某个条件才能满足另一个条件的题目,想到图论。假设当前有一个\(c_{i,j}=\)L,\(c_{i,j+1}=\)R,那么如果要把其右移一格就需要满足\(c_{i,j+2}\)当前空出......
  • CS1752 无法嵌入互操作类型“XXXXClass“。请改适用的接口
    在打开.Net项目时应用其他库有的提示这个问题,这个原因是由于引入的属性中,有一个“嵌入操作类型”设置 设置为false即可。......