zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第八章 数组和矩阵问题 数组的partition 调整

    题目

    数组的partition 调整
    

    java代码

    package com.lizhouwei.chapter8;
    
    /**
     * @Description: 数组的partition 调整
     * @Author: lizhouwei
     * @CreateDate: 2018/5/9 21:24
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter8_23 {
        public void leftUnique(int[] arr) {
            if (arr == null || arr.length < 2) {
                return;
            }
            int left = 0;
            int right = 1;
            while (right < arr.length) {
                if (arr[left] != arr[right++]) {
                    swap(arr, ++left, right - 1);
                }
            }
        }
    
        public void sort(int[] arr) {
            int left = -1;
            int index = 0;
            int right = arr.length - 1;
            while (index < right) {
                if (arr[index] == 0) {
                    swap(arr, index++, ++left);
                } else if (arr[index] == 2) {
                    swap(arr, index, right--);
                } else {
                    index++;
                }
            }
        }
    
    
        public void swap(int[] arr, int a, int b) {
            int temp = arr[a];
            arr[a] = arr[b];
            arr[b] = temp;
        }
    
        //测试
        public static void main(String[] args) {
            Chapter8_23 chapter = new Chapter8_23();
            int[] arr = {1, 2, 2, 2, 3, 3, 4, 5, 6, 6, 7, 7, 8, 8, 8, 9};
            chapter.leftUnique(arr);
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
            }
            System.out.println();
            int[] arr1 = {1, 2, 0, 0, 1, 2, 2, 1, 0, 0};
            chapter.sort(arr1);
            for (int i = 0; i < arr1.length; i++) {
                System.out.print(arr1[i] + " ");
            }
        }
    
    }
    
    

    结果

  • 相关阅读:
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    iOS开发系列--IOS程序开发概览
    iOS开发系列—Objective-C之Foundation框架
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/9016860.html
Copyright © 2011-2022 走看看