• 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;
        }
    }
    
  • 相关阅读:
    MongoDB的基本操作
    Python 进阶 之 协程
    sublime text3 3143 注册码
    git add 文档
    Corosync 配置描述
    Centos 7 设置 DNS
    2017百度春招<度度熊买帽子的问题>
    leetcode 160. Intersection of Two Linked Lists
    leetcode 155. Min Stack
    leetcode 141 142. Linked List Cycle
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13776511.html
Copyright © 2020-2023  润新知