zoukankan      html  css  js  c++  java
  • 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.

    思路:

      双指针看数组,左指针代表0的位置,右指针代表2的位置

    我的代码:

    public class Solution {
        public void sortColors(int[] A) {
            if(A == null || A.length == 0)  return;
            int len = A.length;
            int zeroIndex = 0, curIndex = 0;
            int twoIndex = len - 1;
            while(curIndex <= twoIndex)
            {
                if(A[curIndex] == 1)
                {
                    curIndex++;
                }
                else if(A[curIndex] == 0)
                {
                    int change = A[zeroIndex];
                    A[zeroIndex] = A[curIndex];
                    A[curIndex] = change;
                    curIndex++;
                    zeroIndex++;
                }
                else
                {
                    int change = A[twoIndex];
                    A[twoIndex] = A[curIndex];
                    A[curIndex] = change;
                    twoIndex--;
                }
            }
            return;
        }
    }
    View Code

    他人代码:

    public class Solution {
        public void sortColors(int[] a) {
            if(a == null || a.length <= 1)
                return;
            
            int pl = 0;
            int pr = a.length - 1;
            int i = 0;
            while(i <= pr){
                if(a[i] == 0){
                    swap(a, pl, i);
                    pl++;
                    i++;
                }else if(a[i] == 1){
                    i++;
                }else{
                    swap(a, pr, i);
                    pr--;
                }
            }
        }
        
        private void swap(int[] a, int i, int j){
            int tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }
    }
    View Code

    学习之处:

    • 代码思路一致,里面数值交换,用了两次,应该封装起来更好。
  • 相关阅读:
    使用 VS Code 开发和调试 Burp Suite 扩展
    后渗透神器 Empire 基础用法
    5种语言的按钮事件 断点
    X64下MmIsAddressValid的逆向及内存寻址解析
    x64 内存共享区 KUSER_SHARED_DATA
    内存映射+远线程 调用游戏CALL
    C语言运算符总结
    x32 x64的不同传参方式
    内存占用的一些小问题
    x64分页机制 9
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4319803.html
Copyright © 2011-2022 走看看