zoukankan      html  css  js  c++  java
  • LeetCode 75 颜色分类

    LeetCode 75 颜色分类

    问题描述:
    给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
    此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
    注意:

    • 不能使用代码库中的排序函数来解决这道题。

    三指针

    • lastRed指向左侧连续的0中最后一个0的位置
    • firstBlue指向右侧连续的2中第一个2的位置
    • curr从lastRed+1开始遍历每个元素,并将0,2添加到左右两侧

    执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
    内存消耗:37.4 MB, 在所有 Java 提交中击败了46.38%的用户

    class Solution {
        public void sortColors(int[] nums) {
            if(nums==null || nums.length==0) {
                return;
            }
            //三指针
            int lastRed = -1, firstBlue = nums.length;
            while(lastRed<firstBlue-1 && nums[lastRed+1]==0) {
                lastRed++;
            }
            while(firstBlue>lastRed+1 && nums[firstBlue-1]==2) {
                firstBlue--;
            }
            int curr = lastRed+1;
            while(lastRed<firstBlue && curr<firstBlue) {
                if(nums[curr]==0) {
                    //交换lastRed+1与curr
                    swap(nums, lastRed+1, curr);
                    lastRed++;
                }
                if(nums[curr]==2) {
                    //交换firstBlue-1与curr
                    swap(nums, firstBlue-1, curr);
                    firstBlue--;
                }
                if(curr==lastRed || curr==firstBlue || nums[curr]==1) {
                    curr++;
                }
            }
            return;
        }
    
        public void swap(int[] nums, int idx1, int idx2) {
            if(nums==null || nums.length==0 || idx1<0 || idx1>=nums.length || idx2<0 || idx2>=nums.length) {
                return;
            }
            //交换idx1、idx2
            int tmp = nums[idx1];
            nums[idx1] = nums[idx2];
            nums[idx2] = tmp;
            return;
        }
    }
    
  • 相关阅读:
    VS中的路径宏
    Eigen3
    Python3.6 import源文件与编译文件的关系
    使用C语言扩展Python3
    mysql.connector 事务总结
    C++ -- STL泛型编程(一)之vector
    JSP -- include指令与include动作的区别
    Rails -- 关于Migration
    ruby -- 进阶学习(八)自定义方法route配置
    ruby -- 进阶学习(七)strong parameters之permitted.has_key
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13776511.html
Copyright © 2011-2022 走看看